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.
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
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.
41 // Make and call a swap function for ints.
42 var intSwap
func(int, int) (int, int)
44 fmt
.Println(intSwap(0, 1))
46 // Make and call a swap function for float64s.
47 var floatSwap
func(float64, float64) (float64, float64)
49 fmt
.Println(floatSwap(2.72, 3.14))
56 func ExampleStructTag() {
58 F
string `species:"gopher" color:"blue"`
62 st
:= reflect
.TypeOf(s
)
64 fmt
.Println(field
.Tag
.Get("color"), field
.Tag
.Get("species"))
70 func ExampleStructTag_Lookup() {
72 F0
string `alias:"field_0"`
78 st
:= reflect
.TypeOf(s
)
79 for i
:= 0; i
< st
.NumField(); i
++ {
81 if alias
, ok
:= field
.Tag
.Lookup("alias"); ok
{
83 fmt
.Println("(blank)")
88 fmt
.Println("(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
))