尝试将字符串转换为实例变量

问题描述:

我是GO语言的新手。 试图通过构建真正的Web应用程序来学习GO。 我正在使用狂欢框架。尝试将字符串转换为实例变量

这里是我的资源路线:

GET  /resource/:resource      Resource.ReadAll 
GET  /resource/:resource/:id     Resource.Read 
POST /resource/:resource      Resource.Create 
PUT  /resource/:resource/:id     Resource.Update 
DELETE /resource/:resource/:id     Resource.Delete 

例如:

GET /资源/用户调用Resource.ReadAll( “用户”)

这是我的资源控制器(它只是一个虚拟的动作):

type Resource struct { 
    *revel.Controller 
} 

type User struct { 
    Id int 
    Username string 
    Password string 
} 

type Users struct {} 

func (u Users) All() string { 
     return "All" 
} 

func (c Resource) ReadAll(resource string) revel.Result { 
    fmt.Printf("GET %s", resource) 
    model := reflect.New(resource) 
    fmt.Println(model.All()) 
    return nil 
} 

我想获取用户实例通过转换结构资源字符串来对象调用全部函数。

和错误:

cannot use resource (type string) as type reflect.Type in argument to reflect.New: string does not implement reflect.Type (missing Align method)

我是新来走请不要评判我:)

+3

这是你正在尝试做什么? http://stackoverflow.com/questions/23030884/is-there-a-way-to-create-an-instance-of-a-struct-from-a-string – ANisus

你的问题是在这里:

model := reflect.New(resource) 

你不能以这种方式从字符串中实例化一个类型。您需要或者有使用一个开关,并根据模型做的东西:

switch resource { 
case "users": 
    model := &Users{} 
    fmt.Println(model.All()) 
case "posts": 
    // ... 
} 

或正确使用reflect。例如:

var types = map[string]reflect.Type{ 
    "users": reflect.TypeOf(Users{}) // Or &Users{}. 
} 

// ... 

model := reflect.New(types[resource]) 
res := model.MethodByName("All").Call(nil) 
fmt.Println(res) 
+0

这就是我现在的代码:http ://joxi.ru/0KAgEEehM0QWml和错误:http://joxi.ru/9E2pMMKFz0lZAY – num8er

+1

这仍然不能工作,因为你不能调用'interface {}'上的方法,(因为它没有方法)。你仍然需要[键入断言](http://golang.org/ref/spec#Type_assertions)来这样做,如果你愿意,没有必要试图从一个字符串实例化一个类型。这是在动态语言中运行良好的东西,而不是在Go中。 –

+0

非常感谢你!通过使用switch..case制作。 – num8er