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! : )
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
.
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.
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.
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.