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

Mic*_*err 7 global-variables go

这可能听起来很愚蠢,但我如何在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!")
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Nat*_*ate 30

我在这里看到至少两个问题,也许是三个问题.

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

我希望下面的代码以有用的方式演示这一点.旗帜套餐是我在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)
}
Run Code Online (Sandbox Code Playgroud)


Son*_*nia 20

Go中与全局变量最接近的是变量.你定义一个像

var text string
Run Code Online (Sandbox Code Playgroud)

但是,命令行参数已经位于包变量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
    }
}
Run Code Online (Sandbox Code Playgroud)


pet*_*rSO -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("Please give me some text!")
    }
    return text
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为这个答案被否决了,因为它给了OP他们需要的东西,而不是他们要求的:) (4认同)