Skip to content

Instantly share code, notes, and snippets.

@mutuadavid93
Last active September 16, 2020 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mutuadavid93/619e6e2502c7ba631b6c768faeca2bdd to your computer and use it in GitHub Desktop.
Save mutuadavid93/619e6e2502c7ba631b6c768faeca2bdd to your computer and use it in GitHub Desktop.
// 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