simple_interface2.go 705 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // simple_interface2.go
  2. package main
  3. import (
  4. "fmt"
  5. )
  6. type Simpler interface {
  7. Get() int
  8. Set(int)
  9. }
  10. type Simple struct {
  11. i int
  12. }
  13. func (p *Simple) Get() int {
  14. return p.i
  15. }
  16. func (p *Simple) Set(u int) {
  17. p.i = u
  18. }
  19. type RSimple struct {
  20. i int
  21. j int
  22. }
  23. func (p *RSimple) Get() int {
  24. return p.j
  25. }
  26. func (p *RSimple) Set(u int) {
  27. p.j = u
  28. }
  29. func fI(it Simpler) int {
  30. switch it.(type) {
  31. case *Simple:
  32. it.Set(5)
  33. return it.Get()
  34. case *RSimple:
  35. it.Set(50)
  36. return it.Get()
  37. default:
  38. return 99
  39. }
  40. return 0
  41. }
  42. func main() {
  43. var s Simple
  44. fmt.Println(fI(&s)) // &s is required because Get() is defined with a receiver type pointer
  45. var r RSimple
  46. fmt.Println(fI(&r))
  47. }
  48. /* Output:
  49. 5
  50. 50
  51. */