Sobes.tech
Junior — Middle

What features of OOP in Go differ from implementations in other programming languages?

sobes.tech AI

Answer from AI

Go lacks traditional classes and inheritance like in C++ or Java. Instead, it uses composition through embedded types and interfaces. Key features of OOP in Go:

  • No classes: structures (struct) are used to describe data.
  • Interfaces: define a set of methods that a type must implement, without specifying how (duck typing).
  • Composition instead of inheritance: types are embedded within other types, allowing code reuse.
  • Methods: can be defined for any type, including structs.

Example:

package main
import "fmt"

type Speaker interface {
    Speak() string
}

type Dog struct {
    Name string
}

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

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

Thus, Go implements OOP through interfaces and composition, which simplifies architecture and increases code flexibility.