golang博客里有一个例子。下面两段程序的结果是相同的。
package main
import (
    "fmt"
    "reflect"
)

type A struct {
    Name string
}
func (p A) test(){}
func (p A) Test1(){
    fmt.Println("df")
}

type AInterface interface {
    Test1()
    test()
}

func main() {
    var a A
    a.Name = "hha"
    var value reflect.Value = reflect.ValueOf(a)
    p := value.Interface().(AInterface)
    p.Test1()
}
package main
import (
    "fmt"
    "reflect"
)

type A struct {
    Name string
}
func (p A) test(){}
func (p A) Test1(){
    fmt.Println("df")
}

func main() {
    var a A
    a.Name = "hha"
    var value reflect.Value = reflect.ValueOf(a)
    vf := value.MethodByName("Test1")
    in := make([]reflect.Value, 0)
    vf.Call(in)
}
遗憾的是第一种方法事先定义好了interface,如果你加入的新方法应该是不能成功的。

上一篇:
下一篇:

相关文章:

Categories: 博客记录

0 Responses so far.

Leave a Reply