一个value同时满足两种interface

这是一个小示例,说明一个 value 同时可以既是这种 interface 又是那种 interface。

package main

import "fmt"

type Ia interface {
	myMethod1()
}

type Ib interface {
	myMethod2()
}

type myInt int

func (myInt) myMethod1() {}
func (myInt) myMethod2() {}

func main() {
	var i interface{}
	i = myInt(1)
	if _, ok := i.(Ia); ok {
		fmt.Println("I'm Ia.")
	}
	if _, ok := i.(Ib); ok {
		fmt.Println("I'm Ib.")
	}
}

  

其中,i 不能是 non-interface type, 可以是 interface{} 或者 Ia 或者 Ib。

原文地址:https://www.cnblogs.com/ahui2017/p/6583212.html