【问题标题】:Getting reflect.Type of structure获取反射。结构类型
【发布时间】:2015-09-13 11:48:34
【问题描述】:

Go 中是否可以从结构本身检索 reflect.Type?

伪:

type MyStruct struct {
  Name string
}

type := reflect.TypeOf(MyStruct)

之后是否可以制作该类型的切片?

更新: 我知道reflect.TypeOf((*t1)(nil)).Elem() 这个问题的解决方案。我正在寻找一个更好的解决方案,因为这在我看来非常不友好。我会试着解释一下情况。

在开发数据库模型之上的“通用”数据服务时,我想做一些类似的事情:

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

DataService 能够使用该模型进行查找、插入等操作。因此我需要传递结构,以便模型可以正确使用(例如与 http 服务器)。

第二部分是必需的,因为Find 应该返回找到的对象的切片。

因为我使用的是 Mongo,所以在 db.Collection

中没有像 schema 这样可用的东西

【问题讨论】:

标签: reflection go


【解决方案1】:

第一部分:与in golang, is is possible get reflect.Type from the type itself? from name as string?重复

对于第二部分:之后制作该类型的切片:

您可以使用Type.SliceOf()获取元素类型为您已有的切片的Type,您可以使用reflect.MakeSlice()函数创建该类型的切片。它返回一个Value,您可以使用它的Value.Interface() 方法获取一个interface{},如果您需要将结果作为[]MyStruct 的类型,您可以在其上使用type assertion

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} {} {} {} {} {} {} {} {} {}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-27
    • 2017-11-12
    • 1970-01-01
    • 2013-12-16
    • 2012-04-03
    • 1970-01-01
    • 2017-07-06
    • 2010-12-20
    相关资源
    最近更新 更多