golang interface 用法
Golang 中的 interface 是一种类型,可以用于定义一组方法集合,任何实现了这个方法集的类型都可以被视为这个 interface 的实现类型。在 Golang 中,interface 可以用于实现多态,使得代码更加灵活和可扩展。
interface 的定义方式如下:
type MyInterface interface {
Method1()
Method2() int
Method3(string) (bool, error)
}
上述代码定义了一个 MyInterface 接口,包含三个方法:Method1、Method2 和 Method3。任何实现了这三个方法的类型都可以被视为 MyInterface 接口的实现类型。
下面是一个示例:
type MyStruct struct {}
func (m MyStruct) Method1() {
fmt.Println("Method1")
}
func (m MyStruct) Method2() int {
fmt.Println("Method2")
return 1
}
func (m MyStruct) Method3(s string) (bool, error) {
fmt.Println("Method3")
return true, nil
}
func main() {
var i MyInterface = MyStruct{}
i.Method1()
i.Method2()
i.Method3("")
}
上述代码定义了一个 MyStruct 类型,并实现了 MyInterface 接口中的三个方法。在 main 函数中,通过将 MyStruct 类型实例化并赋值给 MyInterface 类型变量 i,实现了多态。可以看到,i 可以调用 MyInterface 中定义的三个方法。
总之,interface 是 Golang 中实现多态的关键,通过将不同实现转换为相同的接口类型,可以让代码更加灵活和可扩展。
原文地址: http://www.cveoy.top/t/topic/IAI 著作权归作者所有。请勿转载和采集!