1

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

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Sorry Dustin, you're right. The wording of your answer confused me, and I've removed the comment.
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.

Comments

0

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.

2 Comments

There is no need for the loop. Just return make([]foo, count) is sufficient. make already constructs the elements of the slice to their zero values.
I thought about your point after I posted this - didn't get a chance to test it. At the time I thought that maybe makewould just allocate the memory but not the foo instance. I edited, taking your word for it.:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.