-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreflection.go
61 lines (49 loc) · 1.21 KB
/
reflection.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
package main
import (
"fmt"
"reflect"
)
type Person struct {
Name string
Age int
Address string
}
func inspectStruct(person interface{}) {
valueOf := reflect.ValueOf(person)
typeOf := reflect.TypeOf(person)
fmt.Printf("Type: %v\n", typeOf)
if valueOf.Kind() == reflect.Struct {
fmt.Printf("Fields:\n")
for i := 0; i < valueOf.NumField(); i++ {
field := valueOf.Field(i)
fieldName := typeOf.Field(i).Name
fieldType := field.Type()
fieldValue := field.Interface()
fmt.Printf("%s (%v): %v\n", fieldName, fieldType, fieldValue)
}
}
}
func setField(person interface{}, fieldName string, newValue interface{}) {
valueOf := reflect.ValueOf(person).Elem()
field := valueOf.FieldByName(fieldName)
if field.IsValid() && field.CanSet() {
newFieldValue := reflect.ValueOf(newValue)
if newFieldValue.Type() == field.Type() {
field.Set(newFieldValue)
} else {
fmt.Printf("Error: Type mismatch for field %s\n", fieldName)
}
} else {
fmt.Printf("Error: Field %s not found or cannot be set\n", fieldName)
}
}
func main() {
person := Person{
Name: "Joan Clarke",
Age: 30,
Address: "123 Main St",
}
inspectStruct(person)
setField(&person, "Age", 35)
inspectStruct(person)
}