接口这部分教程有两个部分。
什么是接口?
在 Go 中,接口是一组方法签名。当一个类型为接口中的所有方法提供定义时,就可以说它实现了接口。它与 OOP 世界非常相似。接口指定类型应具有的方法,类型决定如何实现这些方法。
例如,WashingMachine 可以是具有方法签名 Cleaning() 和 Drying() 的接口。任何提供 Cleaning() 和 Drying()__ 定义的类型都被认为实现了 WashingMachine 接口。
声明并实现接口
让我们通过一个程序来创建和实现一个接口。
package mainimport ("fmt")//interface definitiontype VowelsFinder interface {FindVowels() []rune}type MyString string//MyString implements VowelsFinderfunc (ms MyString) FindVowels() []rune {var vowels []runefor _, rune := range ms {if rune == 'a' || rune == 'e' || rune == 'i' || rune == 'o' || rune == 'u' {vowels = append(vowels, rune)}}return vowels}func main() {name := MyString("Sam Anderson")var v VowelsFinderv = name // possible since MyString implements VowelsFinderfmt.Printf("Vowels are %c", v.FindVowels())}
在程序第 8 行中创建了一个 VowelsFinder 接口类型,它具有一个方法 FindVowels() []rune。
下一行中 MyString 类型被创建。
程序第 15 行中,我们将方法 **FindVowels() []rune 添加到接收器类型 MyString。现在 MyString 实现了 VowelsFinder** 接口。这与 Java 等其他语言完全不同,其中类必须明确声明它使用 implements 关键字实现接口。如果类型包含接口中声明的所有方法**,在 Go 中就不需要,因为 Go 的接口是隐式实现的**。
**
程序第 28 行中,我们将类型为 MyString 的 name 分配给 VowelsFinder 类型的 v。这是被允许的,因为 MyString 实现了 VowelsFinder。 v.FindVowels() 在下一行调用MyString 类型的 FindVowels 方法并输出字符串 Sam Anderson 中的所有元音。程序输出 Vowels are [a e o]。
日常中使用接口
上面的例子告诉我们如何创建和实现接口,但它并没有真正展示接口的实际用途。 如果我们在上面的程序中使用 name.FindVowels() 而不是 v.FindVowels(),它也会工作,并且不会使用创建的接口。
现在让我们来看一下接口的实际用法。
我们将编写一个简单的程序,根据员工的个人工资计算公司的总支出。为了描述简洁方便点,我们假设所有费用均以美元计算。
package mainimport ("fmt")type SalaryCalculator interface {CalculateSalary() int}type Permanent struct {empId intbasicpay intpf int}type Contract struct {empId intbasicpay int}//salary of permanent employee is sum of basic pay and pffunc (p Permanent) CalculateSalary() int {return p.basicpay + p.pf}//salary of contract employee is the basic pay alonefunc (c Contract) CalculateSalary() int {return c.basicpay}/*total expense is calculated by iterating though the SalaryCalculator slice and summingthe salaries of the individual employees*/func totalExpense(s []SalaryCalculator) {expense := 0for _, v := range s {expense = expense + v.CalculateSalary()}fmt.Printf("Total Expense Per Month $%d", expense)}func main() {pemp1 := Permanent{1, 5000, 20}pemp2 := Permanent{2, 6000, 30}cemp1 := Contract{3, 3000}employees := []SalaryCalculator{pemp1, pemp2, cemp1}totalExpense(employees)}
在程序第7行中使用了一个方法 CalculateSalary() int 声明了接口 SalaryCalculator 。
公司有两种员工,第 11 和 17 行定义了结构 Permanent 和 Contract。长期雇员的工资是 basicpay 和 pf 的总和,而对于合同雇员来说,只有 basicpay。第 23 和 28 行中 CalculateSalary 方法中代码相对应的实现了这一点。通过声明此方法,Permanent 和 Contract 现在都实现了 SalaryCalculator 接口。
第 36 行中声明的 totalExpense 函数表达了使用接口的美妙之处。此方法将SalaryCalculator 接口 []SalaryCalculator 切片作为参数。第 49 行我们将一个包含Permanent 和 Contract 类型的切片传递给 totalExpense 函数。totalExpense 函数通过调用相应类型的 CalculateSalary 方法来计算费用,这在第 39 行中完成。
程序输出
Total Expense Per Month $14050
这样做的最大好处是 totalExpense 可以扩展到任何新员工类型,而无需更改任何代码。让我们说公司增加了一种具有不同薪资结构的新类型的员工 Freelancer 。这个Freelancer可以在切片参数中传递给 totalExpense ,甚至没有一行代码更改为totalExpense 函数。这个方法将做它应该做的事情,因为 Freelancer 也将实现SalaryCalculator 接口:)
让我们修改这个程序,添加新的 Freelancer(自由职业者) 员工。自由职业者的工资是每小时工资和总工作小时数的乘积。
package mainimport ("fmt")type SalaryCalculator interface {CalculateSalary() int}type Permanent struct {empId intbasicpay intpf int}type Contract struct {empId intbasicpay int}type Freelancer struct {empId intratePerHour inttotalHours int}//salary of permanent employee is sum of basic pay and pffunc (p Permanent) CalculateSalary() int {return p.basicpay + p.pf}//salary of contract employee is the basic pay alonefunc (c Contract) CalculateSalary() int {return c.basicpay}//salary of freelancerfunc (f Freelancer) CalculateSalary() int {return f.ratePerHour * f.totalHours}/*total expense is calculated by iterating through the SalaryCalculator slice and summingthe salaries of the individual employees*/func totalExpense(s []SalaryCalculator) {expense := 0for _, v := range s {expense = expense + v.CalculateSalary()}fmt.Printf("Total Expense Per Month $%d", expense)}func main() {pemp1 := Permanent{empId: 1,basicpay: 5000,pf: 20,}pemp2 := Permanent{empId: 2,basicpay: 6000,pf: 30,}cemp1 := Contract{empId: 3,basicpay: 3000,}freelancer1 := Freelancer{empId: 4,ratePerHour: 70,totalHours: 120,}freelancer2 := Freelancer{empId: 5,ratePerHour: 100,totalHours: 100,}employees := []SalaryCalculator{pemp1, pemp2, cemp1, freelancer1, freelancer2}totalExpense(employees)}
我们在第 22 行添加了 Freelancer 结构,并在第 39 行声明了 CalculateSalary 方法。由于 Freelancer 结构也实现了 SalaryCalculator 接口,所以在 totalExpense 方法中不需要修改其他代码。我们在 main 方法中添加了几个Freelancer 雇员。这个程序打印,
Total Expense Per Month $32450
接口的内部组成
接口可以被认为是由元组 (type, value) 在内部组成的。 type 是接口的基础具体类型,value 保存具体类型的值。
让我们通过一个程序来更好地理解。
package mainimport ("fmt")type Worker interface {Work()}type Person struct {name string}func (p Person) Work() {fmt.Println(p.name, "is working")}func describe(w Worker) {fmt.Printf("Interface type %T value %v\n", w, w)}func main() {p := Person{name: "Naveen",}var w Worker = pdescribe(w)w.Work()}
Worker 接口有一个方法 Work(),Person 结构类型实现了该接口。在第 27 行,我们将 Person 类型的变量 p 赋值给 Worker 类型的 w。现在 w 的具体类型是 Person,它包含了一个 name 字段为 Naveen 的 Person。第 17 行中的 describe 函数打印了接口的值和具体类型。这个程序输出
Interface type main.Person value {Naveen}Naveen is working
我们在接下来的章节中更多地讨论如何提取接口的底层的值。
空接口
具有零方法的接口称为空接口。即它表示为 interface{}。由于空接口的方法为零,因此所有类型都实现空接口。
package mainimport ("fmt")func describe(i interface{}) {fmt.Printf("Type = %T, value = %v\n", i, i)}func main() {s := "Hello World"describe(s)i := 55describe(i)strt := struct {name string}{name: "Naveen R",}describe(strt)}
在上面的程序中,在第 7 行中,describe(i interface{}) 函数将空接口作为参数,因此可以传递任何类型。
我们将 string,int 和 struct 传递给第 13,15 和 21 行中的 describe 函数。这个程序输出,
Type = string, value = Hello WorldType = int, value = 55Type = struct { name string }, value = {Naveen R}
类型断言
类型断言用于提取接口的基础值。
i.(T) 是用于获取具体类型为 T 的接口 i 的基础值的语法。
一个程序胜过千言万语😀,让我们写一个类型断言。
package mainimport ("fmt")func assert(i interface{}) {s := i.(int) //get the underlying int value from ifmt.Println(s)}func main() {var s interface{} = 56assert(s)}
第 13 行中 s 的具体类型是 int。我们在第 8 行中使用语法 i.(int) 获取 i 的 int 值。该程序输出 56。
如果上述程序中的具体类型不是 int,会发生什么呢?
package mainimport ("fmt")func assert(i interface{}) {s := i.(int)fmt.Println(s)}func main() {var s interface{} = "Steven Paul"assert(s)}
在上面的程序中,我们将 s 具体类型 string 传递给 assert 函数,该函数尝试从中提取 int值。该程序将报错 panic: interface conversion: interface {} is string, not int。
要解决上述问题,我们可以使用语法
v, ok := i.(T)
如果 i 的具体类型是 T,则 v 将具有 i 的基础值,ok 将为真。
如果 i 的具体类型不是 T,那么 ok 将为 false 并且 v 将具有类型 T 的零值并且程序将不会报错。
package mainimport ("fmt")func assert(i interface{}) {v, ok := i.(int)fmt.Println(v, ok)}func main() {var s interface{} = 56assert(s)var i interface{} = "Steven Paul"assert(i)}
当 Steven Paul 传递给 assert 函数时,ok 将为 false,因为 i 的具体类型不是 int 而 v为 0。该程序将输出,
56 true0 false
类型Switch
类型 switch 用于将接口的具体类型与各种 case 语句中指定的多种类型进行比较。它类似于  switch case。唯一的区别是 cases 指定类型而不是正常 switch 中的值。
type switch 的语法类似于 Type 断言。在类型断言的语法 i.(T) 中,类型 T 应该替换为类型 switch 的关键字 type。让我们看看下面的程序如何工作。
package mainimport ("fmt")func findType(i interface{}) {switch i.(type) {case string:fmt.Printf("I am a string and my value is %s\n", i.(string))case int:fmt.Printf("I am an int and my value is %d\n", i.(int))default:fmt.Printf("Unknown type\n")}}func main() {findType("Naveen")findType(77)findType(89.98)}
上面程序第 8 行中,switch i.(type) 指定了类型 switch。每个 case 语句都将 i 的具体类型与特定类型进行比较。如果任何情况匹配,则输出相应的语句。该程序输出,
I am a string and my value is NaveenI am an int and my value is 77Unknown type
第 20 行中 89.98 是 float64 类型,不匹配任何情况,因此在最后一行输出 Unknown type。
还可以将类型与接口进行比较。如果我们有一个类型,并且该类型实现了一个接口,则可以将该类型与它实现的接口进行比较。
让我们写一个程序。
package mainimport "fmt"type Describer interface {Describe()}type Person struct {name stringage int}func (p Person) Describe() {fmt.Printf("%s is %d years old", p.name, p.age)}func findType(i interface{}) {switch v := i.(type) {case Describer:v.Describe()default:fmt.Printf("unknown type\n")}}func main() {findType("Naveen")p := Person{name: "Naveen R",age: 25,}findType(p)}
在上面的程序中,Person 结构实现了 Describer 接口。在第 19 行中的 case 语句中,将 v 与 Describer 接口类型进行比较。 p 实现了 Describer,因此满足了这种情况,在第 32 行中 findType(p),调用 Describe() 方法。
程序输出
unknown typeNaveen R is 25 years old
