将实现了指针接收器的接口的对象传递

huangapple go评论82阅读模式
英文:

Passing objects that implement an interface with a pointer receiver

问题

我理解这与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)
英文:

I understand that this has to do with the fact that Scale takes a pointer receiver. But I don't understand how I need to write PrintArea so this works.

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

Here is the error I get as is.

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

答案1

得分: 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)
}
英文:

The Shape interface requires that the receiver has two methods - Scale and Area. Pointers to a type and the types themselves are considered different types in Go (so *Square and Square are different types).

To implement the interface, the Area and Scale functions must be on either the type or the pointer (or both if you want). So either

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

答案2

得分: 0

只是通过引用传递

PrintArea(&s)
英文:

Just pass by reference

PrintArea(&s)

huangapple
  • 本文由 发表于 2015年4月24日 08:19:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/29836620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定