[译] part 18: golang 接口 1

https://juejin.im/post/5cab8254e51d456e4c4bffd5

什么是接口

面向对象世界中接口的定义是“接口定义对象的行为”。它只指定对象应该做什么。实现此行为(实现细节)的方法取决于对象。

在 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 playgroud

上述程序的第 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接口类型。

我们公司有两种员工,永久Permanent和合同Contract由第一行的结构定义。Permanent雇员的工资是基本工资和工资的总和,而对于Contract雇员来说,只需要基本的工资支付,分别在 23 和 28 行相应的CalculateSalary方法中表示。通过声明此方法,PermanentContract现在都实现了SalaryCalculator接口。

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

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

程序输出,Total Expense Per Month $14050

接口的内部表示

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

让我们写一段代码加深理解,

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Tester interface {
  6. Test()
  7. }
  8. type MyFloat float64
  9. func (m MyFloat) Test() {
  10. fmt.Println(m)
  11. }
  12. func describe(t Tester) {
  13. fmt.Printf("Interface type %T value %v\n", t, t)
  14. }
  15. func main() {
  16. var t Tester
  17. f := MyFloat(89.7)
  18. t = f
  19. describe(t)
  20. t.Test()
  21. }

Run in playground

Tester接口有一个方法Test()MyFloat类型实现该接口。在 24 行中,我们将MyFloat类型的变量f赋给 Tester 类型的t。现在t的具体类型是MyFloatt的值是 89.7。第 17 行中的describe函数打印接口的值和具体类型。该程序输出

  1. Interface type main.MyFloat value 89.7
  2. 89.7

空接口

没有方法的接口称为空接口。它用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{})函数将空接口作为参数,因此可以传递任何类型。

我们将stringintstruct分别为 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)是用于获取具体类型为Ti接口的基础值的语法。

代码胜过言语。让我们写一个类型断言。

  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

在第 12 行,s的具体类型是int。我们在第 8 行中使用语法i.(int)去获取iint型基础值。该程序打印 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

在上面的程序中,我们将具体类型为strings传递给assert函数,该函数尝试从中提取int值。该程序将产生 panic 内容 panic: interface conversion: interface {} is string, not int.

要解决上面的问题,我们只要使用下面的语法,

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

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

如果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,即 int 的零值。该程序将打印,

  1. 56 true
  2. 0 false

类型 Switch

类型switch用于将接口的具体类型与各种case语句中指定的多种类型进行比较。它类似于switch case。唯一的区别是case指定类型而不是正常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.98float64类型,它不匹配任何case,因此在最后一行打印未知类型。

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

来写一段代码让理解更清晰,

  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 playgroud

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

打印,

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

接口的第一部分就结束了。我们将在第二部分中继续讨论接口。

ft_authoradmin  ft_create_time2019-08-03 16:35
 ft_update_time2019-08-03 16:36