reflect_struct.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // reflect.go
  2. package main
  3. import (
  4. "fmt"
  5. "reflect"
  6. )
  7. type NotknownType struct {
  8. s1, s2, s3 string
  9. }
  10. func (n NotknownType) String() string {
  11. return n.s1 + " - " + n.s2 + " - " + n.s3
  12. }
  13. // variable to investigate:
  14. var secret interface{} = NotknownType{"Ada", "Go", "Oberon"}
  15. func main() {
  16. value := reflect.ValueOf(secret) // <main.NotknownType Value>
  17. typ := reflect.TypeOf(secret) // main.NotknownType
  18. // alternative:
  19. //typ := value.Type() // main.NotknownType
  20. fmt.Println(typ)
  21. knd := value.Kind() // struct
  22. fmt.Println(knd)
  23. // iterate through the fields of the struct:
  24. for i := 0; i < value.NumField(); i++ {
  25. fmt.Printf("Field %d: %v\n", i, value.Field(i))
  26. // error: panic: reflect.Value.SetString using value obtained using unexported field
  27. //value.Field(i).SetString("C#")
  28. }
  29. // call the first method, which is String():
  30. results := value.Method(0).Call(nil)
  31. fmt.Println(results) // [Ada - Go - Oberon]
  32. }
  33. /* Output:
  34. main.NotknownType
  35. struct
  36. Field 0: Ada
  37. Field 1: Go
  38. Field 2: Oberon
  39. [Ada - Go - Oberon]
  40. */