Skip to content

Instantly share code, notes, and snippets.

@toddlers
Created January 8, 2020 17:42
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 toddlers/b17b541315bfb6550e4ef1863f083348 to your computer and use it in GitHub Desktop.
Save toddlers/b17b541315bfb6550e4ef1863f083348 to your computer and use it in GitHub Desktop.
interfaces and type embedding golang
package main
import "fmt"
type Boss struct{}
func (b *Boss) AssignWork() {
fmt.Println("Boss assigned work")
}
type Manager struct{}
func (m *Manager) PreparePowerPoint() {
fmt.Println("Power point prepared")
}
type BossManager struct {
Boss
Manager
}
type BossManagerUsingPointer struct {
*Boss
*Manager
}
type PromotionalMaterail interface {
AssignWork()
PreparePowerPoint()
}
func promote(pm PromotionalMaterail) {
fmt.Println("Promoted a person with promise")
}
func main() {
bm := BossManager{}
//Both methods which uses pointer receivers have been promoted
//to BossManager
bm.AssignWork()
bm.PreparePowerPoint()
// However, the method set of BossManager does not invlude either
// method because:
// 1) {Boos, Manager} are embedded as value types, not pointer types.
// 2) This makes it so that only the pointer type *BoosManager
// includes both methods in its method set, thus making it implement
// interface PromotionMaterial
// promote(bm) // would fail withy: can not use bm(type BossManager)
// as type PromotionMaterial in argument to promote:
//BoosManager does not implement PromotionMaterial (AssignWork method
// has pointer receiver)
// This Would work if {Boss, Manager} were embedded as pointer types.
promote(&bm) // Works
// Let us use the struct with the embedded pointer types:
bm2 := BossManagerUsingPointer{}
bm2.AssignWork()
bm2.PreparePowerPoint()
promote(bm2)
promote(&bm2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment