这可能听起来很愚蠢,但如何在Go中定义全局变量? const myglobalvariable = "Hi there!"
并没有真正起作用......
我只想获得命令行参数,之后我想打印它。我使用此代码段执行此操作:
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!")
}
}
问题是它只打印一个空行,所以我考虑使用const myglobalvariable = "Hi there!"
声明一个全局变量,但我得到错误cannot use flag.Args() (type []string) as type ideal string in assignment
...
......我知道这是一个菜鸟问题,所以我希望你能帮助我......
答案 0 :(得分:30)
我在这里至少看到两个问题,可能是三个。
我希望下面的代码以有用的方式演示这一点。旗帜套餐是我在Go中切开牙齿的第一批包裹之一。虽然文档正在改进,但当时并不明显。
仅供参考,在撰写本文时,我使用http://weekly.golang.org作为参考。主要网站太过时了。
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)
}
答案 1 :(得分:20)
Go中与全局变量最接近的是包变量。你定义一个像
var text string
虽然命令行参数已经位于包变量os.Args中,等待您访问它们。你甚至不需要旗帜包。
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
}
}
答案 2 :(得分:-1)
答案 3 :(得分:-3)
为什么需要全局变量?例如,
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
}