douxue4395 2012-12-14 09:42
浏览 43
已采纳

Go中的C样式巨集

I've been playing with go for a week and something I miss from C is preprocessor macros.

What could I use to get this feature, besides hacking a build script that pipes go files through clang -E ?

  • 写回答

2条回答 默认 最新

  • dousha2020 2012-12-15 06:02
    关注

    As mentioned in the comments, build flags are probably the best way to solve whatever you need. For example, if you wanted to have some features only available in development, use a dev flag:

    File constants_dev.go:

    // +build dev
    const DEVELOPMENT = true
    

    File constants_pro.go

    // +build !dev
    const DEVELOPMENT = false
    

    Then in your code, just do a simple if DEVELOPMENT { blah... }. I find this much more readable than any preprocessor. This can get quite messy if you have a lot of build flags, but at that point you should probably be using command-line arguments instead.

    In your comment, you mentioned duplication of code. If your code is really that repetitive, you should probably be putting it in a function anyway, or possibly restructure code to reuse the bits that are repetitive. Personally, I find that anything beyond simple boolean checks ends in hard to maintain code, especially with C-style macros.

    It's the same thing with generics. In one Java library I've used, the class signature was something like this:

    class Thing<A, B, C, D, E>
    

    The library wasn't very well documented, so I had to read a significant amount of the code (both implementation and code that uses the library) to understand what was going on.

    In Go, the language forces a style that generally leads to better, self-documenting code. I think the Go developers omitted things like a preprocessor and generics to avoid temptation to write hard to maintain, but clever, code.

    I would advise you to try out the Go way before looking back on old idioms that you used before. I think you'll find that most of what macros and #defines were used for are largely irrelevant.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码