2015-09-07 131 views
0

我是GO語言的新手。 試圖通過構建真正的Web應用程序來學習GO。 我正在使用狂歡框架。嘗試將字符串轉換爲實例變量

這裏是我的資源路線:

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.ReadAll( 「用戶」)

這是我的資源控制器(它只是一個虛擬的動作):

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 
} 

我想獲取用戶實例通過轉換結構資源字符串來對象調用全部函數。

和錯誤:

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

我是新來走請不要評判我:)

+3

這是你正在嘗試做什麼? http://stackoverflow.com/questions/23030884/is-there-a-way-to-create-an-instance-of-a-struct-from-a-string – ANisus

回答

2

你的問題是在這裏:

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) 
+0

這就是我現在的代碼:http ://joxi.ru/0KAgEEehM0QWml和錯誤:http://joxi.ru/9E2pMMKFz0lZAY – num8er

+1

這仍然不能工作,因爲你不能調用'interface {}'上的方法,(因爲它沒有方法)。你仍然需要[鍵入斷言](http://golang.org/ref/spec#Type_assertions)來這樣做,如果你願意,沒有必要試圖從一個字符串實例化一個類型。這是在動態語言中運行良好的東西,而不是在Go中。 –

+0

非常感謝你!通過使用switch..case製作。 – num8er