duanming7833 2018-11-08 04:56
浏览 57
已采纳

声明没有值的全局变量

I have a program that requires either 1 or 2 arguments depending on what the users wants to run

var (
   clientSet = tools.NewClientSet(os.Args[2])
)
func main {
    if os.Args[1] == "validate" {
       // run validate function, no need for user to have os.Args[2]
    }else if os.Args[1] == "sync" {
      // run sync function that requires os.Args[2]
    }
}
func foo{
   tools.Manage(clientSet)
}

I need the clientSet variable to be global, but I dont need the users to have os.Args[2] if the users only wants to use the validate function. Putting the clientSet function inside main() will make my foo() function broken and I can't declare a variable with an empty value.

So I want my users to be able to run go run main.go validate and go run main.go sync production smoothly.

*production is an arbitrary value

I could have my users to run go run main.go validate _ to plug this problem, but that would be inelegant.What's the best way to tackle this problem?

  • 写回答

3条回答 默认 最新

  • douquejituan938904 2018-11-08 05:59
    关注

    I don't even see the need for a global variable in this case. You can just make the sync function accept a ClientSet e.g. func sync(c ClientSet). But if you really need the global variable then you should not do this unless you want your program to panic when there are no arguments present.

    var (
       clientSet = tools.NewClientSet(os.Args[2])
    )
    

    What you should do is to assign it a default value or the zero value of your type.

    var (
       clientSet tools.ClientSet
    )
    

    Your main function would look somewhat like this:

    var (
        clientSet tools.ClientSet
    )
    
    func main() {
    
        if len(os.Args) < 2 {
            os.Exit(1)
        }
    
        switch os.Args[1] {
        case "validate":
            validate()
    
        case "sync":
    
            if len(os.Args) < 3 {
                os.Exit(1)
            }
    
            clientSet = tools.NewClientSet(os.Args[2])
            sync()
        default:
            // place your default case here
        }
    
    }
    

    Still, I suggest you just pass a ClientSet to the sync function since it will avoid global variables.

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

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂