Sobes.tech
Middle

Kuidas on Go-s üles ehitatud objektorienteeritud mudel?

sobes.tech AI

Vastus AI-lt

Go does not have a traditional object-oriented model with deep inheritance hierarchies. Instead, it uses:

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

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

    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 structure.
    • Methods with pointer receivers (e.g., (p *Person)) work with the original structure, 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 structure 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)     // Access to Name field via embedded Person
    fmt.Println(e.Greet())  // Call to Greet method via embedded Person
    fmt.Println(e.GetID())  // Call to Employee method
    

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