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

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

Global variables / Get command line argument and print it

问题

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

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

package main

import (
	"flag"
	"fmt"
)

var text string

func main() {
	gettext()
	fmt.Println(text)
}

func gettext() {
	flag.Parse()
	args := flag.Args()
	if len(args) < 1 {
		fmt.Println("Please give me some text!")
	} else {
		text = args[0]
	}
}

问题是它只打印一个空行,所以我想通过使用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:

package main

import (
	&quot;flag&quot;
	&quot;fmt&quot;
)

func main() {
	gettext();
	fmt.Println(text)
}

func gettext() {
	flag.Parse()
	text := flag.Args()
	if len(text) &lt; 1 {
		fmt.Println(&quot;Please give me some text!&quot;)
	}
}

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作为参考。主站点已经过时了。

package main

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

//这是如何声明全局变量
var someOption bool

//这是如何声明全局常量
const usageMsg string = "goprog [-someoption] args\n"

func main() {
	flag.BoolVar(&someOption, "someOption", false, "Run with someOption")
	//设置Usage将在提供了从未定义的选项时执行usage,例如"goprog -someOption -foo"
	flag.Usage = usage
	flag.Parse()
	if someOption {
		fmt.Printf("someOption was set\n")
	}
	//如果有其他必需的命令行参数,不是选项,现在可以手动解析它们。flag不会为您完成这部分。
	for _, v := range flag.Args() {
		fmt.Printf("%+v\n", v)
	}

	//将此程序命名为"./goprog -someOption dog cat goldfish",输出如下:
	//someOption was set
	//dog
	//cat
	//goldfish
}

func usage() {
	fmt.Printf(usageMsg)
	flag.PrintDefaults()
	os.Exit(1)
}
英文:

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

//Calling this program as &quot;./goprog -someOption dog cat goldfish&quot;
//outputs
//someOption was set
//dog
//cat
//goldfish

}

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

答案2

得分: 20

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

var text string

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

package main

import (
    "fmt"
    "os"
)

func main() {
    if len(os.Args) < 2 {     // (程序名是os.Arg[0])
        fmt.Println("请给我一些文本!")
    } else {
        fmt.Println(os.Args[1:])  // 打印所有参数
    }
}
英文:

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

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.

package main

import (
    &quot;fmt&quot;
    &quot;os&quot;
)

func main() {
    if len(os.Args) &lt; 2 {     // (program name is os.Arg[0])
        fmt.Println(&quot;Please give me some text!&quot;)
    } else {
        fmt.Println(os.Args[1:])  // print all args
    }
}

答案3

得分: -1

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

package main

import (
    "flag"
    "fmt"
)

func main() {
    text := gettext()
    fmt.Println(text)
}

func gettext() []string {
    flag.Parse()
    text := flag.Args()
    if len(text) < 1 {
        fmt.Println("请给我一些文本!")
    }
    return text
}
英文:

Why do you need a global variable? For example,

package main

import (
	&quot;flag&quot;
	&quot;fmt&quot;
)

func main() {
	text := gettext()
	fmt.Println(text)
}

func gettext() []string {
	flag.Parse()
	text := flag.Args()
	if len(text) &lt; 1 {
		fmt.Println(&quot;Please give me some text!&quot;)
	}
	return text
}

答案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:

确定