【问题标题】:Trying to convert string to instance variable试图将字符串转换为实例变量
【发布时间】:2020-04-23 05:21:11
【问题描述】:

我是 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")

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

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
}

我正在尝试通过将 资源字符串 转换为对象以调用 All 函数来获取用户结构的实例。

和错误:

不能使用资源(类型字符串)作为反射类型。在参数中键入 reflect.New:字符串没有实现 reflect.Type(缺少 Align 方法)

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

【问题讨论】:

标签: rest go controller resources revel


【解决方案1】:

你的问题在这里:

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)

【讨论】:

  • 这是我的代码现在的样子:joxi.ru/0KAgEEehM0QWml 和错误:joxi.ru/9E2pMMKFz0lZAY
  • 这仍然行不通,因为您不能在interface{} 上调用方法,(因为它没有方法)。你仍然需要type assert 这样做,如果你愿意,尝试从字符串实例化一个类型是没有意义的。这在动态语言中可以很好地工作,而不是在 Go 中。
猜你喜欢
  • 2015-06-07
  • 2010-09-30
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-27
相关资源
最近更新 更多