Sobes.tech
Junior — Middle

How is the concept of object-oriented programming implemented in Go?

sobes.tech AI

Answer from AI

Go does not have a traditional object-oriented model with inheritance and classes, but the language supports OOP concepts through:

  • Structures (structs) — user-defined data types that can contain fields.
  • Methods — functions associated with types (including structs), allowing object behavior implementation.
  • Interfaces — define a set of methods that a type must implement, ensuring polymorphism.

Example:

package main
import "fmt"

type Animal interface {
    Speak() string
}

type Dog struct {}

func (d Dog) Speak() string {
    return "Woof!"
}

type Cat struct {}

func (c Cat) Speak() string {
    return "Meow!"
}

func main() {
    animals := []Animal{Dog{}, Cat{}}
    for _, a := range animals {
        fmt.Println(a.Speak())
    }
}

Thus, Go implements OOP through composition and interfaces, not inheritance.