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...
Using the “global” Keyword. To globalize a variable, use the global keyword within a function's definition. Now changes to the variable value will be preserved.
Use the env command. The env command returns a list of all global variables that have been defined.
I see at least two questions here, maybe three.
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.
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)
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With