英文:
Mismatch types uint32 and bool in Go
问题
我有一个定义如下的C宏:
#define normalize(c, a) c = (a) + ((a) == 0xFFFFFFFF)
我正在用Go重新编写它,据我所知,Go中没有C宏这样的东西。因此,我创建了一个普通函数:
func normalize(a uint32, c *uint32) {
*c = a + (a == 0xFFFFFFFF)
}
问题是这给我带来了类型不匹配的错误。有什么办法可以修复它吗?
英文:
I have a C macro defined like this:
#define normalize(c, a) c = (a) + ((a) == 0xFFFFFFFF)
I was rewriting it in Go, and as long as I know there is no such things as C macros in Go. Therefore, I created a normal function:
func normalize(a uint32, c *uint32) {
*c = a + (a == 0xFFFFFFFF)
}
The problem is that this gives me a type mismatch error. Any ideas how to fix it?
答案1
得分: 2
所以你的 C 语言的 normalize
宏会将 c
赋值为 a
,如果 a
不等于 0xffffffff
,否则赋值为 0
。我不确定这是什么样的归一化,但现在不是我的关注点。
根据你提供的 Go 函数签名,可以这样实现:
func normalize(a uint32, c *uint32) {
if a != 0xffffffff {
*c = a
} else {
*c = 0
}
}
然而,我不确定为什么不直接返回一个值,而是通过 c
指针进行写入?
func normalize(a uint32) uint32 {
if a != 0xffffffff {
return a
}
return 0
}
顺便提一下:对于你的 C 宏也是一样的。顺便说一下,这个宏会对 a
进行两次求值,如果你将带有副作用的函数作为 a
传递进去,可能会让你感到惊讶。有没有什么理由不使用(内联)函数来替代宏,或者至少使其求值为一个新值,而不是将 c
赋值为它呢?
英文:
So your C normalize
macro assigns c
to a
if a
is not equal to 0xffffffff
, or to 0
otherwise. I'm not sure what kind of normalization it is, but it's not my concern now.
So given the Go function signature you provided, this would work:
func normalize(a uint32, c *uint32) {
if a != 0xffffffff {
*c = a
} else {
*c = 0
}
}
However, I'm not sure why not just return a value instead of writing it via c
pointer?
func normalize(a uint32) {
if a != 0xffffffff {
return a
}
return 0
}
Side note: the same applies to your C macro. By the way, the macro evaluates a
twice, this might come as a surprise if you ever pass some function with side effects as a
. Any reason not to use (inline) function instead of a macro, or at least make it so that it evaluates to a new value, instead of assigning c
to it?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论