英文:
Initialising multiple structs in go
问题
<!-- language-all: lang-go -->
我需要初始化多个结构体变量
假设结构体如下:
type Foo struct {
a int
b *Foo
}
假设我想要初始化5个这样的结构体变量。有没有比下面的代码片段多次重复更简洁的方法?
s0 := &Foo{}
s1 := &Foo{}
s2 := &Foo{}
类似于
var a, b, c, d int
谢谢帮助!: )
英文:
<!-- language-all: lang-go -->
I need to initialise multiple struct variables
Let's say the struct is
type Foo struct {
a int
b *Foo
}
And let's say I want to initialise 5 of those. Is there a cleaner way of doing it than below fragment multiple times?
s0 := &Foo{}
s1 := &Foo{}
s2 := &Foo{}
something like
var a, b, c, d int
Thanks for help! : )
答案1
得分: 7
你可以将它们放在一条语句中,如果你愿意的话:
s0, s1, s2 := new(Foo), new(Foo), new(Foo)
你也可以这样做:
var s0, s1, s2 Foo
然后依次使用 &s0
、&s1
和 &s2
,而不是 s0
、s1
和 s2
。
英文:
You can put them in one statement if you want:
s0, s1, s2 := new(Foo), new(Foo), new(Foo)
You can also do this:
var s0, s1, s2 Foo
And then use &s0
, &s1
and &s2
subsequently instead of s0
, s1
and s2
.
答案2
得分: 1
你需要指针吗?如果不需要,那么你在问题中已经得到了答案。只需在变量声明中将int
替换为你的类型即可。
英文:
Do you require pointers? If not, the you have exactly the answer in your question. Just replace int
with your type in your var statement.
答案3
得分: 1
你可以使用循环和切片来分配5个foos。
foos := make([]*Foo, 5)
for i := range foos {
foos[i] = &Foo{}
}
另一种方法是使用数组:
foos := [5]Foo{}
然后使用&foos[0]
、&foos[1]
等作为指针。
英文:
You can use a loop and a slice to allocate 5 foos.
foos := make([]*Foo, 5)
for i := range foos {
foos[i] = &Foo{}
}
An alternative would be to use an array:
foos := [5]Foo{}
and use &foos[0], &foos[1], ... as your pointers.
答案4
得分: 0
首选的方法是将其包装在一个工厂函数中(无论如何,你都应该这样做):
func NewFoos(count int) []foo {
return make([]foo, count, count)
}
这样做既简洁又清晰:它允许你轻松地初始化所需数量的对象。
英文:
Preferred way would be to wrap this in a factory function (which you should do anyhow):
func NewFoos(count int) []foo {
return make([]foo, count, count)
}
This is clean, concise and soft: Allows you to easily initialize as many or as few as you need.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论