Sobes.tech
Middle

How is the object-oriented model structured in Go?

sobes.tech AI

Answer from AI

Go lacks a traditional object-oriented model with deep class inheritance hierarchies. Instead, it uses:

  • Structs: Define data fields, similar to classes without methods.

    type Person struct {
        Name string
        Age  int
    }
    
  • Methods: Functions bound to a specific struct. They are defined separately from the struct.

    func (p Person) Greet() string {
        return "Hello, my name is " + p.Name
    }
    
    func (p *Person) CelebrateBirthday() {
        p.Age++
    }
    
    • Methods with value receivers (e.g., (p Person)) work with a copy of the struct.
    • Methods with pointer receivers (e.g., (p *Person)) work with the original struct, allowing modification of its fields.
  • Interfaces: Sets of method signatures. Types implementing all methods of an interface implicitly satisfy that interface. This is the basis of polymorphism in Go.

    type Greeter interface {
        Greet() string
    }
    
    // Person implicitly implements Greeter
    
  • Composition (Embedding): Instead of inheritance, one struct can embed another, gaining access to its fields and methods.

    type Employee struct {
        Person // Embedding the Person struct
        ID     string
    }
    
    func (e Employee) GetID() string {
        return e.ID
    }
    

    Embedded fields and methods are accessible directly:

    e := Employee{
        Person: Person{Name: "Alice", Age: 30},
        ID:     "E123",
    }
    fmt.Println(e.Name)     // Accessing Name through embedded Person
    fmt.Println(e.Greet())  // Calling Greet method through embedded Person
    fmt.Println(e.GetID())  // Calling Employee's method
    

Thus, the object-oriented model in Go is built on composition of structs and behavior defined by interfaces, rather than on a classical inheritance hierarchy.