016-08-04 Bernd Edlinger <bernd.edlinger@hotmail.de>
[official-gcc.git] / libgo / go / reflect / example_test.go
blob9e2b9b3e9724dcc5eb0d6956841d50c71b832dea
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.
5 package reflect_test
7 import (
8 "fmt"
9 "io"
10 "os"
11 "reflect"
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]}
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()
34 // Make a function of the right type.
35 v := reflect.MakeFunc(fn.Type(), swap)
37 // Assign it to the value fn represents.
38 fn.Set(v)
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))
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))
51 // Output:
52 // 1 0
53 // 3.14 2.72
56 func ExampleStructTag() {
57 type S struct {
58 F string `species:"gopher" color:"blue"`
61 s := S{}
62 st := reflect.TypeOf(s)
63 field := st.Field(0)
64 fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
66 // Output:
67 // blue gopher
70 func ExampleStructTag_Lookup() {
71 type S struct {
72 F0 string `alias:"field_0"`
73 F1 string `alias:""`
74 F2 string
77 s := S{}
78 st := reflect.TypeOf(s)
79 for i := 0; i < st.NumField(); i++ {
80 field := st.Field(i)
81 if alias, ok := field.Tag.Lookup("alias"); ok {
82 if alias == "" {
83 fmt.Println("(blank)")
84 } else {
85 fmt.Println(alias)
87 } else {
88 fmt.Println("(not specified)")
92 // Output:
93 // field_0
94 // (blank)
95 // (not specified)
98 func ExampleTypeOf() {
99 // As interface types are only used for static typing, a
100 // common idiom to find the reflection Type for an interface
101 // type Foo is to use a *Foo value.
102 writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
104 fileType := reflect.TypeOf((*os.File)(nil))
105 fmt.Println(fileType.Implements(writerType))
107 // Output:
108 // true