英文:
Convert returned values to a specific type
问题
我刚开始学习go,并遇到了以下的“问题”。
我正在使用一个返回4个无符号32位整数的函数,我想知道在我分配它们时将这些值转换为8位整数的最佳方法(或者是否可能)。我已经通过将它们分配给uint32,然后在那之后进行转换来使其工作,但我想知道是否有更简洁的方法。
示例:
r, g, b, _ := image.At(x, y).RGBA() // 理想情况下在这个阶段进行转换
所以Image.At返回uint32,但我希望r、g、b是uint8类型的。
谢谢
英文:
I'm just getting started with go and I've come across the following "problem".
I'm using a function which returns 4 unsigned 32 bit integers, and I was wondering what the best method to convert these values to 8 bit integers when I'm assigning them. (Or if it is possible). I have got it to work by assigning them to uint32, then converting them after that but I was wondering if there is a more concise way of doing it.
Example:
r, g, b, _ := image.At(x, y).RGBA() // ideally convert them at this stage
So Image.At returns uint32, but I would like r,g,b to be uint8
Thanks
答案1
得分: 4
Go没有你想要的语法。你最好的选择是在下一行中完成。
rbig, gbig, bbig := image.At(x, y).RGBA()
r, g, b := uint8(rbig), uint8(gbig), uint8(bbig)
如果这真的让你烦恼,那就创建一个辅助函数
func convert(i, j, k, _ uint32) (uint8, uint8, uint8) { return uint8(i), uint8(j), uint8(k) }
r, g, b := convert(image.At(x, y).RGBA())
仍然需要至少两行,但你可以在任何需要的地方重用这个函数,并且调用点可能看起来更清晰一些。
英文:
Go has no syntax for what you want there. You're best bet is to just do it in the next line down.
rbig, gbig, bbig := image.At(x, y).RGBA()
r, g, b := uint8(rbig), uint8(gbig), uint8(bbig)
If that really annoys you though then just make a helper function
func convert(i, j, k, _ uint32) (uint8, uint8, uint8) { return uint8(i), uint8(j), uint8(k) }
r, g, b := convert(image.At(x, y).RGBA())
Still a minimum of two lines but you can reuse the function anywhere you need it and the call site might look a little cleaner to you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论