Type Shadowing

What will be printed when the code below is executed?

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type S1 struct{}
  6. func (s1 S1) f() {
  7. fmt.Println("S1.f()")
  8. }
  9. func (s1 S1) g() {
  10. fmt.Println("S1.g()")
  11. }
  12. type S2 struct {
  13. S1
  14. }
  15. func (s2 S2) f() {
  16. fmt.Println("S2.f()")
  17. }
  18. type I interface {
  19. f()
  20. }
  21. func printType(i I) {
  22. fmt.Printf("%T\n", i)
  23. if s1, ok := i.(S1); ok {
  24. s1.f()
  25. s1.g()
  26. }
  27. if s2, ok := i.(S2); ok {
  28. s2.f()
  29. s2.g()
  30. }
  31. }
  32. func main() {
  33. printType(S1{})
  34. printType(S2{})
  35. }

Answer

  1. main.S1
  2. S1.f()
  3. S1.g()
  4. main.S2
  5. S2.f()
  6. S1.g()