golan知识点-interface(2)

实现接口:值方法、指针方法

    在类型的实现当中,可以有值方法,或者指针方法。当这个类型单独使用的时候,就按照类型本身的方法类型进行使用。
而当我们的类型是某个接口的实现。那当我们再使用接口变量的时候,用法上就是有差异的。因为接口中是没有明确定义出来,接口下面的方法是值方法,还是指针方法。 以下是一个具体的值方法和指针方法的示例:

package main
 
import "fmt"
 
type Describer interface {  
    Describe()
}
type Person struct {  
    name string
    age  int
}
 
func (p Person) Describe() { // 使用值接受者实现。 值方法。
    fmt.Printf("%s is %d years old\n", p.name, p.age)
}
 
type Address struct {
    state   string
    country string
}
 
func (a *Address) Describe() { // 使用指针接受者实现。指针方法。
    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"}
 
    /* 如果下面一行取消注释会导致编译错误:
       cannot use a (type Address) as type Describer
       in assignment: Address does not implement
       Describer (Describe method has pointer
       receiver)
    */
    //d2 = a
 
    d2 = &a // 这是合法的。 这里指针变量。要使用指针方法的时候。就需要时以指针的形式。 调用的时候才会传递指针到方法中。也就是 (*指针).接口方法名()。
    // 因为在第 22 行,Address 类型的指针实现了 Describer 接口
    d2.Describe()
 
}
程序输出:

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

解析:
    在上面程序中的第 13 行,结构体 Person 使用值接受者,实现了 Describer 接口。
我们在讨论方法的时候就已经提到过,使用值接受者声明的方法,既可以用值来调用,也能用指针调用。不管是一个值,还是一个可以解引用的指针,调用这样的方法都是合法的。
p1 的类型是 Person,在第 29 行,p1 赋值给了 d1。由于 Person 实现了接口变量 d1,因此在第 30 行,会打印 Sam is 25 years old。
接下来在第 32 行,d1 又赋值为 &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 行,我们使用 Address 类型的指针接受者实现了接口 Describer,而接下来我们试图用 a 来赋值 d2。然而 a 属于值类型,它并没有实现 Describer 接口。你应该会很惊讶,因为我们曾经学习过,使用指针接受者的方法,无论指针还是值都可以调用它。那么为什么第 45 行的代码就不管用呢?
其原因是:对于使用指针接受者的方法,用一个指针或者一个可取得地址的值来调用都是合法的。但接口中存储的具体值(Concrete Value)并不能取到地址,因此在第 45 行,对于编译器无法自动获取 a 的地址,于是程序报错。
第 47 行就可以成功运行,因为我们将 a 的地址 &a 赋值给了 d2。


实现多接口

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

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())
}
输出:

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())
}
输出:
Naveen Ramanathan has salary $5200
Leaves left = 25

解析:在上述程序的第 15 行,我们创建了一个新的接口 EmployeeOperations,它嵌套了两个接口:SalaryCalculator 和 LeaveCalculator。
如果一个类型定义了 SalaryCalculator 和 LeaveCalculator 接口里包含的方法,我们就称该类型实现了 EmployeeOperations 接口。
在第 29 行和第 33 行,由于 Employee 结构体定义了 DisplaySalary 和 CalculateLeavesLeft 方法,因此它实现了接口 EmployeeOperations。
在 46 行,empOp 的类型是 EmployeeOperations,e 的类型是 Employee,我们把 empOp 赋值为 e。接下来的两行,empOp 调用了 DisplaySalary() 和 CalculateLeavesLeft() 方法。

接口的零值

接口的零值是 nil。对于值为 nil 的接口,其底层值(Underlying Value)和具体类型(Concrete Type)都为 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)
    }
}
上面程序里的 d1 等于 nil,程序会输出:
d1 is nil and has type <nil> value <nil>
//对于值为 nil 的接口,由于没有底层值和具体类型,当我们试图调用它的方法时,程序会产生 panic 异常。
package main
 
type Describer interface {
    Describe()
}
 
func main() {  
    var d1 Describer
    d1.Describe()
}

小结:

  • 接口实现: 值方法、指针方法。 当实现是指针方法时,在使用接口变量时,需要接收具体类型的指针值。 
  • 实现多接口: 一个具体的实现类型,能够实现多个接口。可同时赋值给两个指针变量。 
  • 嵌套接口: 一个更大的接口中嵌入(放入定义中)多个子接口。具体的实现类型,需要实现所有子接口的所有方法。 
  • 接口空值: 定义一个接口变量之后,这个变量是一个控制。type及value都是空值。只有接收了具体实现类型的变量,才会进行赋值。调用空值,会出错。

参考链接:

https://blog.csdn.net/cbmljs/article/details/83189359

转载于:https://my.oschina.net/u/4156317/blog/3069589

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值