Embedding pointer or not?

As seen below Container struct has two non-pointer embedded fields - A and []B. It might contain a lot of data.

If I change my code and pass *Container to do() function, it will avoid re-copying so the app should be memory efficient. However, what I am trying to understand is that, should I also change embedded fields A and []B as *A and []*B as well to avoid copying or are they already copied when *Container passed?

Thanks

package main

type Container struct {
	ID int
	// ... more fields
	A A // or *A?
	B []B // or []*B?
}

type A struct {
	ID int
	// ... more fields
}

type B struct {
	ID int
	// ... more fields
}

func main() {
	c := Container{
		ID: 1,
		A:  A{
			ID: 491,
		},
		B:  []B{
			{
				ID: 87,
			},
		},
	}
	
	do(c)
}

func do(c Container) {
	// Do something with `c` but modification is not required.
}

You don’t need to change field A and []B to pointer type to avoid memory copying. When you passing *Container to do() function, it’s the address of Container object that’s passed to the function.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.