Go
flag.String and flag.Int
Learn to define flags with a type.
flag.String and flag.Int
Functions such as flag.String, flag.Int and flag.Duration return a pointer; the value is filled after Parse and read with *name. Alternatively the ...Var forms bind to an existing variable:
ad := flag.String("ad", "dünya", "selamlanacak kişi")
var sure time.Duration
flag.DurationVar(&sure, "sure", 5*time.Second, "zaman aşımı")
flag.Parse()
fmt.Println("Merhaba", *ad, sure)
Duration options accept readable values such as -sure=1m30s.
Your own option type
Any type implementing the flag.Value interface (String() and Set(string) error) can be an option. For example, a repeatable option:
type liste []string
func (l *liste) String() string { return strings.Join(*l, ",") }
func (l *liste) Set(v string) error { *l = append(*l, v); return nil }
var etiketler liste
flag.Var(&etiketler, "etiket", "tekrarlanabilir")
// -etiket=go -etiket=web → [go web]
Exercise Repeatable option
Write the liste type above. Register it in a FlagSet with fs.Var(&etiketler, "etiket", "..."), parse []string{"-etiket=go", "-etiket=web"} and print etiketler.
Show example solution
package main
import (
"flag"
"fmt"
"strings"
)
type liste []string
func (l *liste) String() string { return strings.Join(*l, ",") }
func (l *liste) Set(v string) error { *l = append(*l, v); return nil }
func main() {
var etiketler liste
fs := flag.NewFlagSet("app", flag.ContinueOnError)
fs.Var(&etiketler, "etiket", "tekrarlanabilir")
if err := fs.Parse([]string{"-etiket=go", "-etiket=web"}); err != nil {
fmt.Println(err)
return
}
fmt.Println(etiketler)
}
Test yourself
-
If <code>*ad</code> is read before <code>Parse</code> after <code>ad := flag.String(...)</code>, what do you get?
- nil
- A panic
- The default value
- The value the user gave
Show answer
The default value — The pointer is filled with the default at definition; command-line values are written only when Parse is called.
-
Read the value
ad := flag.String("ad", "dünya", "kişi")
flag.Parse()
fmt.Println("Merhaba", ____ad)
Show answer
ad := flag.String("ad", "dünya", "kişi")
flag.Parse()
fmt.Println("Merhaba", *ad)
-
Function and return
- flag.String
- *string
- flag.Int
- *int
- flag.DurationVar
- Binds an existing variable
- flag.Var
- Custom flag.Value
Next lesson: flag.Parse