gpt4 book ai didi

go - 为什么我必须同时导入 "image/color"和 "image"?

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

我刚刚学习 Go 并编写了以下结构 (Image) 来实现 image.Image 接口(interface)。

package main

import (
"image"
"image/color"
"code.google.com/p/go-tour/pic"
)

type Image struct{}

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

func (img Image) Bounds() image.Rectangle {
return image.Rect(0, 0, 100, 100)
}

func (img Image) At(x, y int) color.Color {
return color.RGBA{100, 100, 255, 255}
}

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

如果我只导入 image/color 而没有导入 image,则 image.Rect 是未定义的。为什么? image/color 不应该已经涵盖了 image 的方法和属性吗?

此外,如果我将函数接收器从 (img Image) 更改为 (img *Image),则会出现错误:

Image does not implement image.Image (At method requires pointer receiver)

这是为什么呢? (img *Image) 不是指针接收器吗?

最佳答案

如果您查看 source for the image package及其子包,你会看到 image/color does not depend on image根本没有,所以它从不导入它。

image does however import image/color

对于问题的第二部分,您将所有接收器更改为指针,这意味着您还应该将 Image 指针传递给 ShowImage:

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

在指针接收器上定义的方法必须在指针上访问。但是可以从指针或值访问仅在结构上定义的方法。

这里有一些文档解释了方法的指针或值接收器之间的区别:

  1. Should I define methods on values or pointers?
  2. Why do T and *T have different method sets?

关于go - 为什么我必须同时导入 "image/color"和 "image"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14017253/

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