Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 传递实现与指针接收器接口的对象_Go - Fatal编程技术网

Go 传递实现与指针接收器接口的对象

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) {

我知道这与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) {
        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-编译错误消失,但应用程序逻辑不正确。我会更新答案。