简体   繁体   English

得到反映结构类型

[英]Getting reflect.Type of structure

Is it possible in Go to retrieve reflect.Type from structure itself? Go中是否可以从结构本身中检索reflect.Type?

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. 更新:我知道此问题的reflect.TypeOf((*t1)(nil)).Elem()解决方案。 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. DataService可以使用该模型执行“查找”,“插入”等操作。 Therefore I need to pass the structure so the model can be used correctly (for example with http server). 因此,我需要传递结构,以便可以正确使用模型(例如,使用http服务器)。

The second part is needed as Find should return slice of found objects. 第二部分是必需的,因为Find应该返回找到的对象的切片。

Because I am using Mongo, there is nothing like schema available within db.Collection 因为我使用的是Mongo,所以db.Collection中没有类似架构的 东西

For the first part: it is a duplicate of in golang, is is possible get reflect.Type from the type itself? 对于第一部分:它是golang中的重复项,是否可以从类型本身中获取reflect.Type? 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. 您可以使用Type.SliceOf()获得其元素类型已经为您所拥有的切片的Type ,并且可以使用reflect.MakeSlice()函数来创建此类切片。 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 : 它返回一个Value ,您可以使用其Value.Interface()方法获取一个interface{} ,如果需要将结果作为[]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} {} {} {} {} {} {} {} {} {}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM