使用指针接收器传递实现接口的对象

时间:2015-04-24 00:19:13

标签: 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) {
        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)

2 个答案:

答案 0 :(得分:2)

Shape接口要求接收方有两种方法 - ScaleArea。指向类型的指针和类型本身在Go中被视为不同的类型(因此*SquareSquare是不同的类型)。

要实现该接口,AreaScale函数必须位于类型或指针上(如果需要,则两者都必须)。所以要么

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

答案 1 :(得分:0)

通过引用传递

PrintArea(&s)