Flag
Flag is the package that the Go standard library provides to parse the command-line arguments.
Flag is a package Qanda.ren library that the Go Standard library provides parsing command-line arguments
How to use:
Flag. Type (name, defvalue, usage)
Where type is a string, Int, bool, and so on, and returns a pointer of the corresponding type.
Flag. Typevar (&flagvar, name, defvalue, usage)
Binds the flag to a variable.
Custom Flag
Just implement flag. The value interface can:
Type Value Interface {
String () string
Set (String) error
}
Define the flag in the following way:
Flag. Var (&flagvar, name, usage)
Example
Package Main
Import "Flag"
Import "FMT"
Import "StrConv"
Type percentage float32
Func (P *percentage) Set (s string) error {
V, err: = StrConv. Parsefloat (S, 32)
*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", page, "User's Age")
Vipptr: = flag. Bool ("VIP", True, "is a VIP user")
var email string
Flag. Stringvar (&email, "email", "[email protected]", "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-flags
Name:lyh
Age:22
Vip:true
Email: [Email protected]
Other: []
$./command-line-flags-name golang-age 4-vip=true-pop 99 simple, high concurrency, etc.
Name:golang
Age:4
Vip:true
pop:99
Email: [Email protected]
Other: [Simple high concurrency, etc.]
$./command-line-flags-h
Usage of./command-line-flags:
-age=22:user ' s Age
-email= "[Email protected]": User ' s email
-name= "lyh": User ' s name
-pop=0.0:popularity
-vip=true:is a VIP User
Flag is a package Qanda.ren library that the Go Standard library provides parsing command-line arguments