Start learning free

LESSON 598 OF 639 · OBJECT-ORIENTED PROGRAMMING

Getters and Setters in Go in Go

Lesson

TL ; DR:

A getter reads a private field. A setter changes it, but only to a value the class allows.

Go has no special syntax for them. You write both as methods, as in the Access Modifiers lesson. The getter getAge() returns the unexported field age. The setter setAge(value) changes it.


type Dog struct {
    age int
}

func NewDog(age int) Dog {
    return Dog{age: age}
}

func (this Dog) getAge() int {
    return this.age
}

func (this *Dog) setAge(value int) {
    if value >= 0 {
        this.age = value
    }
}


Full lesson:

In the Access Modifiers lesson, getName() let other code read an unexported field. Often other code must change a field too. A setter allows that, and it checks each new value first.

The getter

The getter only reads, so a value receiver (this Dog) is enough. Other code calls rex.getAge().

The setter

The setter has a pointer receiver, (this *Dog). Then the change reaches the dog itself, not a copy. Other code calls rex.setAge(4).

The rule

A dog's age can't be negative. So setAge changes this.age only when value is 0 or more. After rex.setAge(-5), the age stays as it was.

Why not an exported field?

With an exported Age field, any code could set it to -5. Nothing would check it. The setter keeps the rule next to the type.


Your task

The Dog struct keeps its age in the unexported field age. Add a getter getAge() that returns it. Add a setter setAge(value) that ignores negative values.

The code in mainFunction creates rex with NewDog(3), then reads and sets its age.

Expected output:

Rex is 3
Rex is still 3
Rex is 4
STEP 1 OF 3
    Ctrl + Enter to check

    Getters And Setters in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free