Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

反射小节求更新 #15

Open
goodnull opened this issue Oct 19, 2023 · 1 comment
Open

反射小节求更新 #15

goodnull opened this issue Oct 19, 2023 · 1 comment

Comments

@goodnull
Copy link

求更新3.5反射小节

@goodnull
Copy link
Author

下面是一些常见的反射用法:

获取变量的类型信息
使用reflect.TypeOf()函数可以获取一个变量的类型信息,例如:

var x int = 10
t := reflect.TypeOf(x)
fmt.Println(t.Name(), t.Kind()) // 输出:int int

获取变量的值信息
使用reflect.ValueOf()函数可以获取一个变量的值信息,例如:

var x int = 10
v := reflect.ValueOf(x)
fmt.Println(v.Int()) // 输出:10

修改变量的值
使用reflect.ValueOf()函数获取到变量的值信息后,可以使用反射提供的一系列方法来修改变量的值,例如:

var x int = 10
v := reflect.ValueOf(&x).Elem()
v.SetInt(20)
fmt.Println(x) // 输出:20
动态调用函数
使用reflect.ValueOf()函数获取到函数的值信息后,可以使用反射提供的Call()方法来动态调用函数,例如:

func add(a, b int) int {
    return a + b
}

f := reflect.ValueOf(add)
result := f.Call([]reflect.Value{reflect.ValueOf(1), reflect.ValueOf(2)})
fmt.Println(result[0].Int()) // 输出:3

动态创建对象
使用reflect.New()函数可以动态创建一个对象,例如:

type Person struct {
    Name string
    Age  int
}

pType := reflect.TypeOf(Person{})
pValue := reflect.New(pType)
p := pValue.Interface().(*Person)
p.Name = "Alice"
p.Age = 20
fmt.Println(p) // 输出:&{Alice 20}

需要注意的是,反射的使用需要谨慎,因为它会降低代码的可读性和性能。在实际应用中,应该尽量避免过度使用反射,只在必要时才使用。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant