接口这部分教程有两个部分。

什么是接口?


在 Go 中,接口是一组方法签名。当一个类型为接口中的所有方法提供定义时,就可以说它实现了接口。它与 OOP 世界非常相似。接口指定类型应具有的方法,类型决定如何实现这些方法。

例如,WashingMachine 可以是具有方法签名 Cleaning() Drying() 的接口。任何提供 Cleaning()Drying()__ 定义的类型都被认为实现了 WashingMachine 接口。

声明并实现接口


让我们通过一个程序来创建和实现一个接口。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. //interface definition
  6. type VowelsFinder interface {
  7. FindVowels() []rune
  8. }
  9. type MyString string
  10. //MyString implements VowelsFinder
  11. func (ms MyString) FindVowels() []rune {
  12. var vowels []rune
  13. for _, rune := range ms {
  14. if rune == 'a' || rune == 'e' || rune == 'i' || rune == 'o' || rune == 'u' {
  15. vowels = append(vowels, rune)
  16. }
  17. }
  18. return vowels
  19. }
  20. func main() {
  21. name := MyString("Sam Anderson")
  22. var v VowelsFinder
  23. v = name // possible since MyString implements VowelsFinder
  24. fmt.Printf("Vowels are %c", v.FindVowels())
  25. }

Run in playground

在程序第 8 行中创建了一个 VowelsFinder 接口类型,它具有一个方法 FindVowels() []rune。

下一行中 MyString 类型被创建。

程序第 15 行中,我们将方法 **FindVowels() []rune 添加到接收器类型 MyString。现在 MyString 实现了 VowelsFinder** 接口。这与 Java 等其他语言完全不同,其中类必须明确声明它使用 implements 关键字实现接口。如果类型包含接口中声明的所有方法**Go 中就不需要,因为 Go 的接口是隐式实现的**。
**
程序第 28 行中,我们将类型为 MyStringname 分配给 VowelsFinder 类型的 v。这是被允许的,因为 MyString 实现了 VowelsFinder。 v.FindVowels() 在下一行调用MyString 类型的 FindVowels 方法并输出字符串 Sam Anderson 中的所有元音。程序输出 Vowels are [a e o]。

日常中使用接口


上面的例子告诉我们如何创建和实现接口,但它并没有真正展示接口的实际用途。 如果我们在上面的程序中使用 name.FindVowels() 而不是 v.FindVowels(),它也会工作,并且不会使用创建的接口。

现在让我们来看一下接口的实际用法。

我们将编写一个简单的程序,根据员工的个人工资计算公司的总支出。为了描述简洁方便点,我们假设所有费用均以美元计算。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type SalaryCalculator interface {
  6. CalculateSalary() int
  7. }
  8. type Permanent struct {
  9. empId int
  10. basicpay int
  11. pf int
  12. }
  13. type Contract struct {
  14. empId int
  15. basicpay int
  16. }
  17. //salary of permanent employee is sum of basic pay and pf
  18. func (p Permanent) CalculateSalary() int {
  19. return p.basicpay + p.pf
  20. }
  21. //salary of contract employee is the basic pay alone
  22. func (c Contract) CalculateSalary() int {
  23. return c.basicpay
  24. }
  25. /*
  26. total expense is calculated by iterating though the SalaryCalculator slice and summing
  27. the salaries of the individual employees
  28. */
  29. func totalExpense(s []SalaryCalculator) {
  30. expense := 0
  31. for _, v := range s {
  32. expense = expense + v.CalculateSalary()
  33. }
  34. fmt.Printf("Total Expense Per Month $%d", expense)
  35. }
  36. func main() {
  37. pemp1 := Permanent{1, 5000, 20}
  38. pemp2 := Permanent{2, 6000, 30}
  39. cemp1 := Contract{3, 3000}
  40. employees := []SalaryCalculator{pemp1, pemp2, cemp1}
  41. totalExpense(employees)
  42. }

Run in playground

在程序第7行中使用了一个方法 CalculateSalary() int 声明了接口 SalaryCalculator

公司有两种员工,第 11 和 17 行定义了结构 Permanent 和 Contract。长期雇员的工资是 basicpay 和 pf 的总和,而对于合同雇员来说,只有 basicpay。第 23 和 28 行中 CalculateSalary 方法中代码相对应的实现了这一点。通过声明此方法,PermanentContract 现在都实现了 SalaryCalculator 接口。

第 36 行中声明的 totalExpense 函数表达了使用接口的美妙之处。此方法将SalaryCalculator 接口 []SalaryCalculator 切片作为参数。第 49 行我们将一个包含PermanentContract 类型的切片传递给 totalExpense 函数。totalExpense 函数通过调用相应类型的 CalculateSalary 方法来计算费用,这在第 39 行中完成。

程序输出

  1. Total Expense Per Month $14050

这样做的最大好处是 totalExpense 可以扩展到任何新员工类型,而无需更改任何代码。让我们说公司增加了一种具有不同薪资结构的新类型的员工 Freelancer 。这个Freelancer可以在切片参数中传递给 totalExpense ,甚至没有一行代码更改为totalExpense 函数。这个方法将做它应该做的事情,因为 Freelancer 也将实现SalaryCalculator 接口:)

让我们修改这个程序,添加新的 Freelancer(自由职业者) 员工。自由职业者的工资是每小时工资和总工作小时数的乘积。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type SalaryCalculator interface {
  6. CalculateSalary() int
  7. }
  8. type Permanent struct {
  9. empId int
  10. basicpay int
  11. pf int
  12. }
  13. type Contract struct {
  14. empId int
  15. basicpay int
  16. }
  17. type Freelancer struct {
  18. empId int
  19. ratePerHour int
  20. totalHours int
  21. }
  22. //salary of permanent employee is sum of basic pay and pf
  23. func (p Permanent) CalculateSalary() int {
  24. return p.basicpay + p.pf
  25. }
  26. //salary of contract employee is the basic pay alone
  27. func (c Contract) CalculateSalary() int {
  28. return c.basicpay
  29. }
  30. //salary of freelancer
  31. func (f Freelancer) CalculateSalary() int {
  32. return f.ratePerHour * f.totalHours
  33. }
  34. /*
  35. total expense is calculated by iterating through the SalaryCalculator slice and summing
  36. the salaries of the individual employees
  37. */
  38. func totalExpense(s []SalaryCalculator) {
  39. expense := 0
  40. for _, v := range s {
  41. expense = expense + v.CalculateSalary()
  42. }
  43. fmt.Printf("Total Expense Per Month $%d", expense)
  44. }
  45. func main() {
  46. pemp1 := Permanent{
  47. empId: 1,
  48. basicpay: 5000,
  49. pf: 20,
  50. }
  51. pemp2 := Permanent{
  52. empId: 2,
  53. basicpay: 6000,
  54. pf: 30,
  55. }
  56. cemp1 := Contract{
  57. empId: 3,
  58. basicpay: 3000,
  59. }
  60. freelancer1 := Freelancer{
  61. empId: 4,
  62. ratePerHour: 70,
  63. totalHours: 120,
  64. }
  65. freelancer2 := Freelancer{
  66. empId: 5,
  67. ratePerHour: 100,
  68. totalHours: 100,
  69. }
  70. employees := []SalaryCalculator{pemp1, pemp2, cemp1, freelancer1, freelancer2}
  71. totalExpense(employees)
  72. }

Run in playground

我们在第 22 行添加了 Freelancer 结构,并在第 39 行声明了 CalculateSalary 方法。由于 Freelancer 结构也实现了 SalaryCalculator 接口,所以在 totalExpense 方法中不需要修改其他代码。我们在 main 方法中添加了几个Freelancer 雇员。这个程序打印,

  1. Total Expense Per Month $32450

接口的内部组成


接口可以被认为是由元组 (type, value) 在内部组成的。 type 是接口的基础具体类型,value 保存具体类型的值。

让我们通过一个程序来更好地理解。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Worker interface {
  6. Work()
  7. }
  8. type Person struct {
  9. name string
  10. }
  11. func (p Person) Work() {
  12. fmt.Println(p.name, "is working")
  13. }
  14. func describe(w Worker) {
  15. fmt.Printf("Interface type %T value %v\n", w, w)
  16. }
  17. func main() {
  18. p := Person{
  19. name: "Naveen",
  20. }
  21. var w Worker = p
  22. describe(w)
  23. w.Work()
  24. }

Run in playground

Worker 接口有一个方法 Work(),Person 结构类型实现了该接口。在第 27 行,我们将 Person 类型的变量 p 赋值给 Worker 类型的 w。现在 w 的具体类型是 Person,它包含了一个 name 字段为 Naveen 的 Person。第 17 行中的 describe 函数打印了接口的值和具体类型。这个程序输出

  1. Interface type main.Person value {Naveen}
  2. Naveen is working

我们在接下来的章节中更多地讨论如何提取接口的底层的值。

空接口

具有零方法的接口称为空接口。即它表示为 interface{}。由于空接口的方法为零,因此所有类型都实现空接口。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func describe(i interface{}) {
  6. fmt.Printf("Type = %T, value = %v\n", i, i)
  7. }
  8. func main() {
  9. s := "Hello World"
  10. describe(s)
  11. i := 55
  12. describe(i)
  13. strt := struct {
  14. name string
  15. }{
  16. name: "Naveen R",
  17. }
  18. describe(strt)
  19. }

Run in playground

在上面的程序中,在第 7 行中,describe(i interface{}) 函数将空接口作为参数,因此可以传递任何类型。

我们将 string,int 和 struct 传递给第 13,15 和 21 行中的 describe 函数。这个程序输出,

  1. Type = string, value = Hello World
  2. Type = int, value = 55
  3. Type = struct { name string }, value = {Naveen R}


类型断言


类型断言用于提取接口的基础值。

i.(T) 是用于获取具体类型为 T 的接口 i 的基础值的语法。

一个程序胜过千言万语😀,让我们写一个类型断言。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func assert(i interface{}) {
  6. s := i.(int) //get the underlying int value from i
  7. fmt.Println(s)
  8. }
  9. func main() {
  10. var s interface{} = 56
  11. assert(s)
  12. }

Run in playground

第 13 行中 s 的具体类型是 int。我们在第 8 行中使用语法 i.(int) 获取 i 的 int 值。该程序输出 56。

如果上述程序中的具体类型不是 int,会发生什么呢?

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func assert(i interface{}) {
  6. s := i.(int)
  7. fmt.Println(s)
  8. }
  9. func main() {
  10. var s interface{} = "Steven Paul"
  11. assert(s)
  12. }

Run in playground

在上面的程序中,我们将 s 具体类型 string 传递给 assert 函数,该函数尝试从中提取 int值。该程序将报错 panic: interface conversion: interface {} is string, not int

要解决上述问题,我们可以使用语法

  1. v, ok := i.(T)

如果 i 的具体类型是 T,则 v 将具有 i 的基础值,ok 将为真。

如果 i 的具体类型不是 T,那么 ok 将为 false 并且 v 将具有类型 T 的零值并且程序将不会报错。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func assert(i interface{}) {
  6. v, ok := i.(int)
  7. fmt.Println(v, ok)
  8. }
  9. func main() {
  10. var s interface{} = 56
  11. assert(s)
  12. var i interface{} = "Steven Paul"
  13. assert(i)
  14. }

Run in playground

当 Steven Paul 传递给 assert 函数时,ok 将为 false,因为 i 的具体类型不是 int 而 v为 0。该程序将输出,

  1. 56 true
  2. 0 false


类型Switch


类型 switch 用于将接口的具体类型与各种 case 语句中指定的多种类型进行比较。它类似于 switch case。唯一的区别是 cases 指定类型而不是正常 switch 中的值。

type switch 的语法类似于 Type 断言。在类型断言的语法 i.(T) 中,类型 T 应该替换为类型 switch 的关键字 type。让我们看看下面的程序如何工作。

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func findType(i interface{}) {
  6. switch i.(type) {
  7. case string:
  8. fmt.Printf("I am a string and my value is %s\n", i.(string))
  9. case int:
  10. fmt.Printf("I am an int and my value is %d\n", i.(int))
  11. default:
  12. fmt.Printf("Unknown type\n")
  13. }
  14. }
  15. func main() {
  16. findType("Naveen")
  17. findType(77)
  18. findType(89.98)
  19. }

Run in playground

上面程序第 8 行中,switch i.(type) 指定了类型 switch。每个 case 语句都将 i 的具体类型与特定类型进行比较。如果任何情况匹配,则输出相应的语句。该程序输出,

  1. I am a string and my value is Naveen
  2. I am an int and my value is 77
  3. Unknown type

第 20 行中 89.98 是 float64 类型,不匹配任何情况,因此在最后一行输出 Unknown type。

还可以将类型与接口进行比较。如果我们有一个类型,并且该类型实现了一个接口,则可以将该类型与它实现的接口进行比较。

让我们写一个程序。

  1. package main
  2. import "fmt"
  3. type Describer interface {
  4. Describe()
  5. }
  6. type Person struct {
  7. name string
  8. age int
  9. }
  10. func (p Person) Describe() {
  11. fmt.Printf("%s is %d years old", p.name, p.age)
  12. }
  13. func findType(i interface{}) {
  14. switch v := i.(type) {
  15. case Describer:
  16. v.Describe()
  17. default:
  18. fmt.Printf("unknown type\n")
  19. }
  20. }
  21. func main() {
  22. findType("Naveen")
  23. p := Person{
  24. name: "Naveen R",
  25. age: 25,
  26. }
  27. findType(p)
  28. }

Run in playground

在上面的程序中,Person 结构实现了 Describer 接口。在第 19 行中的 case 语句中,将 v 与 Describer 接口类型进行比较。 p 实现了 Describer,因此满足了这种情况,在第 32 行中 findType(p),调用 Describe() 方法。

程序输出

  1. unknown type
  2. Naveen R is 25 years old


原文链接


https://golangbot.com/interfaces-part-1/