Sobes.tech
Middle+

How is OOP implemented in Go?

sobes.tech AI

Answer from AI

Go does not have traditional OOP with inheritance, but it has composition and interfaces, which allow implementing polymorphism and encapsulation.

Main mechanisms:

  • Structures (struct) — similar to classes without methods.
  • Methods — functions with a receiver, attached to structures.
  • Interfaces — describe a set of methods that a structure must implement.
  • Composition — instead of inheritance, structures can include other structures to extend functionality.

Example:

package main
import "fmt"

type Animal interface {
    Speak() string
}

type Dog struct {
    Name string
}

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

func main() {
    var a Animal = Dog{Name: "Buddy"}
    fmt.Println(a.Speak()) // Outputs: Woof!
}

Thus, Go uses interfaces and composition to implement OOP principles without traditional inheritance hierarchies.