全局变量 / 获取命令行参数并打印它

huangapple go评论101阅读模式
英文:

Global variables / Get command line argument and print it

问题

这可能听起来很愚蠢,但是我如何在Go中定义一个全局变量?const myglobalvariable = "Hi there!"并不起作用...

我只想获取命令行参数,然后打印它。我使用以下代码片段来实现:

  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. )
  6. var text string
  7. func main() {
  8. gettext()
  9. fmt.Println(text)
  10. }
  11. func gettext() {
  12. flag.Parse()
  13. args := flag.Args()
  14. if len(args) < 1 {
  15. fmt.Println("Please give me some text!")
  16. } else {
  17. text = args[0]
  18. }
  19. }

问题是它只打印一个空行,所以我想通过使用const myglobalvariable = "Hi there!"来声明一个全局变量,但是我得到了错误cannot use flag.Args() (type []string) as type ideal string in assignment...
...我知道这是一个新手问题,所以希望你能帮助我...

英文:

This may sound stupid but how do I define a global variable in Go? const myglobalvariable = &quot;Hi there!&quot; doesn't really work...

I just want to get the command line argument and after this I want to print it. I do this using this code snippet:

  1. package main
  2. import (
  3. &quot;flag&quot;
  4. &quot;fmt&quot;
  5. )
  6. func main() {
  7. gettext();
  8. fmt.Println(text)
  9. }
  10. func gettext() {
  11. flag.Parse()
  12. text := flag.Args()
  13. if len(text) &lt; 1 {
  14. fmt.Println(&quot;Please give me some text!&quot;)
  15. }
  16. }

The problem is that it just prints an empty line so I thought about declaring a global variable using const myglobalvariable = &quot;Hi there!&quot; but I just get the error cannot use flag.Args() (type []string) as type ideal string in assignment...
...I know this is a noob question so I hope you can help me...

答案1

得分: 30

我至少看到了两个问题,也许是三个。

  1. 如何声明全局变量?
  2. 如何声明全局常量?
  3. 如何解析命令行选项和参数?

我希望下面的代码以一种有帮助的方式演示了这一点。flag包是我在Go中首次接触的包之一。当时并不明显,尽管文档正在改进。

值得一提的是,在撰写本文时,我正在使用http://weekly.golang.org作为参考。主站点已经过时了。

  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. )
  7. //这是如何声明全局变量
  8. var someOption bool
  9. //这是如何声明全局常量
  10. const usageMsg string = "goprog [-someoption] args\n"
  11. func main() {
  12. flag.BoolVar(&someOption, "someOption", false, "Run with someOption")
  13. //设置Usage将在提供了从未定义的选项时执行usage,例如"goprog -someOption -foo"
  14. flag.Usage = usage
  15. flag.Parse()
  16. if someOption {
  17. fmt.Printf("someOption was set\n")
  18. }
  19. //如果有其他必需的命令行参数,不是选项,现在可以手动解析它们。flag不会为您完成这部分。
  20. for _, v := range flag.Args() {
  21. fmt.Printf("%+v\n", v)
  22. }
  23. //将此程序命名为"./goprog -someOption dog cat goldfish",输出如下:
  24. //someOption was set
  25. //dog
  26. //cat
  27. //goldfish
  28. }
  29. func usage() {
  30. fmt.Printf(usageMsg)
  31. flag.PrintDefaults()
  32. os.Exit(1)
  33. }
英文:

I see at least two questions here, maybe three.

  1. How do you declare a global variable?
  2. How do you declare a global constant?
  3. How do you parse command line options and arguments?

I hope the code below demonstrates this in a helpful way. The flag package was one of the first packages I had to cut my teeth on in Go. At the time it wasn't obvious, though the documentation is improving.

FYI, at the time of this writing I am using http://weekly.golang.org as a reference. The main site is far too out of date.

<pre><code>package main

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

//This is how you declare a global variable
var someOption bool

//This is how you declare a global constant
const usageMsg string = "goprog [-someoption] args\n"

func main() {
flag.BoolVar(&someOption, "someOption", false, "Run with someOption")
//Setting Usage will cause usage to be executed if options are provided
//that were never defined, e.g. "goprog -someOption -foo"
flag.Usage = usage
flag.Parse()
if someOption {
fmt.Printf("someOption was set\n")
}
//If there are other required command line arguments, that are not
//options, they will now be available to parse manually. flag does
//not do this part for you.
for _, v := range flag.Args() {
fmt.Printf("%+v\n", v)
}

  1. //Calling this program as &quot;./goprog -someOption dog cat goldfish&quot;
  2. //outputs
  3. //someOption was set
  4. //dog
  5. //cat
  6. //goldfish

}

func usage() {
fmt.Printf(usageMsg)
flag.PrintDefaults()
os.Exit(1)
}</code></pre>

答案2

得分: 20

在Go语言中,最接近全局变量的东西是变量。你可以像这样定义一个:

  1. var text string

然而,命令行参数已经存储在一个包变量os.Args中,等待你访问它们。你甚至不需要使用flag包。

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. if len(os.Args) < 2 { // (程序名是os.Arg[0])
  8. fmt.Println("请给我一些文本!")
  9. } else {
  10. fmt.Println(os.Args[1:]) // 打印所有参数
  11. }
  12. }
英文:

The closest thing to a global variable in Go is a package variable. You define one like

  1. var text string

Command line arguments though, are already sitting in a package variable, os.Args, waiting for you to access them. You don't even need the flag package.

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;os&quot;
  5. )
  6. func main() {
  7. if len(os.Args) &lt; 2 { // (program name is os.Arg[0])
  8. fmt.Println(&quot;Please give me some text!&quot;)
  9. } else {
  10. fmt.Println(os.Args[1:]) // print all args
  11. }
  12. }

答案3

得分: -1

你为什么需要一个全局变量?例如,

  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. )
  6. func main() {
  7. text := gettext()
  8. fmt.Println(text)
  9. }
  10. func gettext() []string {
  11. flag.Parse()
  12. text := flag.Args()
  13. if len(text) < 1 {
  14. fmt.Println("请给我一些文本!")
  15. }
  16. return text
  17. }
英文:

Why do you need a global variable? For example,

  1. package main
  2. import (
  3. &quot;flag&quot;
  4. &quot;fmt&quot;
  5. )
  6. func main() {
  7. text := gettext()
  8. fmt.Println(text)
  9. }
  10. func gettext() []string {
  11. flag.Parse()
  12. text := flag.Args()
  13. if len(text) &lt; 1 {
  14. fmt.Println(&quot;Please give me some text!&quot;)
  15. }
  16. return text
  17. }

答案4

得分: -2

查看gofmtgodoc其他如何处理相同的事情。

英文:

See how gofmt, godoc, and others handle the same thing.

huangapple
  • 本文由 发表于 2012年3月3日 04:02:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/9539633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定