在Go中,uint32和bool之间的类型不匹配。

huangapple go评论89阅读模式
英文:

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?

huangapple
  • 本文由 发表于 2017年6月11日 04:45:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/44477897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定