doumu8911 2016-02-16 09:46
浏览 112
已采纳

在Go中封装平台特定代码的正确方法是什么?

I want to develop a small Go application, which shows the used key stroke shortcuts to the audience of a presentation.

To hook into the keyboard events I will have to use some platform specific code. What is the Go way to encapsulate platform specific code? I've been searching for keywords like compiler switch or platform modules, but I couldn't really find something about.

  • 写回答

2条回答 默认 最新

  • douxin1956 2016-02-16 09:51
    关注

    The solution to platform specific code is the build constraints.

    A build constraint, also known as a build tag, is a line comment that begins

    // +build
    

    that lists the conditions under which a file should be included in the package. Constraints may appear in any kind of source file (not just Go), but they must appear near the top of the file, preceded only by blank lines and other line comments. These rules mean that in Go files a build constraint must appear before the package clause.

    So basically each platform specific Go code should go into different files, and you can mark each of these Go files with the target they are intended for.

    For example if a file contains Linux specific code (e.g. syscalls), start it with:

    // +build linux
    

    If a file contains Windows specific syscalls, start it with:

    // +build windows
    

    A lot more "options" are available, read the linked docs. For example you can specify constraints to the OS, Architecture, Go version, the compiler being used. You can also specify multiple constraints that will be interpreted with logical OR or AND, or you can use negation (e.g. this code is for every target platform except linux).

    You can even mark a .go file to be ignored with the following constraint:

    // +build ignore
    

    Note that build constraints are compiler specific. If a specific compiler does not recognize a build constraint, the compiler will ignore the file. As an example the Go AppEngine SDK comes with a built-in, modified Go compiler which additionally recognizes the

    // +build appengine
    

    constraint, which means the source file is intended for the Google App Engine Platform only. "Regular" Go compilers will ignore the file, giving you the possibility to not have a bunch of compiler errors if someone tries to build the code without the Go AppEngine SDK.

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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路