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()
p1是一个Person类型的值,它在第29行被分配给d1。Person实现了Describer接口,因此第30行将打印Sam is 25 years old。
同样地,d1在第32行被分配给&p2。因此,第33行将打印James is 32 years old。Awesome:)。
Address结构在第22行使用指针接收器实现了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)**。这是因为,Describer接口是在第22行用Address指针接收器实现的,而我们正试图向其赋值a,它是一个值类型,但没有实现Describer接口。这肯定会让你感到惊讶,因为我们早先学过,带有指针接收器的方法会同时接受指针和值接收器。那么为什么第45行的代码不能工作呢?
func(e Employee) CalculateLeavesLeft() int { return e.totalLeaves - e.leavesTaken }
funcmain() { 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()) }