Menu
Coddy logo textTech

Introduction to OOP in Go

Part of the Object Oriented Programming section of Coddy's GO journey — lesson 5 of 107.

Go doesn't have classes, but it achieves object-oriented programming through structs and methods. A struct groups related data, and methods define behavior attached to that struct.

Define a struct to hold data

type Dog struct {
    Name string
    Age  int
}

Attach a method to the struct

func (d Dog) Bark() string {
    return d.Name + " says Woof!"
}

Create an instance and use it

package main

import "fmt"

type Dog struct {
    Name string
    Age  int
}

func (d Dog) Bark() string {
    return d.Name + " says Woof!"
}

func main() {
    myDog := Dog{Name: "Buddy", Age: 3}
    fmt.Println(myDog.Bark()) // Output: Buddy says Woof!
    fmt.Println(myDog.Age)    // Output: 3
}

In Go, the (d Dog) part before the method name is called a receiver. It connects the method to the Dog struct, similar to how methods belong to classes in other languages.

challenge icon

Challenge

Easy

Create a Cat struct with a method to practice Go's approach to OOP:

  • Define a Cat struct with Name (string) and Age (int) fields
  • Add a Speak method that returns the cat's name followed by " says Meow!"

Cheat sheet

Go achieves object-oriented programming through structs and methods. A struct groups related data, and methods define behavior attached to that struct.

Define a struct to hold data:

type Dog struct {
    Name string
    Age  int
}

Attach a method to the struct using a receiver:

func (d Dog) Bark() string {
    return d.Name + " says Woof!"
}

The (d Dog) part before the method name is the receiver, which connects the method to the struct.

Create an instance and use it:

myDog := Dog{Name: "Buddy", Age: 3}
fmt.Println(myDog.Bark()) // Output: Buddy says Woof!
fmt.Println(myDog.Age)    // Output: 3

Try it yourself

package main

import "fmt"

func main() {
    var name string
    var age int
    fmt.Scan(&name, &age)

    cat := Cat{Name: name, Age: age}

    fmt.Printf("Name: %s\n", cat.Name)
    fmt.Printf("Age: %d\n", cat.Age)
    fmt.Println(cat.Speak())
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming