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


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: = "hello"

// or

func (f *Foo) SetBar(n string) { = n


Does it even matter?


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 == "" { = "SOME_DEFAULT_VALUE" }
    else { = 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 += " World!" // f.baz remains 639, 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.