教程 > go 教程 > 阅读:400

go 语言实现多个接口——迹忆客-ag捕鱼王app官网

本章节继续介绍接口相关的内容,实现多个接口。一种类型可以实现多个接口。在阅读本章节之前,如果对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 接口。

查看笔记

扫码一下
查看教程更方便
网站地图