Go语言接口
官网介绍:go.dev/ref/spec#In…
An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface. The value of an uninitialized variable of interface type is nil.
接口类型指定一个名为其interface的方法集。接口类型的变量可以存储任何类型的值,其方法集是接口的任何超集。这样的类型被称为实现接口。未初始化的接口类型变量的值为空。
简单使用
package main import "fmt" type Leaner interface { toLearning() } type Stu struct { Name string Role string } type Tea struct { Name string Role string } func (s Stu) toLearning() { fmt.Println("I am " + s.Name + " a " + s.Role + "and I love Study.") } func (t Tea) toLearning() { fmt.Println("I am " + t.Name + " a " + t.Role + "and I love Study.") } func main() { s := Stu{Name: "zs", Role: "teacher"} s.toLearning() t := Tea{Name: "ls", Role: "Student"} t.toLearning() } 复制代码
网络异常,图片无法展示
|
接口使用的注意事项:
接口可以嵌套,但是不能嵌套自己,也不能循环嵌套
例如:
// 正确:可以进行嵌套 type inter1 interface{ sayHello() } type inter2 interface{ inter1 sayHi() } // 错误:Bad 不能嵌入自己 type Bad interface { Bad } // 错误:Bad1 不能使用 Bad2 嵌入自己 type Bad1 interface { Bad2 } type Bad2 interface { Bad1 } 复制代码
interface在Map类型中的使用
interface在Go语言中可以被认为是最高级别的泛型,可以类比与Java的Object,在Map数据类型中的使用比较广泛。
示例:
func main() { myMap := map[string]interface{}{ "id": 1, "name": "zs", "age": 100, } for k, v := range myMap { fmt.Print(k+"---") fmt.Print(v) fmt.Println() } }