尝试将字符串转换为实例变量
I'm new to GO language. Trying to learn GO by building real web application. I'm using revel framework.
And here is my resource routes:
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
for example:
GET /resource/users calls Resource.ReadAll("users")
And this is my Resource controller (it's just a dummy actions for now):
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
}
I'm trying get instance of Users struct by converting resource string to object to call All function.
and the error:
cannot use resource (type string) as type reflect.Type in argument to reflect.New: string does not implement reflect.Type (missing Align method)
I'm new to GO please don't judge me :)
我是GO语言的新手。 尝试通过构建真实的Web应用程序来学习GO。 我正在使用 启示框架。 p>
这是我的资源路线: p>
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
code>
例如: p>
GET / resource / users调用Resource.ReadAll(“ users”) p>
这是我的资源控制器(目前只是一个虚拟操作): p>
type资源结构{
* revel.Controller
}
type用户结构{\ n ID int
用户名字符串
密码字符串
}
type用户结构{}
func(u Users)All()字符串{
返回“全部”
}
func(c 资源)ReadAll(资源字符串)revel.Res ult {
fmt.Printf(“ GET%s”,资源)
模型:= reflect.New(资源)
fmt.Println(model.All())
返回nil
}
代码> pre>
我正在尝试通过将资源字符串 strong>转换为对象以调用 All strong>函数来获取Users结构的实例。
p>
和错误: p>
不能使用资源(类型字符串)作为反射类型。 新增:字符串未实现reflect.Type(缺少Align
方法) p>
blockquote>
我是GO新手,请不要判断我:) p >
div>
Your problem is here:
model := reflect.New(resource)
You can't instantiate a type from a string that way. You need to either use a switch there and do stuff depending on the model:
switch resource {
case "users":
model := &Users{}
fmt.Println(model.All())
case "posts":
// ...
}
Or use reflect
correctly. Something like:
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)