flag.String and flag.Int
- Go course
- Intermediate
- Lesson 72/80
- 4 min
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]Practice 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.
Starter code
package main
import (
"flag"
"fmt"
"strings"
)
func main() {
// buraya yaz
}Sample 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)
}Expected output
[go web]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
- The value the user gave
Explanation: The pointer is filled with the default at definition; command-line values are written only when Parse is called.
2 Read the value
ad := flag.String("ad", "dünya", "kişi")
flag.Parse()
fmt.Println("Merhaba", ____ad)
ad := flag.String("ad", "dünya", "kişi")
flag.Parse()
fmt.Println("Merhaba", *ad)
Explanation: flag.String returns a pointer; the value is reached with *ad.
3 Function and return
| Term | Meaning |
|---|---|
flag.String |
*string |
flag.Int |
*int |
flag.DurationVar |
Binds an existing variable |
flag.Var |
Custom flag.Value |