example_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2012 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package reflect_test
  5. import (
  6. "fmt"
  7. "reflect"
  8. )
  9. func ExampleMakeFunc() {
  10. // swap is the implementation passed to MakeFunc.
  11. // It must work in terms of reflect.Values so that it is possible
  12. // to write code without knowing beforehand what the types
  13. // will be.
  14. swap := func(in []reflect.Value) []reflect.Value {
  15. return []reflect.Value{in[1], in[0]}
  16. }
  17. // makeSwap expects fptr to be a pointer to a nil function.
  18. // It sets that pointer to a new function created with MakeFunc.
  19. // When the function is invoked, reflect turns the arguments
  20. // into Values, calls swap, and then turns swap's result slice
  21. // into the values returned by the new function.
  22. makeSwap := func(fptr interface{}) {
  23. // fptr is a pointer to a function.
  24. // Obtain the function value itself (likely nil) as a reflect.Value
  25. // so that we can query its type and then set the value.
  26. fn := reflect.ValueOf(fptr).Elem()
  27. // Make a function of the right type.
  28. v := reflect.MakeFunc(fn.Type(), swap)
  29. // Assign it to the value fn represents.
  30. fn.Set(v)
  31. }
  32. // Make and call a swap function for ints.
  33. var intSwap func(int, int) (int, int)
  34. makeSwap(&intSwap)
  35. fmt.Println(intSwap(0, 1))
  36. // Make and call a swap function for float64s.
  37. var floatSwap func(float64, float64) (float64, float64)
  38. makeSwap(&floatSwap)
  39. fmt.Println(floatSwap(2.72, 3.14))
  40. // Output:
  41. // 1 0
  42. // 3.14 2.72
  43. }
  44. func ExampleStructTag() {
  45. type S struct {
  46. F string `species:"gopher" color:"blue"`
  47. }
  48. s := S{}
  49. st := reflect.TypeOf(s)
  50. field := st.Field(0)
  51. fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
  52. // Output:
  53. // blue gopher
  54. }