Mat*_*att 1 struct types pointers initialization go
例如:
type Foo struct {
x int
}
var foo *Foo = &Foo{5}
type Bar *struct {
x int
}
var bar Bar = ??
Run Code Online (Sandbox Code Playgroud)
我该如何初始化bar?
我意识到有一个解决方法:
type Bar *Foo
var bar Bar = &Foo{5}
Run Code Online (Sandbox Code Playgroud)
但我想避免这种情况.
[可能]没有理由使用该表格type Bar *struct.该类型是一个指向匿名结构的指针,因此您必须使用匿名结构初始化它(或者当您指出时,它是一个等效的可转换结构类型).
var b Bar = &struct{x int}{}
// or
b := Bar(&Foo{})
Run Code Online (Sandbox Code Playgroud)
声明基本上是相同的
type Bar *Foo
Run Code Online (Sandbox Code Playgroud)
这可能会让你更清楚自己想做什么.
但同样,这是非惯用的,你可能会在团队设置或公共界面中遇到阻力(即我个人不会通过这是代码审查)