Part 19 接口II

欢迎来到Golang 系列教程的第19部分,这是我们接口教程的第2部分,以免您错过第一部分,你可点击获取第一部分内容。

使用指针接收器 vs 值接收器实现接口

所有在第一部分讨论接口例子都是使用值接收器实现。使用指针接收器实现也是可以的。使用指针接收器实现接口有一些细微之处需要注意,我们使用下面的程序来理解它。

ontent. Learn more
Got it!
GOLANGBOT.COM
GOLANG TUTORIAL - TABLE OF CONTENTSSUPPORT THIS WEBSITEABOUTADVERTISE HERE
Part 19: Interfaces - II
17 JUNE 2017
This tutorial was updated on September 3rd, 2017.

Welcome to tutorial no. 19 in Golang tutorial series. This is the second part in our 2 part interface tutorial. In case you missed the first part, you can read it from here https://golangbot.com/interfaces-part-1/

Implementing interfaces using pointer receivers vs value receivers
All the example interfaces we discussed in part 1 were implemented using value receivers. It is also possible to implement interfaces using pointer receivers. There is a subtlety to be noted while implementing interfaces using pointer receivers. Lets understand that using the following program.

package main

import "fmt"

type Describer interface {  
    Describe()
}
type Person struct {  
    name string
    age  int
}

func (p Person) Describe() { //implemented using value receiver  
    fmt.Printf("%s is %d years old\n", p.name, p.age)
}

type Address struct {  
    state   string
    country string
}

func (a *Address) Describe() { //implemented using pointer receiver  
    fmt.Printf("State %s Country %s", a.state, a.country)
}

func main() {  
    var d1 Describer
    p1 := Person{"Sam", 25}
    d1 = p1
    d1.Describe()
    p2 := Person{"James", 32}
    d1 = &p2
    d1.Describe()

    var d2 Describer
    a := Address{"Washington", "USA"}

    /* compilation error if the following line is
       uncommented
       cannot use a (type Address) as type Describer
       in assignment: Address does not implement
       Describer (Describe method has pointer
       receiver)
    */
    //d2 = a

    d2 = &a //This works since Describer interface
    //is implemented by Address pointer in line 22
    d2.Describe()

}

在上面的程序中,在 13 行,结构体 Person 使用值接收器实现 Describer 接口。

正如我们已经在方法讨论中学习到的,方法使用值接收器可以同时接收接受指针和值接收器。在任何值或值可以被解引用调用值方法是合法的

p1 是类型为 Person 的值,它在 29 行被赋值给 d1Person 实现 d1 接口。因此 30 行将打印 Sam is 25 years old

类似地,d1在 32 行被赋值为 &p2。因此 33 行将打印 James is 32 years old。真棒。

在 22 行,Address 结构体使用指针接收器实现 Describer 接口。

如果在上面程序的 45 行取消注释,我们将得到汇编错误main.go:42: cannot use a (type Address) as type Describer in assignment: Address does not implement Describer (Describe method has pointer receiver)。这是因为,在 22 行,Describer 接口使用 a Address 指针实现,而我们试图指定的 a 是一个值类型,它没有实现 Describer 接口。这无疑让我们惊讶,由于我们前面学习到,拥有指针接收器的方法可以接受值和指针接收器。那么为什么在 45 行的代码不能工作呢。

这是因为在任何已经是个指针或地址可以被取到的地方调用一个指针值函数是全法的。在接口中存储的具体值是不可寻址的,因此对编译器来说在45行自动获取 a的地址是不可以的。所以代码将失败

在47行,由于我们将 a 的地址 &a 赋值给 d2

程序的其余部分是自解释的,这个程序打印

Sam is 25 years old  
James is 32 years old  
State Washington Country USA  

实现多个接口

一个类型可以实现多个接口,我们在下面的程序中看它是如何做到的。

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 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,
    }
    var s SalaryCalculator = e
    s.DisplaySalary()
    var l LeaveCalculator = e
    fmt.Println("\nLeaves left =", l.CalculateLeavesLeft())
}

上面的程序分别在第 7 行和 11 行声明了两个接口 SalaryCalculatorLeaveCalculator

定义在 15 行的结构体 Employee 在 24 行提供了接口 SalaryCalculatorDisplaySalary 方法的实现。在 28 行实现了接口 LeaveCalculatorCalculateLeavesLeft 方法。现在 Employee 实现了 SalaryCalculatorLeaveCalculator 接口。

在41 行。我们将 e 赋值给 SalaryCalculator 接口类型的变量,43行我们将同样的变量 e 赋值给 LeaveCalculator 类型的变量。这是可以的,由于 eEmployee 类型的,它同时实现了 SalaryCalculatorLeaveCalculator 接口

程序输出

Naveen Ramanathan has salary $5200  
Leaves left = 25  

嵌入接口

尽管 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 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,
    }
    var empOp EmployeeOperations = e
    empOp.DisplaySalary()
    fmt.Println("\nLeaves left =", empOp.CalculateLeavesLeft())
}

在上面程序的 15 行,接口EmployeeOperations 通过嵌入 SalaryCalculatorLeaveCalculator接口被创建。

任何类型,只要它提供了SalaryCalculatorLeaveCalculator接口中存在的方法的方法定义,我们就说它实现了EmployeeOperations接口。

结构体 Employee 实现了 EmployeeOperations 接口,因为它分别在 29 行和 33 行提供了 DisplaySalaryCalculateLeavesLeft 提供的方法。

在 46 行,类型为 Employeee,赋值给 EmployeeOperations 类型的 empOp。在下面两行,empOp 调用 DisplaySalaryCalculateLeavesLeft 方法。

程序输出

Naveen Ramanathan has salary $5200  
Leaves left = 25  

接口的空值

接口的空值是 nil。一个空接口,它的底层的值和具体类型都是nil。

package main

import "fmt"

type Describer interface {  
    Describe()
}

func main() {  
    var d1 Describer
    if d1 == nil {
        fmt.Printf("d1 is nil and has type %T value %v\n", d1, d1)
    }
}

上面程序的 d1nil,程序输出

d1 is nil and has type <nil> value <nil> 

如果我们尝试调用一个 nil 接口,程序将 panic,由于 nil 接口即没有底层值也没有具体类型。

package main

type Describer interface {  
    Describe()
}

func main() {  
    var d1 Describer
    d1.Describe()
}

由于上面程序中 d1nil。这个程序将以运行时错误**panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0xc8527]"**panic。

下一教程 并发介绍

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 内容概要 《计算机试卷1》是一份综合性的计算机基础和应用测试卷,涵盖了计算机硬件、软件、操作系统、网络、多媒体技术等多个领域的知识点。试卷包括单选题和操作应用两大类,单选题部分测试学生对计算机基础知识的掌握,操作应用部分则评估学生对计算机应用软件的实际操作能力。 ### 适用人群 本试卷适用于: - 计算机专业或信息技术相关专业的学生,用于课程学习或考试复习。 - 准备计算机等级考试或职业资格认证的人士,作为实战演练材料。 - 对计算机操作有兴趣的自学者,用于提升个人计算机应用技能。 - 计算机基础教育工作者,作为教学资源或出题参考。 ### 使用场景及目标 1. **学习评估**:作为学校或教育机构对学生计算机基础知识和应用技能的评估工具。 2. **自学测试**:供个人自学者检验自己对计算机知识的掌握程度和操作熟练度。 3. **职业发展**:帮助职场人士通过实际操作练习,提升计算机应用能力,增强工作竞争力。 4. **教学资源**:教师可以用于课堂教学,作为教学内容的补充或学生的课后练习。 5. **竞赛准备**:适合准备计算机相关竞赛的学生,作为强化训练和技能检测的材料。 试卷的目标是通过系统性的题目设计,帮助学生全面复习和巩固计算机基础知识,同时通过实际操作题目,提高学生解决实际问题的能力。通过本试卷的学习与练习,学生将能够更加深入地理解计算机的工作原理,掌握常用软件的使用方法,为未来的学术或职业生涯打下坚实的基础。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值