Skip to content

Instantly share code, notes, and snippets.

@MarioCarrion
Last active February 17, 2018 00:16
Show Gist options
  • Save MarioCarrion/f65dee6a460978544a8a7cf4f56d0c73 to your computer and use it in GitHub Desktop.
Save MarioCarrion/f65dee6a460978544a8a7cf4f56d0c73 to your computer and use it in GitHub Desktop.
Go Tip: Embedding Example with interfaces
package main
import (
"fmt"
)
type GreetingsService interface {
SayHello() string
SayGoodMorning() string
}
type EnglishService struct {
Country string
}
func (EnglishService) SayHello() string { return "hello!" }
func (EnglishService) SayGoodMorning() string { return "good morning!" }
type SpanishService struct{}
func (SpanishService) SayHello() string { return "hola!" }
func (SpanishService) SayGoodMorning() string { return "buenos dias!" }
type GiveMeYourMoneyService struct {
GreetingsService
Country string
}
func (GiveMeYourMoneyService) SayGoodMorning() string { return "$$$" }
func main() {
e := EnglishService{Country: "Neverland"}
fmt.Printf("EnglishService: %+v\n", e)
fmt.Printf("EnglishService.SayHello %v\n", e.SayHello())
fmt.Printf("EnglishService.GoodMorning %v\n", e.SayGoodMorning())
o := GiveMeYourMoneyService{GreetingsService: &e, Country: "Sokovia"}
fmt.Printf("FancierService: %+v\n", o)
fmt.Printf("FancierService.SayHello: %s\n", o.SayHello())
fmt.Printf("FancierService.GoodMorning: %s\n", o.SayGoodMorning())
// This panics because you already assigned it to the specific type,
// you will need to re-instantiate "o" and specify the value again
// o.GreetingsService = &SpanishService{}
var e1 *EnglishService = o.GreetingsService.(*EnglishService)
fmt.Printf("original.Country: %s\n", e1.Country)
//-
o = GiveMeYourMoneyService{GreetingsService: &SpanishService{}, Country: "Pueblo Viejo"}
fmt.Printf("FancierService: %+v\n", o)
fmt.Printf("FancierService.SayHello: %s\n", o.SayHello())
fmt.Printf("FancierService.GoodMorning: %s\n", o.SayGoodMorning())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment