The flag package
- Go course
- Intermediate
- Lesson 71/80
- 4 min
Learn the basics of the flag package.
The flag package
The flag package parses command-line options (-port=8080, -v) and generates help text automatically:
port := flag.Int("port", 8080, "dinlenecek port")
ayrintili := flag.Bool("v", false, "ayrıntılı çıktı")
flag.Parse()
fmt.Println(*port, *ayrintili)Running ./app -h lists every option with its description and default value.
The bool option trap
Bool options don't take a value after a space: if you write -v false, -v becomes true and false counts as a positional argument. To turn it off write -v=false. Parsing also stops at the first positional argument: in app dosya.txt -v, -v isn't seen as an option.
Practice Parse with a FlagSet
Create fs := flag.NewFlagSet("app", flag.ContinueOnError); define the options port (int, default 8080) and v (bool). Call fs.Parse([]string{"-port=9000", "-v"}) and print both values.
Starter code
package main
import (
"flag"
"fmt"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"flag"
"fmt"
)
func main() {
fs := flag.NewFlagSet("app", flag.ContinueOnError)
port := fs.Int("port", 8080, "dinlenecek port")
v := fs.Bool("v", false, "ayrıntılı çıktı")
if err := fs.Parse([]string{"-port=9000", "-v"}); err != nil {
fmt.Println(err)
return
}
fmt.Println(*port, *v)
}Expected output
9000 true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the flag package do with <code>-port 9000</code>, <code>-port=9000</code> and <code>--port=9000</code>?
- Only -port=9000
- Only --port=9000
- None of them
- It accepts all three Correct answer
Explanation: The flag package treats single and double dashes the same; for non-bool options the value can follow a space or =.
2 Parse
port := flag.Int("port", 8080, "port")
flag.____()
fmt.Println(*port)
port := flag.Int("port", 8080, "port")
flag.Parse()
fmt.Println(*port)
Explanation: flag.Parse reads os.Args and fills the defined options.
3 Command line
| Term | Meaning |
|---|---|
-port=9000 |
Option with a value |
-v |
Bool option |
-v=false |
Turning a bool off |
-h |
Help text |