使用反射(reflect)从空指针定义的类型创建一个新的结构体。

huangapple go评论74阅读模式
英文:

Create a new struct with reflect from type defined by a nil pointer

问题

我可以帮你翻译代码部分,以下是翻译好的内容:

我想知道是否可以通过使用reflect.New()从由nil指针指定的类型中分配一个结构体。

type SomeType struct{
   A int
}

sometype := (*SomeType)(nil)

v := reflect.valueOf(sometype)
// 我想根据指针定义的类型分配一个新的结构体
// newA := reflect.New(...)
//
newA.A = 3

我应该如何做到这一点?

英文:

I would like know if it is possible to allocate a struct from a type specified by a nil pointer by using reflect.New()

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

How should I do this ?

答案1

得分: 12

使用reflect.Type.Elem()

s := (*SomeType)(nil)
t := reflect.TypeOf(s).Elem()

v := reflect.New(t)
sp := (*SomeType)(unsafe.Pointer(v.Pointer()))
sp.A = 3

Playground: http://play.golang.org/p/Qq8eo-W2yq

编辑:下面的评论中,Elwinar 指出可以使用 reflect.Indirect() 来获取结构体,而不需要使用 unsafe.Pointer

s := (*SomeType)(nil)
t := reflect.TypeOf(s).Elem()

ss := reflect.Indirect(reflect.New(t)).Interface().(SomeType)
ss.A = 3

Playground: http://play.golang.org/p/z5xgEMR_Vx

英文:

Use reflect.Type.Elem():

s := (*SomeType)(nil)
t := reflect.TypeOf(s).Elem()

v := reflect.New(t)
sp := (*SomeType)(unsafe.Pointer(v.Pointer()))
sp.A = 3

Playground: http://play.golang.org/p/Qq8eo-W2yq

EDIT: Elwinar in comments below pointed out that you can get the struct without unsafe.Pointer by using reflect.Indirect():

s := (*SomeType)(nil)
t := reflect.TypeOf(s).Elem()

ss := reflect.Indirect(reflect.New(t)).Interface().(SomeType)
ss.A = 3

Playground: http://play.golang.org/p/z5xgEMR_Vx

huangapple
  • 本文由 发表于 2014年12月5日 21:01:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/27316508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定