我是 GO 語言的新手。嘗試通過構建真實的 Web 應用程序來學習 GO。我正在使用 Revel 框架。這是我的資源路線:GET /resource/:resource Resource.ReadAllGET /resource/:resource/:id Resource.ReadPOST /resource/:resource Resource.CreatePUT /resource/:resource/:id Resource.UpdateDELETE /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.Type in參數來reflect.New:字符串沒有實現reflect.Type(缺少Align方法)我是 GO 新手,請不要評判我 :)
1 回答

忽然笑
TA貢獻1806條經驗 獲得超5個贊
你的問題在這里:
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)
- 1 回答
- 0 關注
- 159 瀏覽
添加回答
舉報
0/150
提交
取消