// xuhh_go_interface
project
main.go
/*
interface : 是一系列(一个或者多个)方法的合集,任何类型的方法合集(拥有相同函数名称、参数列表(不含参数名)、返回值)
只要包含与之对应的方法,则它就实现了该接口(意思就是可以进行赋值),无需另外添加声明。
1. 接口只有函数声明,没有函数的实现。接口后面一般已er结束
2. 接口中没有数据字段,而且接口可以嵌套,一种类型可以包含多个接口。
*/package main import ( "fmt" ) type IAdditioner interface { Addition() int } type IMultiplicationer interface { Multiplication() int } type IMather interface { IAdditioner IMultiplicationer } type _SMathTransform struct { num int } func (s *_SMathTransform) Addition() int { return s.num + 1 } func (s *_SMathTransform) Multiplication() int { return s.num * 1 } type _SMath struct { nLeft int nRight int } func (a *_SMath) Addition() int { return a.nLeft + a.nRight } func (a *_SMath) Substruction() int { if a.nLeft > a.nRight { return a.nLeft - a.nRight } else { return a.nRight - a.nLeft } } func PrintAnything(v interface{}) { fmt.Println("print : ", v) } type IStringer interface { String() string } type _String struct { id string name string } func (s *_String) String() string { return fmt.Sprintf("%s, %s", s.id, s.name) } func String() string { return fmt.Sprintf("hello world") } //将接口 赋值给函数,直接实现,有时会省下不少事情 type IFunctioner interface { DoSomething() } type Function func() func (funct Function) DoSomething() { funct() } func main() { a := _SMath{1, 2} var IAdd IAdditioner = &_SMath{3, 4} fmt.Println(IAdd.Addition()) IAdd = &a fmt.Println(IAdd.Addition()) //空接口 PrintAnything("Hello World!") //接口推断和查询 var inter interface{} = &_String{"1", "nike"} if v, ok := inter.(fmt.Stringer); ok { fmt.Println(v) } var inter1 interface{} if v, ok := inter1.(func() string); ok { fmt.Println("this is function", v) } var interSt IStringer = &_String{"2", "lisa"} switch value := interSt.(type) { case nil: fmt.Println("this interface is null") case IStringer: fmt.Println(value.String()) case (*_String): fmt.Println("id == ", value.id, "name == ", value.name) default: fmt.Println("this interface is other interface") } //接口转换 var iadd IAdditioner = &_SMath{4, 5} var imath IMather = &_SMathTransform{10} fmt.Println(iadd.Addition()) //imath = imuli 大的集合可以赋值给小的集合,相反不行 iadd = imath if v, ok := iadd.(IMather); ok { fmt.Println("this interface is IMather", v.Addition(), v.Multiplication()) } //函数实现接口 var function IFunctioner = Function{func() { PrintAnything("HELLO ,WORLD") }} }
有疑问加站长微信联系(非本文作者)