How can I initialize a type that is a pointer to a struct in Go?

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

How can I initialize a type that is a pointer to a struct in Go?

问题

例如:

type Foo struct {
        x int
}
var foo *Foo = &Foo{5}

type Bar *struct {
        x int
}
var bar Bar = ??

我该如何初始化 bar

我意识到有一个解决方法:

type Bar *Foo
var bar Bar = &Foo{5}

但我想避免这种方法。

英文:

For example:

type Foo struct {
        x int
}
var foo *Foo = &Foo{5}

type Bar *struct {
        x int
}
var bar Bar = ??

How can I initialize bar?

I realize there is a workaround:

type Bar *Foo
var bar Bar = &Foo{5}

But I would like to avoid that.

答案1

得分: 5

type Bar *struct这种形式几乎没有理由使用。这个类型是一个指向匿名结构体的指针,所以你必须用一个匿名结构体来初始化它(或者如你指出的,一个等效的可转换的结构体类型)。

var b Bar = &struct{x int}{}
// 或者
b := Bar(&Foo{})

这个声明本质上与

type Bar *Foo

是相同的,这可能会更清楚你想要做什么。

但是再次强调,这不是惯用的写法,在团队环境或公共接口中使用这种写法可能会遇到阻力(例如,我个人不会通过这种写法进行代码审查)。

英文:

There's [probably] no reason to ever use the form type Bar *struct. The type is a pointer to an anonymous struct, so you have to initialize it with an anonymous struct (or as you point out, an equivalent, convertible struct type).

var b Bar = &struct{x int}{}
// or
b := Bar(&Foo{})

The declaration is essentially the same is

type Bar *Foo

Which may make it a little more clear what you're trying to do.

But again, this is non-idiomatic, and you will probably encounter resistance using this in a team setting or public interface (i.e. I personally wouldn't pass this is code review)

huangapple
  • 本文由 发表于 2015年3月20日 02:50:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/29152710.html
匿名

发表评论

匿名网友

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

确定