package main
import (
"fmt"
"reflect"
)
//接口类型I1
type I1 interface{
M1()
}
//接口类型I2
type I2 interface{
M2()
}
//非接口类型T
type T struct{
V int
}
/非接口类型T同时实现了I1和I2
func (*T) M1(){}
func (*T) M2(){}
//接受接口I2为参数的函数
func F(I2)(){}
func main(){
var i1 I1 = &T{V:1} //隐式转换,将类型T的值转换成接口值i1
fmt.Println(reflect.TypeOf(i1),i1) //*main.T &{1}
//F(i1) //直接用I1类型的值作为参数,编译报错:
//cannot use i1 (variable of type I1) as type I2 in argument to F:
//I1 does not implement I2 (missing M2 method)
i2,ok := i1.(I2) //将接口I1的值(动态类型为*T)转换为接口I2类型的值:
//因为*T同时实现I1和I2,所以断言会成功,输出I2类型的值
fmt.Println(reflect.TypeOf(i2),i2, ok) // *main.T &{1} true
F(i2) //传类型断言后的值,ok
}