gpt4 book ai didi

go - Exercise :Image中的指针接收器和值接收器

转载 作者:IT王子 更新时间:2023-10-29 01:52:36 26 4
gpt4 key购买 nike

我对 Go 很陌生,对 Go 中的接收器概念很困惑。这是围棋之旅中的练习。

问题正文:

Remember the picture generator you wrote earlier? Let's write another one, but this time it will return an implementation of image.Image instead of a slice of data.

Define your own Image type, implement the necessary methods, and call pic.ShowImage.

Bounds should return a image.Rectangle, like image.Rect(0, 0, w, h).

ColorModel should return color.RGBAModel.

At should return a color; the value v in the last picture generator corresponds to color.RGBA{v, v, 255, 255} in this one.

这是我的代码:

package main

import "golang.org/x/tour/pic"
import "image"
import "image/color"


type Image struct{}

func (img *Image) Bounds() image.Rectangle{
w := 100
h := 100
return image.Rect(0,0,w,h)
}

func (img *Image) ColorModel() color.Model{
return color.RGBAModel
}

func (img *Image) At(x int, y int) color.Color{
return color.RGBA{uint8(x^y), uint8(y/2), 255,255}
}

func main() {
m := Image{}
pic.ShowImage(m)
}

并且会报编译错误:

command-line-arguments ./compile110.go:26: cannot use m (type Image) as type image.Image in argument to pic.ShowImage: Image does not implement image.Image (At method has pointer receiver)


我的理解是,对于方法的接收者,可以设置为指针或值。但是,当我将所有“*Image”设置为“Image”时,错误就消失了。

有人可以帮我解决这个问题吗?


下面提供的答案足以解决我提出的问题。然而,指针和值接收器似乎有点复杂。

来自 Effective Go:

The rule about pointers vs. values for receivers is that value methods can be invoked on pointers and values, but pointer methods can only be invoked on pointers. This rule arises because pointer methods can modify the receiver; invoking them on a value would cause the method to receive a copy of the value, so any modifications would be discarded. The language therefore disallows this mistake. There is a handy exception, though. When the value is addressable, the language takes care of the common case of invoking a pointer method on a value by inserting the address operator automatically.

希望这对你们中的一些人也有帮助。

最佳答案

当您在 Go 中使用接口(interface)时,您需要确保您使用的实例实现了该接口(interface)。在 Go-Tour 示例问题中,Image 不满足 image.Image 接口(interface),只有 &Image 满足。

因此,您需要更改方法签名以获取使 Image 工作的值接收器,或者将 &Image 传递给 pic.ShowImage 函数,因为指向 Image 的指针确实实现了该接口(interface)。

关于go - Exercise :Image中的指针接收器和值接收器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37427023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com