2019独角兽企业重金招聘Python工程师标准>>>
Golang接口定义使用interface来声明,它相对于其他语言最大的特定就是接口定义和实现的关联性仅仅依赖接口的名字和声明,无需显式声明。
接口定义和实现 在下面这个例子中,定义了两个自定义类型city country 和接口类型IName city、country分别实现了接口IName, 它们不需要代码上不需要去和IName关联(比如implement IName),只需要实现 IName定义的方法即可。接口更像是双方约定的协议,达到更加精炼、灵活的效果。
空接口:interface{} 它不包含任何的方法,所以类型都实现了空接口。空接口在我们需要存储任意类型的时候相当有用,非常类似C语言中void* 类型。printname 函数中输入参数就是一个空接口
接口检查 有时候需要检查某个obj是否实现了接口,可以用obj.(I)来查询它是否实现了接口 printname中 ivalue, ok := p.(IName) if !ok { fmt.Println("It is not a IName interface obj:", p) return }
接口类型 由于实现接口的obj可能有多个,如果需要确切知道是哪一个,可以使用 obj.(type)来判断。 这里有两个实现IName接口的struct, printname 中就是通过obj.(type) 来判断是city 还是country.
Code:
package mainimport ("fmt"
)type city struct {name string
}func (c city) Put(name string) {c.name = name
}func (c city) GetName() string {return c.name
}type country struct {name string
}func (c country) Put(name string) {c.name = name
}func (c country) GetName() string {return c.name
}type IName interface {Put(string)GetName() string
}//interface type and query
func printname(p interface{}) {ivalue, ok := p.(IName)if !ok {fmt.Println("It is not a IName interface obj:", p)return}switch ivalue.(type) {case *city:fmt.Println("It is a *city: ", ivalue.GetName())case *country:fmt.Println("It is a *country: ", ivalue.GetName())case city:fmt.Println("It is a city: ", ivalue.GetName())case country:fmt.Println("It is a country: ", ivalue.GetName())default:fmt.Println("It is other IName interface")}}func main() {var c1, c2, c3, c4 interface{}c1 = city{name: "Hangzhou"}c2 = country{name: "US"}c3 = &city{name: "Shanghai"}c4 = &country{name: "Japan"}fmt.Println(c1)fmt.Println(c2)fmt.Println(c3)fmt.Println(c4)//print name of object has interface INameprintname(c1)printname(c2)printname(c3)printname(c4)//print name of object not has interface INameprintname(10)printname("abc")
}
Output:
{Hangzhou}
{US}
&{Shanghai}
&{Japan}
It is a city: Hangzhou
It is a country: US
It is a *city: Shanghai
It is a *country: Japan
It is not a IName interface obj: 10
It is not a IName interface obj: abc
code : https://github.com/panyingyun/gostudy/blob/master/exp8.go