golang学习笔记--Interface

728 阅读1分钟

什么是 Interface

在面向对象的世界中,接口的一般定义是“接口定义对象的行为”,即只定义对象的行为,至于对象如何行动则具体实现在对象中。

在 Golang 中,接口是一组方法签名,当一个类型为接口中的所有方法提供定义时,就说实现了该接口。接口指定类型应具有的方法,类型决定如何实现这些方法。

接口的定义和实现

package main

import (  
    "fmt"
)

//interface definition
type VowelsFinder interface {  
    FindVowels() []rune
}

type MyString string

//MyString implements VowelsFinder
func (ms MyString) FindVowels() []rune {  
    var vowels []rune
    for _, 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 VowelsFinder
    v = name // possible since MyString implements VowelsFinder
    fmt.Printf("Vowels are %c", v.FindVowels())

interface 应用场景

类 java 中的多态

package main

import (  
    "fmt"
)
// 接口定义
type SalaryCalculator interface {  
    CalculateSalary() int
}
// 类型1
type Permanent struct {  
    empId    int
    basicpay int
    pf       int
}
// 类型2
type Contract struct {  
    empId  int
    basicpay int
}

// Permanent salary 计算实现
func (p Permanent) CalculateSalary() int {  
    return p.basicpay + p.pf
}

// Contract salary 计算实现
func (c Contract) CalculateSalary() int {  
    return c.basicpay
}

/*
通过对SalalCalculator切片进行迭代并求和来计算总费用个人雇员的工资
*/
func totalExpense(s []SalaryCalculator) {  
    expense := 0
    for _, 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)
}

在上述程序片段中,totalExpense 接收一个 interface slice,可以应用于任何实现SalaryCalculator interface 的类型,若我们添加一个新的类型,实现一种新的薪资计算方式,上述代码可以完全不需要修改即可使用。

用于内部表示

可以将接口视为由元组(类型,值)在内部表示。type是接口的基础具体类型,value持有具体类型的值。

type Tester interface {  
    Test()
}

type MyFloat float64

func (m MyFloat) Test() {  
    fmt.Println(m)
}

func describe(t Tester) {  
    fmt.Printf("Interface type %T value %v\n", t, t)
}
func main() {  
    var t Tester
    f := MyFloat(89.7) 
    t = f               // 此处将类型赋值,
    describe(t)         // 此处的输出为 Interface type main.MyFloat value 89.7  
    t.Test()
}

空接口

空接口中没有任何方法,表示为 interface{},由于空接口没有任何方法,因此可以理解为所有类型默认实现了此接口。

func describe(i interface{}) {  
    fmt.Printf("Type = %T, value = %v\n", i, i)
}

func main() {  
    s := "Hello World"
    describe(s)      // Type = string, value = Hello World  
    i := 55
    describe(i)      // Type = int, value = 55 
    strt := struct {
        name string
    }{
        name: "Naveen R",
    }
    describe(strt)   // Type = struct { name string }, value = {Naveen R}  
}

类型判定

可以使用语法 i.(T) 获取变量i中T类型的值,以此来判断传入的类型是否正确

s := i.(int) // 获取变量 i 中 int 类型的数据,若 i 不是 int, 则 panic
v, ok := i.(int) // 用这种方式避免 panic

此外,也可以配合 switch 实现类型判断

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")
    }
}   

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

type Describer interface {  
    Describe()
}
type Person struct {  
    name string
    age  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")
    }
}

通过嵌入接口,实现继承的功能

type SalaryCalculator interface {  
    DisplaySalary()
}

type LeaveCalculator interface {  
    CalculateLeavesLeft() int
}

type EmployeeOperations interface {  
    SalaryCalculator
    LeaveCalculator
}

type Employee struct {  
    firstName string
    lastName string
    basicPay int
    pf int
    totalLeaves int
    leavesTaken int
}

// Employee 实现了 DisplaySalary 和 CalculateLeavesLeft 两个接口,也就默认实现了 EmployeeOperations 接口
func (e Employee) DisplaySalary() {  
    fmt.Printf("%s %s has salary $%d", e.firstName, e.lastName, (e.basicPay + e.pf))
}

func (e Employee) CalculateLeavesLeft() int {  
    return e.totalLeaves - e.leavesTaken
}

func main() {  
    e := Employee {
        firstName: "Naveen",
        lastName: "Ramanathan",
        basicPay: 5000,
        pf: 200,
        totalLeaves: 30,
        leavesTaken: 5,
    }
    // 此处可以说 Employee 实现了 EmployeeOperations接口
    var empOp EmployeeOperations = e
    empOp.DisplaySalary()
    fmt.Println("\nLeaves left =", empOp.CalculateLeavesLeft())
}

接口的 0 值

接口的零值为nil。 nil接口具有其基础值和具体类型(如nil)。

type Describer interface {  
    Describe()
}

func main() {  
    var d1 Describer
    if d1 == nil {
        // 此处输出  d1 is nil and has type <nil> value <nil> 
        fmt.Printf("d1 is nil and has type %T value %v\n", d1, d1)
    }
}

喜欢的话,访问我的主页吧~