This is a creation in Article, where the information may have evolved or changed.
Command-line arguments are often used to specify options for the command-line program. For example wc -l
, command -l
-line arguments are in the command.
Golang provides a flag package to support basic command-line argument parsing.
Command-line Syntax
The command line syntax is as follows:
-flag-flag=x-flag x // non-boolean flags only
Basic usage
Defining the Flag parameter
Method One :
flag.Xxx()
return a corresponding pointer by means of the method, and give a few chestnuts:
wordPtr := flag.String("word", "foo", "a string")numbPtr := flag.Int("numb", 42, "an int")boolPtr := flag.Bool("fork", false, "a bool")
Used in the form offlag.Type(name, defValue, usage)
Method Two :
The flag.XxxVar()
flag is bound to a variable by means of the method, which returns the value type, for example, a chestnut:
var svar stringflag.StringVar(&svar, "svar", "bar", "a string var")
Used in the form offlag.TypeVar(&flagvar, name, defValue, usage)
Method Three :
By flag.Var()
binding a custom type, the custom type needs to implement the Value
interface ( Receives
must be a pointer),
type Value interface { String() string Set(string) error}
How to use itflag.Var(&flagvar, name, usage)
Analytical
Call flag.Parse()
Parse command-line arguments to the defined flag
Other
can also be flag.Args()
used flag.Arg(i)
to get non-flag command line arguments
Chestnuts
Package Mainimport "flag" import "FMT" import "StrConv" type percentage float32func (P *percentage) Set (s string) error {V, ERR: = StrConv. Parsefloat (S, +) *p = percentage (v) return Err}func (P *percentage) string () string {return FMT. Sprintf ("%f", *p)}func main () {nameptr: = flag. String ("name", "Lyh", "User ' name") Ageptr: = flag. Int ("Age", Vipptr, "user's age"): = flag. Bool ("VIP", True, "is a VIP user") var email string flag. Stringvar (&email, "email", "lyhopq@gmail.com", "User's email") var pop percentage flag. Var (&pop, "Pop", "popularity") flag. Parse () Others: = flag. Args () fmt. Println ("Name:", *nameptr) fmt. Println ("Age:", *ageptr) fmt. Println ("VIP:", *vipptr) fmt. Println ("Pop:", pop) fmt. Println ("Email:", email) fmt. Println ("Other:", others)}$./command-line-flagsname:lyhage:22vip:trueemail:lyhopq@gmail.comother: []$./ Command-line-flags-name golang-age 4-vip=true-pop 99 Simple high concurrency and so name:golangage:4vip:truepop:99email:lyhopq@gmail.co Mother: [Concise high concurrency and so on]$./command-line-flags-husage of./command-line-flags:-age=22:user ' s age-email= "lyhopq@gmail.com": User ' s Email-name= "lyh": User ' s name-pop=0.0:popularity-vip=true:is a VIP user
Reference
- Golang Flag Package Use details (i)
- Go by Example:command-line Flags
- Method of parameter parsing for command line using flag package in Go language