package main
import (
"fmt"
"reflect"
"strings"
)
type Student struct {
Name string
Age int
Addr string
}
// 遍历结构体, 只遍历,不做修改
func forStruct_1() {
s := Student{Name: "admin", Age: 18, Addr: "china"}
v := reflect.ValueOf(s)
typeOfS := v.Type()
for i := 0; i < v.NumField(); i++ {
fmt.Printf("Field: %s, Value: %s\n", typeOfS.Field(i).Name, v.Field(i).Interface())
}
fmt.Printf("%+v\n", s)
}
// 遍历结构体, 遍历同时做修改
func forStruct_2() {
s := Student{Name: "admin", Age: 18, Addr: "china"}
v := reflect.ValueOf(&s) // 想要修改结构体的值,这里必须传指针
typeOfS := v.Type().Elem()
for i := 0; i < v.Elem().NumField(); i++ { // 无法使用v.NumField, 需要改为v.Elem().NumField()
fmt.Printf("Field: %s, Value: %s\n", typeOfS.Field(i).Name, v.Elem().Field(i).Interface())
if typeOfS.Field(i).Name == "Name" {
v.Elem().Field(i).SetString("Admin2") // 修改Name字段的值
}
}
fmt.Printf("%+v\n", s)
}
func main() {
fmt.Println(strings.Repeat("=", 80))
forStruct_1()
fmt.Println(strings.Repeat("=", 80))
forStruct_2()
}
life is a game