Home | History | Annotate | Download | only in reflect
      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 	"io"
     10 	"os"
     11 	"reflect"
     12 )
     13 
     14 func ExampleMakeFunc() {
     15 	// swap is the implementation passed to MakeFunc.
     16 	// It must work in terms of reflect.Values so that it is possible
     17 	// to write code without knowing beforehand what the types
     18 	// will be.
     19 	swap := func(in []reflect.Value) []reflect.Value {
     20 		return []reflect.Value{in[1], in[0]}
     21 	}
     22 
     23 	// makeSwap expects fptr to be a pointer to a nil function.
     24 	// It sets that pointer to a new function created with MakeFunc.
     25 	// When the function is invoked, reflect turns the arguments
     26 	// into Values, calls swap, and then turns swap's result slice
     27 	// into the values returned by the new function.
     28 	makeSwap := func(fptr interface{}) {
     29 		// fptr is a pointer to a function.
     30 		// Obtain the function value itself (likely nil) as a reflect.Value
     31 		// so that we can query its type and then set the value.
     32 		fn := reflect.ValueOf(fptr).Elem()
     33 
     34 		// Make a function of the right type.
     35 		v := reflect.MakeFunc(fn.Type(), swap)
     36 
     37 		// Assign it to the value fn represents.
     38 		fn.Set(v)
     39 	}
     40 
     41 	// Make and call a swap function for ints.
     42 	var intSwap func(int, int) (int, int)
     43 	makeSwap(&intSwap)
     44 	fmt.Println(intSwap(0, 1))
     45 
     46 	// Make and call a swap function for float64s.
     47 	var floatSwap func(float64, float64) (float64, float64)
     48 	makeSwap(&floatSwap)
     49 	fmt.Println(floatSwap(2.72, 3.14))
     50 
     51 	// Output:
     52 	// 1 0
     53 	// 3.14 2.72
     54 }
     55 
     56 func ExampleStructTag() {
     57 	type S struct {
     58 		F string `species:"gopher" color:"blue"`
     59 	}
     60 
     61 	s := S{}
     62 	st := reflect.TypeOf(s)
     63 	field := st.Field(0)
     64 	fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
     65 
     66 	// Output:
     67 	// blue gopher
     68 }
     69 
     70 func ExampleTypeOf() {
     71 	// As interface types are only used for static typing, a
     72 	// common idiom to find the reflection Type for an interface
     73 	// type Foo is to use a *Foo value.
     74 	writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
     75 
     76 	fileType := reflect.TypeOf((*os.File)(nil))
     77 	fmt.Println(fileType.Implements(writerType))
     78 
     79 	// Output:
     80 	// true
     81 }
     82