duannuo4620 2017-06-10 20:45
浏览 281
已采纳

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?

  • 写回答

1条回答 默认 最新

  • dp9599 2017-06-10 21:10
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于无人驾驶的航向角
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退