ds2010630 2012-12-24 04:58
浏览 29
已采纳

为什么必须同时输入“图像/颜色”和“图像”?

I am just learning Go and wrote the following struct (Image) to implement the 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)
}

If I just import image/color and not import image, image.Rect is undefined. Why? Shouldn't image/color already cover the methods and properties of image?

Also, if I change the function receivers from (img Image) to (img *Image), an error arises:

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

Why is that? Doesn't (img *Image) indicate a pointer receiver?

  • 写回答

1条回答 默认 最新

  • duanhe3393 2012-12-24 05:26
    关注

    If you check out the source for the image package and its sub-packages, you will see that image/color does not depend on image at all, so it never imports it.

    image does however import image/color

    For the second part of your question, where you change all of the receivers to pointers, that means you should also be passing an Image pointer to ShowImage:

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

    Methods defined on a pointer receiver must be accessed on a pointer. But methods defined on just the struct can be accessed from a pointer or the value.

    Here is some documentation explaining the difference between a pointer or a value receiver of a method:

    1. Should I define methods on values or pointers?
    2. Why do T and *T have different method sets?
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 复现论文:matlab仿真代码编写
  • ¥15 esp32驱动GC9A01循环播放视频
  • ¥15 惠普360g9的最新bios
  • ¥30 这个功能用什么软件发合适?
  • ¥60 微信小程序,取消订单,偶尔订单没有改变状态
  • ¥15 用pytorch实现PPO算法
  • ¥15 关于调制信号的星座图?
  • ¥30 前端传参时,后端接收不到参数
  • ¥15 这是有什么问题吗,我检查许可证了但是显示有呢
  • ¥15 机器学习预测遇到的目标函数问题