flag.Parse
- Go course
- Intermediate
- Lesson 73/80
- 4 min
Learn to parse the command line with Parse.
flag.Parse and arguments
After Parse handles the options, the remaining positional arguments are available through flag.Args(); flag.NArg() gives their count and flag.Arg(i) a single one:
// ./kopyala -f kaynak.txt hedef.txt
zorla := flag.Bool("f", false, "üzerine yaz")
flag.Parse()
if flag.NArg() != 2 {
fmt.Fprintln(os.Stderr, "kullanım: kopyala [-f] KAYNAK HEDEF")
os.Exit(2)
}
kaynak, hedef := flag.Arg(0), flag.Arg(1)Exit code 2 is a conventional choice for usage errors.
Custom help text
Assign your own function to the flag.Usage variable to customize the -h output:
flag.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "kullanım: %s [seçenekler] DOSYA\n", os.Args[0])
flag.PrintDefaults()
}PrintDefaults prints every defined option with its description.
Practice Positional arguments
Define the bool option f in a FlagSet and parse []string{"-f", "a.txt", "b.txt"}. Print *f, fs.NArg() and fs.Arg(1) on one line.
Starter code
package main
import (
"flag"
"fmt"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"flag"
"fmt"
)
func main() {
fs := flag.NewFlagSet("kopyala", flag.ContinueOnError)
f := fs.Bool("f", false, "üzerine yaz")
if err := fs.Parse([]string{"-f", "a.txt", "b.txt"}); err != nil {
fmt.Println(err)
return
}
fmt.Println(*f, fs.NArg(), fs.Arg(1))
}Expected output
true 2 b.txt
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>./app -- -dosya.txt</code>, what does <code>--</code> do?
- It errors
- It ends option parsing; -dosya.txt becomes a positional argument Correct answer
- It starts a comment
- It resets all options
Explanation: Everything after -- stays in flag.Args() as a positional argument, even if it starts with a dash.
2 Argument count
flag.Parse()
if flag.____() < 1 {
flag.Usage()
os.Exit(2)
}
flag.Parse()
if flag.NArg() < 1 {
flag.Usage()
os.Exit(2)
}
Explanation: NArg returns the number of positional arguments left after the options.
3 Function and result
| Term | Meaning |
|---|---|
flag.Args() |
Remaining arguments |
flag.NArg() |
Argument count |
flag.Arg(0) |
The first argument |
flag.NFlag() |
Number of options given |