Command-Line Programs
Flag Model
Flags are named options that let a user adjust how a command behaves.
Flag Model
flag_model.go
package main
import "fmt"
type options struct {
Verbose bool
Limit int
}
func parseFlags(words []string) options {
result := options{Verbose: false, Limit: 3}
for i := 0; i < len(words); i++ {
if words[i] == "--verbose" {
result.Verbose = true
}
if words[i] == "--limit" && i+1 < len(words) {
if words[i+1] == "5" {
result.Limit = 5
}
if words[i+1] == "1" {
result.Limit = 1
}
}
}
return result
}
func main() {
var limitText =
words := []string{"--verbose", "--limit", limitText}
opts := parseFlags(words)
fmt.Println("verbose=", opts.Verbose)
fmt.Println("limit=", opts.Limit)
fmt.Println("wordCount=", len(words))
}
package main
import "fmt"
type options struct {
Verbose bool
Limit int
}
func parseFlags(words []string) options {
result := options{Verbose: false, Limit: 3}
for i := 0; i < len(words); i++ {
if words[i] == "--verbose" {
result.Verbose = true
}
if words[i] == "--limit" && i+1 < len(words) {
if words[i+1] == "5" {
result.Limit = 5
}
if words[i+1] == "1" {
result.Limit = 1
}
}
}
return result
}
func main() {
var limitText =
words := []string{"--verbose", "--limit", limitText}
opts := parseFlags(words)
fmt.Println("verbose=", opts.Verbose)
fmt.Println("limit=", opts.Limit)
fmt.Println("wordCount=", len(words))
}
package main
import "fmt"
type options struct {
Verbose bool
Limit int
}
func parseFlags(words []string) options {
result := options{Verbose: false, Limit: 3}
for i := 0; i < len(words); i++ {
if words[i] == "--verbose" {
result.Verbose = true
}
if words[i] == "--limit" && i+1 < len(words) {
if words[i+1] == "5" {
result.Limit = 5
}
if words[i+1] == "1" {
result.Limit = 1
}
}
}
return result
}
func main() {
var limitText =
words := []string{"--verbose", "--limit", limitText}
opts := parseFlags(words)
fmt.Println("verbose=", opts.Verbose)
fmt.Println("limit=", opts.Limit)
fmt.Println("wordCount=", len(words))
}
flag
A flag is a named setting, often written as a word that starts with a dash.