gpt4 book ai didi

rest - 试图将字符串转换为实例变量

转载 作者:IT王子 更新时间:2023-10-29 02:05:02 24 4
gpt4 key购买 nike

我是 GO 语言的新手。尝试通过构建真正的 Web 应用程序来学习 GO。我正在使用 revel 框架。

这是我的资源路线:

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/users 调用 Resource.ReadAll("users")

这是我的资源 Controller (现在只是一个虚拟操作):

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
}

我正在尝试通过将 resource string 转换为对象以调用 All 函数来获取 Users 结构的实例。

和错误:

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

我是 GO 新手,请不要评判我 :)

最佳答案

你的问题在这里:

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)

关于rest - 试图将字符串转换为实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32436827/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com