dqdjfb2325 2013-12-06 13:04
浏览 63

在不同的操作系统上运行时选择func的正确方法

I really like the cross-compile/platform ease for many tasks that I can get with GO. I have a question regarding, I guess, the equivalent of a #ifdef / #else type of construct for executing/compiling a function based upon the operating system.

Here's the scenario - let's say I have a function that inserts information into the OS's control structures to launch a process at the next time the user starts up their system. On Windows I would update the 'RUN/RUNONCE' registry entry for the user, on MAC there would be a plist entry, etc.

In essence, I'd like to be able to write someone analogous to this (or have overloaded OS specific functions):

func setStartupProcessLaunch () {
    if [OS is Windows] {
        updateRegistry(){}
    } else if [OS is Darwin] {
        updatePlist(){}
    } else if [OS is Linux] {
        doLinuxthing() {}
    }
}

Given the static compilation, any of the routines that aren't called would be flagged as a compilation error. So ideally, I'd like to surround my 'doSpecificOS()' functions in #ifdef WINDOWS, #ifdef MAC type of blocks -- what's the proper way to accomplish this? My hope is that I don't need to create several project trees of the same program for each OS platform.

  • 写回答

3条回答 默认 最新

  • duanbeng6709 2013-12-06 13:31
    关注

    You could put your functions in an array or map if they all the take the same number/kinds of arguments and have the same return type.

    Here's an example to illustrate:

    package main
    
    import (
    "fmt"
    )
    
    var functionMap = map[string]func(int)int{}
    var functionArray = [2]func(int)int{nil, nil}
    
    func windowsFunc(x int) int {
        fmt.Printf("Hi from windowsFunc(%d)
    ", x)
        return 0 
    }
    
    func linuxFunc(x int) int {
        fmt.Printf("Hi from linuxFunc(%d)
    ", x)
        return 1
    }
    
    
    func main() {
        functionMap["Windows"] = windowsFunc
        functionMap["Linux"] = linuxFunc
    
        functionArray[0] = windowsFunc
        functionArray[1] = linuxFunc
    
        fmt.Printf("Calling functionMap[\"Windows\"]: ")
        functionMap["Windows"](123)
    
        fmt.Printf("Calling functionArray[1]: ")
        functionArray[1](456)
    }
    

    And the output is:

    Calling functionMap["Windows"]: Hi from windowsFunc(123)
    Calling functionArray[1]: Hi from linuxFunc(456)

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度