Start learning free

LESSON 283 OF 671 · FUNCTIONS & CLASSES

Member Functions in Go

Lesson

TL ; DR:

  • A method is a function with a receiver declared for a struct. It can read and write the struct's fields.


  • Define methods with a receiver so they can be called on struct values:

    type Dog struct {
        name string
    }
    
    func NewDog(name string) Dog {
        return Dog{name: name}
    }
    
    func (d Dog) bark() {
        fmt.Printf("Woof! I am %s\n", d.name)
    }
    

  • Call it on a value with the dot operator: dog.bark()



Full lesson:

So far you've added data to a struct with fields and a constructor function. The other half of OOP is behavior — actions a value can perform. That's what methods are for.


Your task

Add a bark() method that prints "Woof! I am " followed by the dog's name.

Woof! I am Rex
STEP 1 OF 4
    Ctrl + Enter to check