What is the common norm of exposing read only variables?

I am a beginner in Go so please pardon my naivete. I am coming from C#/Java background, where there are public/private properties (or getters/setters). Yet, in go, such approach does not exists. Either a variable starts with Capital letter, hence public, or small letter, hence private. In C# for instance, we can have public get but private set properties.

What is the common norm of exposing public variables in a package, that should not be modified by any code outside the package?

Hello there. I would say If it should be readonly, in this case you need to make it not exported and add an exported getter e.g.,

type Test struct {
    readOnly string
}

func (t *Test) GetReadOnly() string { return t.readOnly }

In this case you’ll be able to work with this variable inside the package without letting user to get access to it, but at the same time, give an interface to read the value outside.

Imho, getters/setters in go appear in their own design. If you want to give user complete access to the internal variable then just export it. But, for example, if the update of the var leads to some internal logic, then it’s better to make it non export and add an additional setter e.g.,

type Test struct {
    SimpleVar string
    specialVar string
}

func (t *Test) SetSpecial(str string) {
    // Do some logic here before re-assigning e.g.,
    t.specialVar = t.SimpleVar + str
}

func (t *Test) GetSpecial() string { return t.specialVar }
3 Likes