github.com/tcnksm/go@v0.0.0-20141208075154-439b32936367/src/reflect/example_test.go (about)

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