教程 > Go 教程 > Go 高级 阅读:345

Go 语言实现多个接口

本章节继续介绍接口相关的内容,实现多个接口。一种类型可以实现多个接口。在阅读本章节之前,如果对Go语言的接口还不熟悉的话,需要先回去阅读 Go 接口详解Go 接口实现的两种方式

下面我们通过一个示例来看一下多接口的实现方式

package main

import (  
    "fmt"
)

type SalaryCalculator interface {  
    DisplaySalary()
}

type LeaveCalculator interface {  
    CalculateLeavesLeft() int
}

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

func (e Employee) DisplaySalary() {  
    fmt.Printf("%s %s 的薪资为 $%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,
    }
    var s SalaryCalculator = e
    s.DisplaySalary()
    var l LeaveCalculator = e
    fmt.Println("\nLeaves left =", l.CalculateLeavesLeft())
}

运行示例

上述代码执行结果如下

Naveen Ramanathan 的薪资为 $5200
Leaves left = 25

上面的程序声明了两个接口SalaryCalculatorLeaveCalculator。这两个接口中分别声明了方法 DisplaySalaryCalculateLeavesLeft。接下来定义了一个结构体Employee。它分别实现了 DisplaySalaryCalculateLeavesLeft 两个方法。 这里就可以说 Employee 实现了接口 SalaryCalculator和LeaveCalculator。

嵌入接口

尽管 go 不提供继承,但可以通过嵌入其他接口来创建新接口。

让我们通过下面的示例来看看这是如何完成的。

package main

import (  
    "fmt"
)

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
}

func (e Employee) DisplaySalary() {  
    fmt.Printf("%s %s 的薪资为 $%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,
    }
    var empOp EmployeeOperations = e
    empOp.DisplaySalary()
    fmt.Println("\nLeaves left =", empOp.CalculateLeavesLeft())
}

运行示例

上述代码运行结果如下

Naveen Ramanathan 的薪资为 $5200
Leaves left = 25

上面程序中的EmployeeOperations接口是通过嵌入SalaryCalculatorLeaveCalculator接口创建的。

如果任何实现了SalaryCalculatorLeaveCalculator接口中的方法的类型,都可以说该类型实现了EmployeeOperations接口。我们可以看到,EmployeeOperations 接口本身并没有声明要实现的方法。相当于是继承了接口 SalaryCalculator 和 LeaveCalculator 的方法。

Employee结构体实现了 DisplaySalaryCalculateLeavesLeft 方法,所以说该结构体实现了 EmployeeOperations 接口。

查看笔记

扫码一下
查看教程更方便