11.6 使用方法集与接口
...大约 1 分钟
11.6 使用方法集与接口
在接口上调用方法时,必须有和方法定义时相同的接收者类型或者是可以根据具体类型 P 直接辨识的:
- 指针方法可以通过指针调用
 - 值方法可以通过值调用
 - 接收者是值的方法可以通过指针调用,因为指针会首先被解引用
 - 接收者是指针的方法不可以通过值调用,因为存储在接口中的值没有地址
 
将一个值赋值给一个接口时,编译器会确保所有可能的接口方法都可以在此值上被调用,因此不正确的赋值在编译期就会失败。
Go 语言规范定义了接口方法集的调用规则:
- 类型 
*T的可调用方法集包含接受者为*T或T的所有方法集 - 类型 
T的可调用方法集包含接受者为T的所有方法 - 类型 
T的可调用方法集不包含接受者为*T的方法 
因为接口变量中存储的值是不可寻址的,所以不能调用接收者为指针的方法。
type Shaper2 interface {
	Area() float32
	Perimeter() float32
}
type Square2 struct {
	side float32
}
func (s *Square2) Area() float32 {
	return s.side * s.side
}
func (s Square2) Perimeter() float32 {
	return s.side * 4
}
func mthds() {
	s1 := Square2{2}
	s2 := &Square2{3}
	var shape Shaper2
	// Cannot use 's1' (type Square2) as the type Shaper2
	// Type does not implement 'Shaper2' as the
	// 'Area' method has a pointer receiver
	// shape = s1
	shape = s2
}
 Powered by  Waline  v2.15.2
