Golang getting command-line arguments

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

When deploying Golang projects, it is unavoidable to set some parameters through the command line, so how do you manipulate command-line arguments in Golang? You can use the OS library and the flag library.

Golang OS library get command line arguments

The OS can use the variable args to get command parameters, OS. Args returns an array of strings, where the first parameter is the execution of the file itself.

package mainimport (    "fmt"    "os")func main() {    fmt.Println(os.Args)}


$./cmd-user= "Root" after compilation execution

[./cmd-user=root]

This way, it is more time-consuming and cumbersome to package itself. Golang provides a flag library, which makes it easy to manipulate named row parameters and describes the use of flag below.

Golang flag get Command line arguments


Use flag to manipulate command-line arguments, supported in the following format: Flag. INT, Flag. Bool, Flag. The format of a function such as String is the same, the first parameter represents the parameter name, the second parameter represents a default value, and the third parameter represents the usage description and description. Flag. The first parameter of a function such as Stringvar is replaced with the variable address, followed by the parameter and flag. string is the same.

-id=1--id=1-id 1--id 1

It's very convenient.

Execute:

$ go Run flag.go-id=2-name= "Golang" Ok:falseid:2port:: 8080name:golang

Use the-h parameter to view Help for use:

$ go Run Flag.go-h-id=0:id-name= "123": Name-ok=false:is ok-port= ": 8080": http Listen port
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.