目录:
指针接收器与值接收器
当用指针接收器来实现接口,需要注意。当方法赋值给接口类型时,需要传递地址给接口
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() {
// d1变量是一个接口类型(Describer)
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()
}
实现多个接口
当对象赋予,实现的接口时,只能使用接口规定的方法,否则要使用断言来改变
示例:
package main
import "fmt"
type SalaryCalculator interface {
DisplaySalary()
}
type LeaveCalculator interface {
CalculateLeavesLeft() int
}
type Employee struct {
firstName, lastName string
basicPay, pf, totalLeaves, 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{
"jeff",
"ding",
100000,
200,
30,
5,
}
var s SalaryCalculator = e
s.DisplaySalary()
var l LeaveCalculator = e
fmt.Println("\n Leaves left =", l.CalculateLeavesLeft())
}
接口嵌套
当使用嵌套接口时,可以使用内部定义子接口的方法
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{
"jeff",
"ding",
100000,
200,
30,
5,
}
var e_ops EmployeeOperations = e
e_ops.DisplaySalary()
fmt.Println("\n Leaves left =", e_ops.CalculateLeavesLeft())
}
接口零值
接口的零值为 nil 类型
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 main() {
var a EmployeeOperations
fmt.Println(a)
}