I'm trying to get command line flags working with strings in golang. Here is my main/main.go file:
package main
import (
"flag"
"log"
)
func main() {
flagString := flag.String("string", "foo", "Enter this string and have it printed back out.")
log.Println("You entered ", *flagString)
}
This simply takes the flag from the command line and prints it out, with default value "foo".
I enter the following into the command prompt after building the project, trying to make it print out bar:
> main -string=bar
(log time+date) You entered foo
> main -string="bar"
(log time+date) You entered foo
Is there something wrong with my code or am I entering it into the command prompt incorrectly?
By the way, I am running Windows 10.
After calling flag.String(...), you need to simply call flag.Parse().
In your example:
package main
import (
"flag"
"log"
)
func main() {
flagString := flag.String("string", "foo", "Enter this string and have it printed back out.")
flags.Parse()
log.Println("You entered ", *flagString)
}