seaguest
seaguest

Reputation: 2630

Should we prefer to using the struct pointer for the list in Golang?

I have a question regarding the array of struct, if we should prefer to using the struct pointer or not.

Let's say we have Item and Cart which contains an array of Items.

type Item struct {
    Id          string
    Name        string
    Price       string
}

type Cart1 struct {
    Id          string
    Items       []Item
}

or

type Cart2 struct {
    Id          string
    Items       []*Item
}

I heard that when we append a struct to a struct list, golang will make a copy and add it to list, this is not necessary, so we should use list of struct pointer, is that true?

could anyone clarify?

Upvotes: 2

Views: 4035

Answers (3)

creker
creker

Reputation: 9570

As I understand your question, you problem is not memory consumption but unnecessary copying of structs.

Everything in Go is passed by value. If you have a slice of structs and you append a new struct Go will make a copy. Depending on the size of the struct it may be too much. Instead you may choose to use a slice of pointers to structs. That way when you append Go will make a copy of a pointer.

That might be cheaper but it also may complicate the code that will access the slice. Because now you have shared mutable state which is a problem especially in Go where you can't have a const pointer and anyone could modify the struct. Pointers are also prone to nil dereference errors.

Which one you choose is entirely up to you. There's no single "Go way" here.

Upvotes: 1

Uvelichitel
Uvelichitel

Reputation: 8490

You are right in your assumption - any(not only append()) function application copy by value provided arguments in Go. But how slice of pointer would reduce memory consumption? You should store actual struct plus reference to it in memory. Referencing is more about access control.

foo := cart1.Items[0]
foo.Name := "foo" //will not change cart1
//but in pointer case
bar := cart2.Items[0]
bar.Name := "bar" //will change cart2.Items[0].Name to "bar"

Upvotes: 3

Plato
Plato

Reputation: 11052

Go Arrays are passed by value, go Slices are passed by reference like a pointer. In fact slices include a pointer as part of their internal data type. Since your cart will have a variable number of items, just use []Item.

See this effective go reference

BTW if the slice has capacity 4 and you append something 5th thing to it, Go doubles the capacity, so it's not like every single addition will assign memory

Upvotes: 1

Related Questions