Sobes.tech
Middle

What are the principles of OOP and how are they implemented in Go?

sobes.tech AI

Answer from AI

Go does not have a traditional implementation of OOP like in Java or C++, but the main principles of OOP are implemented through other mechanisms:

  1. Encapsulation — achieved through visibility of identifiers: exported (with a capital letter) and unexported (with a lowercase). This allows hiding internal implementation details of a package.

  2. Inheritance — Go does not have class inheritance, but it has composition through struct embedding. This allows extending functionality by embedding one struct into another.

  3. Polymorphism — implemented through interfaces. Any type that implements the methods of an interface automatically satisfies that interface, enabling writing generic code.

  4. Abstraction — achieved through interfaces that describe behavior without specifying a concrete implementation.

Example of interface and composition:

package main
import "fmt"

type Speaker interface {
    Speak() string
}

type Person struct {
    Name string
}

func (p Person) Speak() string {
    return "Hello, my name is " + p.Name
}

type Robot struct {
    Person // embedding
    Model string
}

func (r Robot) Speak() string {
    return "Beep boop, I am model " + r.Model
}

func greet(s Speaker) {
    fmt.Println(s.Speak())
}

func main() {
    p := Person{Name: "Alice"}
    r := Robot{Person: Person{Name: "R2D2"}, Model: "R2"}
    greet(p)
    greet(r)
}

Thus, Go supports the main concepts of OOP but does so through composition and interfaces rather than classes and inheritance.