Sobes.tech
Middle

Kuidas on Go keeles rakendatud objektorienteeritud programmeerimise (OOP) kontseptsioonid?

sobes.tech AI

Vastus AI-lt

Go does not have the classical concepts of classes, inheritance, and virtual methods that are characteristic of other languages (Java, C++). OOP is implemented through:

  • Structures (Structs): Combine data (fields).
    type Person struct {
    	Name string
    	Age  int
    }
    
  • Methods: Functions with an associated receiver (struct or other type). Allow structs to have behavior.
    func (p Person) Greet() string {
    	return "Hello, my name is " + p.Name
    }
    
    • Receiver by value: Method works with a copy of the struct. Changes inside the method do not affect the original struct.
    • Receiver by pointer: Method works with the original struct via a pointer. Changes inside the method affect the original struct.
  • Interfaces: Define a set of method signatures that a type must implement. They provide polymorphism "by duck typing" (duck typing). A type implicitly implements an interface if it implements all its methods.
    type Greeter interface {
    	Greet() string
    }
    
    func SayHello(g Greeter) string {
    	return g.Greet()
    }
    
  • Embedding: Allows one struct to "embed" another struct or interface. This is not inheritance in the classical sense, but composition. The embedded struct becomes an anonymous field, and its fields and methods can be accessed directly through the embedding struct instance.
    type Employee struct {
    	Person // embedded struct
    	ID string
    }
    
    // Employee now has fields Name and Age, as well as the Greet() method
    
    e := Employee{
    	Person: Person{Name: "Alice", Age: 30},
    	ID:     "E123",
    }
    fmt.Println(e.Greet()) // calling the Greet() method of the Person struct via Employee
    
OOP Concept Implementation in Go Remarks
Classes Structures No explicit class keyword
Encapsulation Exported (capital letter) / Unexported (small letter) fields/methods Visibility control at package level
Inheritance Embedding Composition instead of hierarchical inheritance
Polymorphism Interfaces Duck typing, implicit interface implementation