2017-09-23 170 views
0

我想创建一个用于在Golang中使用显示的外部函数,但我不知道如何调用该标志变量。这是我的实际代码:Golang:命令行参数undefined:变量

package main 

import (
    "flag" 
    "fmt" 
    "os" 
) 

func Usage() { 
    if ArgSend { 
     fmt.Printf("Usage: SEND") 
     flag.PrintDefaults() 
     os.Exit(0) 

    } else if ArgTest { 
     fmt.Printf("Usage: -test") 
     flag.PrintDefaults() 
     os.Exit(0) 

    } else if ArgMacro { 
     fmt.Printf("Usage: -macro") 
     os.Exit(0) 

    } else { 
     fmt.Printf("Usage of: <-test|-send|-macro>\n") 
     os.Exit(0) 
    } 
} 



func main() { 

    //defaults variables 
    ArgTest, ArgSend, ArgMacro := false, false, false 

    // Args parse 
    flag.BoolVar(&ArgTest, "-test", false, "run test mode") 
    flag.BoolVar(&ArgSend, "-send", false, "run send mode") 
    flag.BoolVar(&ArgMacro, "-macro", false, "run macro mode") 

    flag.Parse() 

    Usage() 
} 

这个错误:

F:\dev\GoLang\gitlab\EasySend\tmp>go run stackoverflow.go -test 
# command-line-arguments 
.\stackoverflow.go:10:5: undefined: ArgSend 
.\stackoverflow.go:15:12: undefined: ArgTest 
.\stackoverflow.go:20:12: undefined: ArgMacro 

如何检查标志解析如果ArgSend是真/假?

回答

0

一个错误在你的榜样几件事情:

  • 你想在你的使用功能使用的变量是不是在范围,因为所有的标志变量主(
  • 的内部声明标志变量本身的类型是错误的,您应该使用标志包中的类型
  • 其他错误包括在标志文本(第二参数)的前面添加' - '而不是解引用标志变量(它们将是指针)

这里有一个很好的例子:golang flags example,你应该检查godocs on flags特别是默认行为,并定制使用的功能,如果你有麻烦修改的例子,然后再次询问这里

更新时间: 对不起,正如彼得在评论中指出的那样,我的回答有点混乱和不正确。

要说明,在“golang标志示例”提供的示例中给出了flag.Bool链接。当使用flag.Bool时,返回一个指针。

在问题中,您使用flag.BoolVar,它允许您引用一个布尔值。您在问题中使用flag.BoolVar实际上是正确的。

因此,所有你需要做的是解决范围确定问题,真不明白你正在尝试与您的使用情况做的,但这里是一个工作的例子,应澄清:

注:本例中的标志瓦尔可以留在主体内,因为它们不是必需的使用功能

package main 

import (
    "flag" 
    "fmt" 
    "os" 
) 

func Usage() { 
    // custom usage (help) output here if needed 
    fmt.Println("") 
    fmt.Println("Application Flags:") 
    flag.PrintDefaults() 
    fmt.Println("") 
} 

var ArgTest, ArgSend, ArgMacro bool 

func main() { 

    // Args parse 
    flag.BoolVar(&ArgTest, "test", false, "run test mode") 
    flag.BoolVar(&ArgSend, "send", false, "run send mode") 
    flag.BoolVar(&ArgMacro, "macro", false, "run macro mode") 

    flag.Parse() 

    // assign custom usage function (will be shown by default if -h or --help flag is passed) 
    flag.Usage = Usage 

    // if no flags print usage (not default behaviour) 
    if len(os.Args) == 1 { 
     Usage() 
    } 

    fmt.Printf("ArgTest val: %t\n", ArgTest) 
    fmt.Printf("ArgSend val: %t\n", ArgSend) 
    fmt.Printf("ArgMacro val: %t\n", ArgMacro) 

} 
+0

不要混淆flag.BoolVar和flag.Bool。 – Peter

+0

@彼得感谢您的意见,我已经更新了答案,希望能够澄清一点 – WebweaverD