Does it matter how I change a variable of a struct?

Issue

I’m relatively new to Go, so just trying to figure out the best practices (for good code). For example, if I have a struct like this:

type Foo struct {
    bar string
}

f := Foo{bar: "test"}

// should I change bar like this:
f.bar = "hello"

// or

func (f *Foo) SetBar(n string) {
    f.bar = n
}

f.SetBar("hello")

Does it even matter?

Solution

Does it even matter?

It depends on how much control you want on the value.

A Setter(and private variable) is useful for checking the input value before setting. This applies to access from other packages only. Same package code can access the variable directly

func (f *Foo) SetBar(n string) {
    if n == "" { f.bar = "SOME_DEFAULT_VALUE" }
    else {f.bar = n }
}

Initialization with bar alone, when other variables can be default

type Foo struct {
    bar string
    baz int
}

f := Foo{bar: "test"} // f.baz will be zero value

Set variable, when other variables, previously initialized need not change.

f := &Foo{bar="Hello", baz=639} // Initialization with both values
f.bar += " World!" // f.baz remains 639, f.bar becomes "Hello World!"

Except for setter others will need bar to be public i.e. Bar, if access outside package is needed.

Hope this helps.

Answered By – s3vt

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.