英文:
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 = "Hi there!"
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 (
"flag"
"fmt"
)
func main() {
gettext();
fmt.Println(text)
}
func gettext() {
flag.Parse()
text := flag.Args()
if len(text) < 1 {
fmt.Println("Please give me some text!")
}
}
The problem is that it just prints an empty line so I thought about declaring a global variable using const myglobalvariable = "Hi there!"
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
我至少看到了两个问题,也许是三个。
- 如何声明全局变量?
- 如何声明全局常量?
- 如何解析命令行选项和参数?
我希望下面的代码以一种有帮助的方式演示了这一点。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.
- How do you declare a global variable?
- How do you declare a global constant?
- 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 "./goprog -someOption dog cat goldfish"
//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 (
"fmt"
"os"
)
func main() {
if len(os.Args) < 2 { // (program name is os.Arg[0])
fmt.Println("Please give me some text!")
} 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 (
"flag"
"fmt"
)
func main() {
text := gettext()
fmt.Println(text)
}
func gettext() []string {
flag.Parse()
text := flag.Args()
if len(text) < 1 {
fmt.Println("Please give me some text!")
}
return text
}
答案4
得分: -2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论