英文:
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
接口要求接收者具有两个方法 - Scale
和Area
。在Go语言中,指向类型的指针和类型本身被认为是不同的类型(因此*Square
和Square
是不同的类型)。
要实现接口,Area
和Scale
函数必须在类型或指针上(或者两者都有,如果你想要)。所以可以这样写:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论