Exercises & activities from the go workshop provided by Packt: https://courses.packtpub.com/courses/go
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.1 KiB

  1. package main
  2. import "fmt"
  3. type record struct {
  4. key string
  5. valueType string
  6. data interface{}
  7. }
  8. type person struct {
  9. lastName string
  10. age int
  11. isMarried bool
  12. }
  13. type animal struct {
  14. name string
  15. category string
  16. }
  17. func newRecord(key string, i interface{}) record {
  18. r := record{}
  19. r.key = key
  20. switch v := i.(type) {
  21. case int:
  22. r.valueType = "int"
  23. r.data = v
  24. case bool:
  25. r.valueType = "bool"
  26. r.data = v
  27. case string:
  28. r.valueType = "string"
  29. r.data = v
  30. case person:
  31. r.valueType = "person"
  32. r.data = v
  33. default:
  34. r.valueType = "unknown"
  35. r.data = v
  36. }
  37. return r
  38. }
  39. func main() {
  40. m := make(map[string]interface{})
  41. a := animal{name: "oreo", category: "cat"}
  42. p := person{lastName: "Doe", isMarried: false, age: 19}
  43. m["person"] = p
  44. m["animal"] = a
  45. m["age"] = 54
  46. m["isMarried"] = true
  47. m["lastName"] = "Smith"
  48. rs := []record{}
  49. for k, v := range m {
  50. r := newRecord(k, v)
  51. rs = append(rs, r)
  52. }
  53. for _, v := range rs {
  54. fmt.Println("Key:", v.key)
  55. fmt.Println("Data:", v.data)
  56. fmt.Println("Type:", v.valueType)
  57. fmt.Println()
  58. }
  59. }