猿问

在go中声明一个没有值的全局变量

我有一个程序需要 1 个或 2 个参数,具体取决于用户想要运行的内容


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)

}

我需要clientSet变量是全局的,但如果用户只想使用验证函数,我不需要用户拥有 os.Args[2]。将函数放在clientSet里面main()会使我的foo()函数损坏,并且我无法声明一个具有空值的变量。


所以我希望我的用户能够顺利go run main.go validate运行go run main.go sync production。


*生产是一个任意值


我可以让我的用户运行来go run main.go validate _解决这个问题,但那会很不雅观。解决这个问题的最佳方法是什么?


Helenr
浏览 129回答 3
3回答

呼啦一阵风

在这种情况下,我什至不认为需要全局变量。您可以让同步功能接受一个ClientSeteg func sync(c ClientSet)。但是如果你真的需要全局变量,那么你不应该这样做,除非你希望你的程序在没有参数存在时发生恐慌。var (&nbsp; &nbsp;clientSet = tools.NewClientSet(os.Args[2]))您应该做的是为它分配一个默认值或您的类型的零值。var (&nbsp; &nbsp;clientSet tools.ClientSet)您的主要功能看起来像这样:var (&nbsp; &nbsp; clientSet tools.ClientSet)func main() {&nbsp; &nbsp; if len(os.Args) < 2 {&nbsp; &nbsp; &nbsp; &nbsp; os.Exit(1)&nbsp; &nbsp; }&nbsp; &nbsp; switch os.Args[1] {&nbsp; &nbsp; case "validate":&nbsp; &nbsp; &nbsp; &nbsp; validate()&nbsp; &nbsp; case "sync":&nbsp; &nbsp; &nbsp; &nbsp; if len(os.Args) < 3 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os.Exit(1)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; clientSet = tools.NewClientSet(os.Args[2])&nbsp; &nbsp; &nbsp; &nbsp; sync()&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; // place your default case here&nbsp; &nbsp; }}尽管如此,我还是建议您将 a 传递ClientSet给 sync 函数,因为它会避免使用全局变量。

潇潇雨雨

答案通常是不使用全局变量。取而代之的是foo接受一个参数foo(clientSet ClientSet)并仅在需要时实例化它。

收到一只叮咚

只需使用len(os.Args)函数var (&nbsp; &nbsp; clientSet tools.ClientSet)func main() {&nbsp; &nbsp; if len(os.Agrs) == 1 {&nbsp; &nbsp; &nbsp; &nbsp; // just the file name&nbsp; &nbsp; } else if len(os.Args) == 2 {&nbsp; &nbsp; &nbsp; &nbsp; if os.Args[1] == "validate" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // run validate function, no need for user to have os.Args[2]&nbsp; &nbsp; &nbsp; &nbsp; } else if os.Args[1] == "sync" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // sync with no argument show error&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else if len(os.Args) == 3 {&nbsp; &nbsp; &nbsp; &nbsp; if os.Args[1] == "validate" {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clientSet = tools.NewClientSet(os.Args[2])&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // non validate with the second arg&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // else, if required&nbsp; &nbsp; }}尽管我建议您不要使用全局变量。尽可能避免。
随时随地看视频慕课网APP

相关分类

Go
我要回答