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条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?