Middle
How are object-oriented programming (OOP) concepts implemented in Go?
sobes.tech AI
Answer from AI
In Go, there are no classical concepts of classes, inheritance, and virtual methods as in 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). They allow structs to have behavior.
func (p Person) Greet() string { return "Hello, my name is " + p.Name }- Receiver by value: The method works with a copy of the struct. Changes inside the method do not affect the original struct.
- Receiver by pointer: The 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 satisfy. They provide polymorphism "by 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 rather 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 Person struct ID string } // Employee now has Name and Age fields, as well as the Greet() method e := Employee{ Person: Person{Name: "Alice", Age: 30}, ID: "E123", } fmt.Println(e.Greet()) // calls the Greet() method of Person 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 |