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

Trying to convert string to instance variable

我是 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 函数来获取 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)