网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
}
###### 使用反射读取字段值
然后,编写一个函数来使用反射读取`Person`结构体实例的字段值:
package main
import (
“fmt”
“reflect”
)
func printFields(person interface{}) {
val := reflect.ValueOf(person)
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
value := val.Field(i)
fmt.Printf("%s: %v\n", field.Name, value.Interface())
}
}
###### 使用反射设置字段值
接下来,编写一个函数来使用反射设置`Person`结构体实例的字段值:
func setAge(person interface{}, newAge int) {
val := reflect.ValueOf(person).Elem()
ageField := val.FieldByName(“Age”)
if ageField.IsValid() && ageField.CanSet() {
ageField.SetInt(int64(newAge))
}
}
###### 包含主函数的完整代码
最后,编写主函数来演示如何使用上述函数:
package main
import (
“fmt”
“reflect”
)
type Person struct {
Name string
Age int
}
func printFields(person interface{}) {
val := reflect.ValueOf(person)
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
value := val.Field(i)
fmt.Printf("%s: %v\n", field.Name, value.Interface())
}
}
func setAge(person interface{}, newAge int) {
val := reflect.ValueOf(person).Elem()
ageField := val.FieldByName(“Age”)
if ageField.IsValid() && ageField.CanSet() {
ageField.SetInt(int64(newAge))
}
}
func main() {
p := Person{Name: “John Doe”, Age: 30}
fmt.Println(“Before setting age:”)
printFields§
setAge(&p, 31) // 注意:传递p的指针
fmt.Println("After setting age:")
printFields(p)
}
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
s/618658159)**
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!