Go中的uint32和bool类型不匹配

问题描述:

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?

我有一个如下定义的C宏: p>

 # 定义normalize(c,a)c =(a)+((a)== 0xFFFFFFFF)
  code>  pre> 
 
 

我在Go中重写了它,只要 知道Go中没有C宏之类的东西。 因此,我创建了一个普通函数: p>

  func normalize(a uint32,c * uint32){
 * c = a +(a == 0xFFFFFFFF)
} \  n  code>  pre> 
 
 

问题是,这给了我一个类型不匹配的错误。 有任何解决办法吗? p> div>

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?