Polymorphism in Go
Polymorphism in object-oriented programming refers to the ability of an object to take on many forms. In Go, polymorphism is achieved through interfaces:
type SoundMaker interface {
MakeSound()
}
func ProduceSound(s SoundMaker) {
s.MakeSound()
}
Go vs Java Comparison
Language Fundamentals
| Feature | Go | Java |
|---|---|---|
| Typing | Static, simple | Static, strict |
| Compilation | Direct to machine code | Bytecode via JVM |
| Performance | Fast startup | JVM overhead |
| Syntax | Minimalist | Feature-rich |
Object Orientation
| Feature | Go | Java |
|---|---|---|
| Classes | Structs | Class keyword |
| Inheritance | Composition preferred | Single inheritance |
| Polymorphism | Interfaces (implicit) | Interfaces + inheritance |
Concurrency Models
| Feature | Go | Java |
|---|---|---|
| Model | Goroutines + channels | Threads + thread pools |
| Memory | Lightweight (KB) | Heavyweight (MB) |
| Syntax | Built-in go keyword |
Thread class |
Basic Data Types in Go
Primitive Types
- Boolean:
bool - Numeric:
- Integers:
int8-int64,uint8-uint64 - Floating-point:
float32,float64 - Complex:
complex64,complex128
- Integers:
- Text:
string
Composite Types
- Arrrays
- Slices
- Maps
- Structs
- Pointers
- Functions
- Interfaces
- Channels
String Traversal Methods
Byte-by-Byte
s := "Hello"
for i := 0; i < len(s); i++ {
fmt.Printf("%c ", s[i])
}
Rune-by-Rune
s := "世界"
for _, r := range s {
fmt.Printf("%c ", r)
}
Byte vs Rune
| Characteristic | Byte | Rune |
|---|---|---|
| Size | 8-bit | 32-bit |
| Purpose | Raw data | Unicode |
| String Access | UTF-8 bytes | Full codepoint |
GMP Scheduling Model
- G: Goroutine (task unit)
- M: OS thread (execution context)
- P: Logical processor (scheduler)
Workflow:
- Goroutines are created and queued
- P assigns G to M for execution
- On blocking, M may be released
Parameter Passing
Go always uses value passing, though some types contain references:
| Type | Behavior | Example |
|---|---|---|
| int | Value copied | Unchanged |
| slice | Header copied | Shared data |
| map | Pointer copied | Shared data |
String Immutability
Go strings are immutable for:
- Safety
- Performance
- Memory management
To modify:
s := "hello"
b := []byte(s)
b[0] = 'H'
s = string(b)
Generics Implementation
Go's generics are implemented through:
- Type parameters
- Compile-time monomorphization
- Runtime type erasure