go - 了解 gometalinter unconvert 不必要的转换警告

标签 go

警告:不必要的转换(unconvert)

这来自以下行:

offsetY += 60 + image.Image(*img.Bitmap).Bounds().Max.Y

我花了一段时间才明白如何将此接口(interface)指针转换为接口(interface),但我认为这不是正确的解决方案,因为 gometalinter 会发出警告。

我想获取 img 的宽度。 imgImage 结构,并且有一个指向真实 image.Image(图像标准库)的位图指针。如果我想在实际的 image.Image 上调用 Bounds,我需要将指向接口(interface)的指针转换为接口(interface)。

应该如何以更友好的方式完成?

我有以下代码:

import (
    "image"
    "image/color"
    "image/draw"
)
type Image struct {
    Src    string
    Title  string
    Width  int
    Height int
    Index  int
    Bitmap *image.Image
}

type Images []Image

offsetY = 10
func ComposeImage(imgs Images) image.Image {
    masterRGBAImg := image.NewRGBA(image.Rect(0, 0, 300, 300))
    masterBounds := masterRGBAImg.Bounds()

    for _, img := range imgs {
        draw.Draw(masterRGBAImg, masterBounds,
            *img.Bitmap, image.Point{X: -10, Y: -offsetY + 10}, draw.Src)


        addLabel(masterRGBAImg, 10, offsetY-30, img.Title)

        // HERE ======
        offsetY += 60 + image.Image(*img.Bitmap).Bounds().Max.Y
        // END ======

    }
    return masterRGBAImg
}

// Draw label on image.
func addLabel(img *image.RGBA, x int, y int, label string) {
    col := color.RGBA{50, 50, 50, 255}
    point := fixed.Point26_6{X: fixed.Int26_6(x * 64), Y: fixed.Int26_6(y * 64)}

    d := &font.Drawer{
        Dst:  img,
        Src:  image.NewUniform(col),
        Face: inconsolata.Bold8x16,
        Dot:  point,
    }
    d.DrawString(label)
}

最佳答案

首先,位图字段是一个*image.Image,所以它是同一类型,当您可以取消引用时不需要转换它。

(*img.Bitmap).Bounds()

但是,image.Image 是一个接口(interface)。指向接口(interface)的指针几乎总是编程错误。

将您的结构定义更改为

type Image struct {
    Src    string
    Title  string
    Width  int
    Height int
    Index  int
    Bitmap image.Image
}

然后您可以直接调用 img.Bitmap.Bounds()

关于go - 了解 gometalinter unconvert 不必要的转换警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40142146/

相关文章:

json - 嵌入式结构的多态 JSON 解码

hash - 如何在Go中实现HashCash的算法(类型转换问题)?

go - 无法在没有解析错误的情况下在 Google go 中添加时间

concurrency - channel 是否通过引用隐式传递

go - 如何设置和解析正文请求中的时间?

mongodb - mongodb 管道查询 $project 中的错误应该是什么?

go - IBM Cloud - Cloud Foundry App Go 部署失败

go - Go Web App 中必须要有 DAL 和 BLL 吗?

go - Heroku Golang 部署

go - 如何端到端/集成测试使用反向代理管理子域的 Go 应用程序?