Go语言通过reflect包实现反射,可动态获取类型和值。1. 使用reflect.TypeOf和ValueOf获取变量的类型与值,Kind返回底层数据结构;2. 遍历结构体字段需传入指针并调用Elem(),结合Tag信息可实现序列化等操作;3. 修改字段前需调用CanSet()判断可设置性,仅当值可寻址时才能修改;4. 通过MethodByName查找方法并用Call调用,参数以[]reflect.Value传递。这些机制广泛应用于通用库、ORM和序列化场景。

Go语言的反射机制通过reflect包实现,能够在运行时动态获取变量的类型和值,并进行操作。反射在编写通用库、序列化、ORM等场景中非常有用。以下是Go反射的基础语法与实用示例。
使用reflect.TypeOf获取变量的类型,reflect.ValueOf获取其值。
package main
import (
"fmt"
"reflect"
)
func main() {
var x int = 42
t := reflect.TypeOf(x) // 类型信息
v := reflect.ValueOf(x) // 值信息
fmt.Println("Type:", t) // int
fmt.Println("Value:", v) // 42
fmt.Println("Kind:", v.Kind()) // int
}
Type表示类型元数据,Value表示具体值。注意Kind返回的是底层数据结构(如int、struct、slice等)。
反射可以遍历结构体字段,读取或修改其值(需传入指针)。
立即学习“go语言免费学习笔记(深入)”;
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func inspectStruct(s interface{}) {
v := reflect.ValueOf(s).Elem()
t := v.Type()
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
structField := t.Field(i)
tag := structField.Tag.Get("json")
fmt.Printf("Field: %s, Value: %v, Tag: %s\n",
structField.Name, field.Interface(), tag)
}
}
func main() {
p := &Person{Name: "Alice", Age: 30}
inspectStruct(p)
}
输出:
Field: Name, Value: Alice, Tag: name Field: Age, Value: 30, Tag: age
注意要传入指针并调用Elem()获取指向的值,否则无法修改。
只有可寻址的reflect.Value才能修改值,通常需传入指针。
func setAge(obj interface{}, newAge int) {
v := reflect.ValueOf(obj).Elem()
ageField := v.FieldByName("Age")
if ageField.CanSet() {
ageField.SetInt(int64(newAge))
}
}
func main() {
p := &Person{Name: "Bob", Age: 25}
setAge(p, 35)
fmt.Println(*p) // {Bob 35}
}
CanSet()判断字段是否可被修改,未导出字段或非指针传递会导致不可设。
反射可以动态调用结构体的方法。
func (p Person) Greet() {
fmt.Printf("Hello, I'm %s, %d years old.\n", p.Name, p.Age)
}
func callMethod(obj interface{}, methodName string) {
v := reflect.ValueOf(obj)
method := v.MethodByName(methodName)
if method.IsValid() {
method.Call(nil) // 无参数调用
}
}
func main() {
p := &Person{Name: "Charlie", Age: 28}
callMethod(p, "Greet") // 输出问候语
}
Call接收一个[]reflect.Value作为参数列表,例如method.Call([]reflect.Value{})。
以上就是Golang反射语法基础与示例代码的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号