Should the parent be reference or inner slice to avoid copying over the wire

Hi,

I am trying to understand what would be the best way to go when it comes to using a type User that contains slice of other types Comment or others. Each example have their own questions below.

Thanks

type User struct {
	Name     string
	Age      int
	Salary   float64
	Username string
	Password string
	Comments []Comment // Or *Comment
	// SomeOtherSlices []Other
}

type Comment struct {
	ID        string
	Message   string
	CreatedAt time.Time
	DeletedAt *time.Time
}

// Would inner `Comments` be copied everytime I passed returned value around?
func storageV1() *User {
	return &User{
		// ...
		Comments: []Comment{{
			// ..
		}},
	}
}

// Given the returned value is a copy and the inner `Comments` a pointer, would inner `Comments` be copied everytime I passed returned value around?
func storageV2() User {
	return User{
		// ...
		Comments: []*Comment{{ // If the field was a pointer
			// ..
		}},
	}
}

// I am not sure if both have to be pointer?
func storageV3() *User {
	return &User{
		// ...
		Comments: []*Comment{{ // If the field was a pointer
			// ..
		}},
	}
}

The slice contents do not get copied unless you work to do it by calling copy(). The slice value is copied, but that’s not much more than a pointer. You don’t gain anything in regard to preventing copying by passing a pointer to a slice.

@mje

If I understand it right, what you are saying is that; going with storageV1 makes more sense compared to other two because, neither User’s basic properties nor Comments property would be copied in memory no matter how many times *User is passed over the wire from one place to another.

Correct

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