Reputation: 2150
Is it possible in Go to retrieve reflect.Type from structure itself?
pseudo:
type MyStruct struct {
Name string
}
type := reflect.TypeOf(MyStruct)
And is it possible to make slice of that type afterwards?
Update:
I am aware of reflect.TypeOf((*t1)(nil)).Elem()
solution for this problem. I am looking for a better solution to this, as this seems to me pretty unfriendly. I'll try to explain the situation.
While developing 'generic' dataservice above database model, I want to do something like:
ds := NewDataService(db.Collection("MyStruct"), MyStruct)
where DataService is able to do Find, Insert etc. using that model. Therefore I need to pass the structure so the model can be used correctly (for example with http server).
The second part is needed as Find
should return slice of found objects.
Because I am using Mongo, there is nothing like schema available within db.Collection
Upvotes: 1
Views: 102
Reputation: 418585
For the first part: it is a duplicate of in golang, is is possible get reflect.Type from the type itself? from name as string?
For the second part: make slice of that type afterwards:
You can get the Type
of the slice whose elements' type is what you already have by using Type.SliceOf()
, and you can use the reflect.MakeSlice()
function to create a slice of such type. It returns a Value
, you can use its Value.Interface()
method to obtain an interface{}
on which you can use type assertion if you need the result as a type of []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)
Output (Go Playground):
main.MyStruct
[{test} {} {} {} {} {} {} {} {} {}]
Upvotes: 1