Getters, Setters & Structs

(I assume you mean getter, as the setter would allow it to be modified.) But why care, really? It looks like your struct in this case is mostly just a plain data object;

// Segment represents a media file with a name and the segment in bytes
type Segment struct {
	filename string
	filesize int
	segment  []byte
}

You’re giving this to someone to give them information about a segment. What they do with it after that point sort of isn’t your business, as the data producer, outside of some sort of “data bondage” like desire to enforce your will. :slight_smile: In Go, you would typically just export the fields. Clearly, if you need to enforce some sort of consistent state in the object - like, the filename can be modified but then the filesize must be updated accordingly - then you want a setter that handles this and keep the fields unexported.

The other side of this coin is there are many types of segments and you want your code to be generic. Then you create getters and return an interface - a typical example might be the os.FileInfo which is just an interface that defines a bunch of getters. The reason is that the actual underlying type will be some OS specific thing, and it just has to define the specified getters to work.

2 Likes