Created
August 29, 2024 12:24
-
-
Save jmsdnns/2cb2cf8b488fed7af330d2761c88b908 to your computer and use it in GitHub Desktop.
basic example of how Go uses composition instead of inheritence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type Polygon struct { | |
Sides int | |
} | |
func (p *Polygon) NSides() int { | |
return p.Sides | |
} | |
type Triangle struct { | |
Polygon // anonymous field | |
} | |
func main() { | |
t := Triangle{ | |
Polygon{ | |
Sides: 3, | |
}, | |
} | |
fmt.Println(t.NSides()) // 3 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment