2015-06-26 27 views
1

是否有可能在Go中從結構本身檢索reflect.Type?正在獲取反射。結構的類型

僞:

type MyStruct struct { 
    Name string 
} 

type := reflect.TypeOf(MyStruct) 

,並有可能使這種類型的片之後?

更新: 我知道reflect.TypeOf((*t1)(nil)).Elem()這個問題的解決方案。我正在尋找更好的解決方案,因爲這在我看來很不友好。我會盡力解釋這種情況。

在發展上述數據庫模型「通用」的DataService,我想要做的事,如:

ds := NewDataService(db.Collection("MyStruct"), MyStruct) 

DataService的地方是能夠做到查找,插入等使用模式。因此,我需要傳遞結構以便模型可以正確使用(例如,使用http服務器)。

第二部分是需要的Find應該返回找到的對象片。

因爲我使用蒙戈,有沒有像模式可用db.Collection

+1

[在golang中可能的重複,是可能的從類型本身得到反映。從名稱字符串?](http://stackoverflow.com/questions/6390585/in-golang-is-is-possible-get-reflect-type-from-the-type-itself-from-name-as-st ) –

+0

我更新了問題 – Gelidus

回答

1

在第一部分中:它是in golang, is is possible get reflect.Type from the type itself? from name as string?

重複對於第二部分:讓片之後:

您可以使用Type.SliceOf()獲取其元素類型爲Type.SliceOf()的片的Type,並且您可以使用reflect.MakeSlice()函數來創建這種類型的切片。它返回一個Value,則可以使用其Value.Interface()方法得到interface{}可以在其上使用type assertion如果需要的結果作爲一種類型的[]MyStruct

tt := reflect.TypeOf((*MyStruct)(nil)).Elem() 
fmt.Println(tt) 

ms := reflect.MakeSlice(reflect.SliceOf(tt), 10, 20).Interface().([]MyStruct) 
ms[0].Name="test" 
fmt.Println(ms) 

輸出(Go Playground):

main.MyStruct 
[{test} {} {} {} {} {} {} {} {} {}]