[关闭]
@adamhand 2019-02-04T10:31:34.000000Z 字数 5134 阅读 637

golang--接口(1)


在 Go 语言中,接口就是方法签名(Method Signature)的集合。当一个类型实现了接口中的所有方法,我们称它实现了该接口。这与面向对象编程(OOP)的说法很类似。接口指定了一个类型应该具有的方法,并由该类型决定如何实现这些方法

接口的声明与实现

让我们编写代码,创建一个接口并且实现它。

  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. }

在第 15 行,我们给接受者类型(Receiver Type) MyString 添加了方法 FindVowels() []rune。现在,我们称 MyString 实现了 VowelsFinder 接口。这就和其他语言(如 Java)很不同,其他一些语言要求一个类使用 implement 关键字,来显式地声明该类实现了接口。而在 Go 中,并不需要这样。如果一个类型包含了接口中声明的所有方法,那么它就隐式地实现了 Go 接口。

在第 28 行,v 的类型为 VowelsFinder,name 的类型为 MyString,我们把 name 赋值给了 v。由于 MyString 实现了 VowelFinder,因此这是合法的。

该程序输出 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. }

上面程序的第 7 行声明了一个 SalaryCalculator 接口类型,它只有一个方法 CalculateSalary() int。

在公司里,我们有两类员工,即第 11 行和第 17 行定义的结构体:Permanent 和 Contract。长期员工(Permanent)的薪资是 basicpay 与 pf 相加之和,而合同员工(Contract)只有基本工资 basicpay。在第 23 行和第 28 行中,方法 CalculateSalary 分别实现了以上关系。由于 Permanent 和 Contract 都声明了该方法,因此它们都实现了 SalaryCalculator 接口。

第 36 行声明的 totalExpense 方法体现出了接口的妙用。该方法接收一个 SalaryCalculator 接口的切片([]SalaryCalculator)作为参数。在第 49 行,我们向 totalExpense 方法传递了一个包含 Permanent 和 Contact 类型的切片。在第 39 行中,通过调用不同类型对应的 CalculateSalary 方法,totalExpense 可以计算得到支出。

这样做最大的优点是:totalExpense 可以扩展新的员工类型,而不需要修改任何代码。假如公司增加了一种新的员工类型 Freelancer,它有着不同的薪资结构。Freelancer只需传递到 totalExpense 的切片参数中,无需 totalExpense 方法本身进行修改。只要 Freelancer 也实现了 SalaryCalculator 接口,totalExpense 就能够实现其功能。

该程序输出 Total Expense Per Month $14050

接口的内部表示

我们可以把接口看作内部的一个元组 (type, value)。 type 是接口底层的具体类型(Concrete Type),而 value 是具体类型的值。

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

在第17行,t 的具体类型为 MyFloat,而 t 的值为 89.7。该程序输出:

  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)

该程序打印:

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

类型断言

类型断言用于提取接口的底层值(Underlying Value)。

在语法 i.(T) 中,接口 i 的具体类型是 T,该语法用于获得接口的底层值。

  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. }

在第 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. }

该程序会报错: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. }

该程序打印:

  1. 56 true
  2. 0 false

类型选择(Type Switch)

类型选择用于将接口的具体类型与很多 case 语句所指定的类型进行比较。它与一般的 switch 语句类似。唯一的区别在于类型选择指定的是类型,而一般的 switch 指定的是值。

类型选择的语法类似于类型断言。类型断言的语法是 i.(T),而对于类型选择,类型 T 由关键字 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. }

该程序输出:

  1. I am a string and my value is Naveen
  2. I am an int and my value is 77
  3. 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. }

在上面程序中,结构体 Person 实现了 Describer 接口。在第 19 行的 case 语句中,v 与接口类型 Describer 进行了比较。p 实现了 Describer,因此满足了该 case 语句,于是当程序运行到第 32 行的 findType(p) 时,程序调用了 Describe() 方法。

该程序输出:

  1. unknown type
  2. Naveen R is 25 years old
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注