Go 传递实现与指针接收器接口的对象
我知道这与Scale需要指针接收器这一事实有关。但我不明白我需要如何写PrintArea才能工作Go 传递实现与指针接收器接口的对象,go,Go,我知道这与Scale需要指针接收器这一事实有关。但我不明白我需要如何写PrintArea才能工作 package main import ( "fmt" ) type Shape interface { Scale(num float64) Area() float64 } type Square struct { edge float64 } func (s *Square) Scale(num float64) {
package main
import (
"fmt"
)
type Shape interface {
Scale(num float64)
Area() float64
}
type Square struct {
edge float64
}
func (s *Square) Scale(num float64) {
s.edge *= num
}
func (s Square) Area() float64 {
return s.edge * s.edge
}
func PrintArea(s Shape) {
fmt.Println(s.Area())
}
func main() {
s := Square{10}
PrintArea(s)
}
这是我得到的错误
# command-line-arguments
/tmp/sandbox126043885/main.go:30: cannot use s (type Square) as type Shape in argument to PrintArea:
Square does not implement Shape (Scale method has pointer receiver)
只是参考一下
PrintArea(&s)
形状
界面要求接收器有两种方法-缩放
和区域
。指向类型的指针和类型本身在Go中被视为不同的类型(因此*Square
和Square
是不同的类型)
要实现该接口,区域
和缩放
函数必须位于类型或指针上(如果需要,也可以同时位于两者)。所以
func (s *Square) Scale(num float64) {
s.edge *= num
}
func (s *Square) Area() float64 {
return s.edge * s.edge
}
func main() {
s := Square{10}
PrintArea(&s)
}
第二个示例不起作用,调用Scale后原始的
s.edge
将保持不变。@OneOfOne-right-编译错误消失,但应用程序逻辑不正确。我会更新答案。