fork download
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. // class Doorbell
  6.  
  7. type Doorbell struct {
  8. }
  9.  
  10. func (this Doorbell) Ring() {
  11. fmt.Println("Ring, Ring! Can I come in?")
  12. }
  13.  
  14. // class Telephone
  15.  
  16. type Telephone struct {
  17. }
  18.  
  19. func (this Telephone) Ring() {
  20. fmt.Println("Ring, Ring! Can we talk?")
  21. }
  22.  
  23. // interfaces are like static duck-typing
  24.  
  25. type Ringer interface {
  26. Ring()
  27. }
  28.  
  29. // this function takes any object that has a "Ring" method
  30.  
  31. func ringThis(r Ringer) {
  32. r.Ring()
  33. }
  34.  
  35. // we could even use an anonymous interface
  36.  
  37. func ringThisAnon(r interface { Ring() }) {
  38. r.Ring()
  39. }
  40.  
  41. func main() {
  42. // all of this typechecks!
  43. ringThis(Doorbell{})
  44. ringThis(Telephone{})
  45. ringThisAnon(Doorbell{})
  46. ringThisAnon(Telephone{})
  47. }
  48.  
Success #stdin #stdout 0s 420608KB
stdin
Standard input is empty
stdout
Ring, Ring! Can I come in?
Ring, Ring! Can we talk?
Ring, Ring! Can I come in?
Ring, Ring! Can we talk?