I'm currently reading a book on Go, and saw the following script:
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"strings"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU()) // Use all the machine's cores
log.SetFlags(0)
algorithm,
minSize, maxSize, suffixes, files := handleCommandLine()
if algorithm == 1 {
sink(filterSize(minSize, maxSize, filterSuffixes(suffixes, source(files))))
} else {
channel1 := source(files)
channel2 := filterSuffixes(suffixes, channel1)
channel3 := filterSize(minSize, maxSize, channel2)
sink(channel3)
}
}
func handleCommandLine() (algorithm int, minSize, maxSize int64,
suffixes, files []string) {
flag.IntVar(&algorithm, "algorithm", 1, "1 or 2")
flag.Int64Var(&minSize, "min", -1,
"minimum file size (-1 means no minimum)")
flag.Int64Var(&maxSize, "max", -1,
"maximum file size (-1 means no maximum)")
var suffixesOpt *string = flag.String("suffixes", "",
"comma-separated list of file suffixes")
flag.Parse()
if algorithm != 1 && algorithm != 2 {
algorithm = 1
}
if minSize > maxSize && maxSize != -1 {
log.Fatalln("minimum size must be < maximum size")
}
suffixes = []string{}
if *suffixesOpt != "" {
suffixes = strings.Split(*suffixesOpt, ",")
}
files = flag.Args()
return algorithm, minSize, maxSize, suffixes, files
}
I pasted only relevant parts since it's too long to paste here. I'll add immediately if more parts or the whole part are required.
In the above code, why the line flag.IntVar(&algorithm, "algorithm", 1, "1 or 2")
doesn't return an error? As long as I know, when you use flag.IntVar
, you have to first define a variable specified as its first argument (algorithm
in this case) before call the function - otherwise it returns an undefined error.
If you write out the following code:
package main
import "flag"
func main() {
flag.IntVar(&a, "a", 0, "test")
}
and if you execute it, you got the error undefined: a
. So I wonder why the first code, which is written by the book's author and I actually tried to run doesn't return an error while the second one does. For your information, there are no variables or constants predefined and there is no init()
function in the script. I also checked out the two functions before the handleCommandLine()
call on the main()
function, (i.e. runtime.GOMAXPROCS(runtime.NumCPU())
and log.SetFlags(0)
), but am pretty sure that the former isn't even relevant on this issue. And I didn't get what it means in documentation with respect to the latter, so maybe it's causing the issue?