How can I execute a specific function by entering a flag, for example, I have three flags:
wordPtr
numbPtr
forkPtr
And when executing a single one, the function that calls is executed:
.\data -wordPtr Test
When executing that flag, only the word function is executed:
package main
import (
"flag"
"fmt"
)
var (
wordPtr string
numbPtr int
forkPtr bool
)
func main() {
flag.StringVar(&wordPtr, "word", "foo", "a string")
flag.IntVar(&numbPtr, "numb", 42, "an int")
flag.BoolVar(&forkPtr, "fork", false, "a bool")
flag.Parse()
if wordPtr != `` {
word(wordPtr)
}
if numbPtr != 0 {
numb(numbPtr)
}
if forkPtr {
fork(forkPtr)
}
}
func word(word string) {
fmt.Println("word:", word)
}
func numb(numb int) {
fmt.Println("numb:", numb)
}
func fork(fork bool) {
fmt.Println("fork:", fork)
}
But, when I execute the last flag, all functions are executed
PS C:\golang> .\logdata.exe -fork
word: foo
numb: 42
fork: true
PS C:\golang>
Do you know why?
You provide default values for the
wordandnumbflags, which means if you don't provide them as cli arguments, they will get the default value.And after
flag.Parse()you only test ifwordPtris not empty ornumbPtris not0, and since the default values are not these, the tests will pass and the functions will be executed.If you use the empty string and
0as the defaults:Then if you don't provide these as cli arguments, your tests will not pass:
Will output:
If you want to test if
wordornumbwas provided as cli arguments, see Check if Flag Was Provided in Go.