Last active
September 16, 2020 16:58
-
-
Save mutuadavid93/619e6e2502c7ba631b6c768faeca2bdd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Static Types :: | |
// e.g. Structs can lead to a nightmare when initializing them | |
// if they are deeply embedded which translates to nesting. | |
// Instead use Structs plus Interfaces to decouple and reuse stuff. | |
// | |
// | |
package main | |
import "fmt" | |
// Speaker interface | |
type Speaker interface { | |
Speak() | |
} | |
// Dog as the base struct | |
type Dog struct{} | |
// Husky is an embedded struct type containing all Speaker interface's methods | |
type Husky struct { | |
// Embed Dog into Husky promoting all the Dog members to Husky. | |
// Dog | |
// Note :: we can as well embed interfaces into other structs. | |
// All methods which belong to Speaker interface, are promoted to Husky. | |
Speaker | |
} | |
// Speak is Dog's method. | |
// Now Dog implements the Speaker type since it defines logic for it. | |
func (d Dog) Speak() { | |
fmt.Println("Wooooof!!!") | |
} | |
// Duck type | |
type Duck struct{} | |
// Speak produces duck's voice | |
func (dck Duck) Speak() { | |
fmt.Println("Quaaack!!!") | |
} | |
func main() { | |
// Note :: If you need to get access to all members of Speaker interface | |
// e.g. Speak() | |
// Use any type which implements that interface e.g. Dog{} as if it were the | |
// the embedded type's(e.g. Husky) property(i.e. Speaker) value. | |
dog := Husky{Speaker: Dog{}} | |
dog.Speak() | |
// Same thing but now implicitly using Speaker Husky's property | |
swampduck := Husky{Duck{}} | |
swampduck.Speak() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment