Reflection 使用由nil指针定义的reflect from类型创建新结构
我想知道是否可以使用Reflection 使用由nil指针定义的reflect from类型创建新结构,reflection,go,Reflection,Go,我想知道是否可以使用reflect.New() 我应该怎么做?使用: 游乐场: EDIT:下面评论中的Elwinar指出,通过使用reflect.Indirect(),可以在不使用不安全的.Pointer的情况下获取结构: 操场:这是唯一的可能吗?有没有不使用不安全软件包的方法?为了避免不得不使用unsafe软件包,您应该使用reflect.Indirect方法。一行:reflect.Indirect(reflect.New(reflect.TypeOf(sometype.Elem())).In
reflect.New()
我应该怎么做?使用:
游乐场:
EDIT:下面评论中的Elwinar指出,通过使用reflect.Indirect()
,可以在不使用不安全的.Pointer
的情况下获取结构:
操场:这是唯一的可能吗?有没有不使用不安全软件包的方法?为了避免不得不使用
unsafe
软件包,您应该使用reflect.Indirect
方法。一行:reflect.Indirect(reflect.New(reflect.TypeOf(sometype.Elem())).Interface()(sometype)
是否继续执行相同的操作,但从接口开始?我的意思是你有一个实现I接口的对象A。我从接口开始,我想创建实现接口的相同底层对象,我使用reflect?
type SomeType struct{
A int
}
sometype := (*SomeType)(nil)
v := reflect.valueOf(sometype)
// I would like to allocate a new struct based on the type defined by the pointer
// newA := reflect.New(...)
//
newA.A = 3
s := (*SomeType)(nil)
t := reflect.TypeOf(s).Elem()
v := reflect.New(t)
sp := (*SomeType)(unsafe.Pointer(v.Pointer()))
sp.A = 3
s := (*SomeType)(nil)
t := reflect.TypeOf(s).Elem()
ss := reflect.Indirect(reflect.New(t)).Interface().(SomeType)
ss.A = 3