A method for parameter parsing of the command line using the flag package in the Go language _golang

Source: Internet
Author: User
Tags email string

Flag
flag is the package that the Go standard library provides to parse command-line arguments.

How to use:

Flag. Type (name, defvalue, usage)

Where type is string, INT, bool, and so on, and returns a pointer to the corresponding type.

Flag. Typevar (&flagvar, name, defvalue, usage)

Bind the flag to a variable.

Custom Flag
as long as the realization of flag. The value interface can:

Type Value Interface {
  string () string
  Set (String) Error
}

The flag is defined by the following methods:

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,) *p = percentage (v) return err} func (P *percentage) string () string {return FMT. Sprintf ("%f", *p)} func main () {nameptr: = flag. String ("name", "Lyh", "User ' s name") Ageptr: = flag. Int ("Age", "User's Age") Vipptr: = 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-flags
name:lyh
age:22
vip:true
email:lyhopq@gmail.com other
: []
$./command-line-flags-name golang-age 4-vip=true-pop 99 Compact High concurrency
name:golang
age:4 vip:true
Pop :
email:lyhopq@gmail.com Other
: [Simple high concurrency and so on]
$/command-line-flags-h
Usage of./command-line-flags:
 -age=22:user ' age
 -email= ' lyhopq@gmail.com ": User ' s email
 -name=" LYH ": User's name
 -pop=0.0:popularity
 -vip=true:is a VIP user

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.