你不能做什么?
反射有一个很大的限制。虽然可以使用反射来创建新函数,但无法在运行时创建新方法。这意味着你不能在运行时使用反射来实现接口。这也意味着使用反射来创建新的结构可能会以奇怪的方式中断。当你从结构体字段切片创建新结构体时,通过匿名结构体字段进行交互存在一些问题。
大多数时候,当结构中有一个字段时,需要给它一个名称。在此示例中,我们有两种类型:Foo 和 Bar:
package main
import (
"fmt"
// "reflect"
)
type Foo struct {
A int
}
func (f Foo) Double() int {
fmt.Printf("instance is :%#v", f)
return f.A * 2
}
type Bar struct {
Foo
B int
}
type Doubler interface {
Double() int
}
func DoDouble(d Doubler) {
fmt.Println(d.Double())
}
func main() {
f := Foo{10}