-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathstruct.go
101 lines (77 loc) · 2.04 KB
/
struct.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// All material is licensed under the Apache License Version 2.0, January 2016
// http://www.apache.org/licenses/LICENSE-2.0
// Example shows how reflection provides readability and simplicity.
package main
import (
"fmt"
"reflect"
)
// user represents a basic user in the system.
type user struct {
name string
age int
building float32
secure bool
roles []string
}
func main() {
// Create a value of the conrete type user.
u := user{
name: "Cindy",
age: 27,
building: 321.45,
secure: true,
roles: []string{"admin", "developer"},
}
// Display the value we are passing.
display(&u)
}
// display will display the details of the provided value.
func display(v interface{}) {
// Inspect the concrete type value that is passed in.
rv := reflect.ValueOf(v)
// Was the value a pointer value.
if rv.Kind() == reflect.Ptr {
// Get the value that the pointer points to.
rv = rv.Elem()
}
// Based on the Kind of value customize the display.
switch rv.Kind() {
case reflect.Struct:
displayStruct(rv)
}
}
// displayStruct will display details about a struct type.
func displayStruct(rv reflect.Value) {
// Show each field and the field information.
for i := 0; i < rv.NumField(); i++ {
// Get field information for this field.
fld := rv.Type().Field(i)
fmt.Printf("Name: %s\tKind: %s", fld.Name, fld.Type.Kind())
// Display the value of this field.
fmt.Printf("\tValue: ")
displayValue(rv.Field(i))
// Add an extra line feed for the display.
fmt.Println()
}
}
// displayValue extracts the native value from the reflect value that is
// passed in and properly displays it.
func displayValue(rv reflect.Value) {
// Display each value based on its Kind.
switch rv.Type().Kind() {
case reflect.String:
fmt.Printf("%s", rv.String())
case reflect.Int:
fmt.Printf("%v", rv.Int())
case reflect.Float32:
fmt.Printf("%v", rv.Float())
case reflect.Bool:
fmt.Printf("%v", rv.Bool())
case reflect.Slice:
for i := 0; i < rv.Len(); i++ {
displayValue(rv.Index(i))
fmt.Printf(" ")
}
}
}