Middle+
Compare the implementation of object-oriented programming in Go and C#.
sobes.tech AI
Answer from AI
In Go, there is no traditional object-oriented inheritance and classes in the conventional sense. Instead, Go uses composition and interfaces.
Main differences:
- Classes and objects: C# is based on classes, from which objects are created. Go uses structs, which can have methods.
- Inheritance: C# supports single and multiple inheritance (via interfaces). Go supports composition (embedding structs) and polymorphism through interfaces.
- Interfaces: In C#, interfaces must be explicitly implemented by classes. In Go, interfaces are implemented implicitly: if a struct has methods matching the interface's signature, it automatically implements that interface.
- Visibility (Access Modifiers): C# uses
public,private,protected,internal. In Go, visibility is determined by the case of the first letter of the name: uppercase is public, lowercase is private (within the package). - Generics: C# has a developed generics system. Go added support for generics starting from version 1.18.
Example of composition in Go:
package main
import "fmt"
type Engine struct {
Type string
}
func (e Engine) Start() {
fmt.Printf("%s engine started!\n", e.Type)
}
type Car struct {
Model string
Engine // Embedding - composition
}
func main() {
myCar := Car{
Model: "Sedan",
Engine: Engine{
Type: "Petrol",
},
}
fmt.Printf("Car model: %s\n", myCar.Model)
myCar.Start() // Calling method of embedded struct
}
Example of interface implementation in Go:
package main
import "fmt"
type Speaker interface {
Speak() string
}
type Dog struct{}
func (d Dog) Speak() string {
return "Woof!"
}
type Cat struct{}
func (c Cat) Speak() string {
return "Meow!"
}
func main() {
animals := []Speaker{Dog{}, Cat{}} // Slice of types implementing Speaker interface
for _, animal := range animals {
fmt.Println(animal.Speak())
}
}
| Attribute | Go | C# |
|---|---|---|
| Classes | No (structs exist) | Yes |
| Objects | Struct instances | Class instances |
| Inheritance | Composition, interfaces | Classical (single), interfaces |
| Interfaces | Implicit implementation | Explicit implementation |
| Visibility | Case of first letter | public, private, protected, etc. |
| Generics | From version 1.18 | Yes |
Go's approach to OOP is more decentralized and focused on behavior (via interfaces) and data structures (via embedding), often leading to more flexible and easily testable code. C# adheres to a more traditional hierarchical model.