How to use command line arguments in Go?
In the Go language, command line parameters are a very important way to pass input to the program and specify runtime behavior. Go provides a standard library flag
to parse command line parameters. This article will introduce how to use command line parameters in Go.
What are command line parameters
Command line parameters are parameters passed to the program through the command line when the program is running, and are used to specify the behavior and input of the program when it is running. For example, the ls
command in Linux can accept multiple command line parameters, such as -l
to list detailed information, -a
to show and hide Documents etc.
In Go, we can use os.Args
to get all the command line arguments passed when the program is running. os.Args
is a string slice, the first element is the name of the program, and the following elements are the command line parameters. For example:
package main import ( "fmt" "os" ) func main() { fmt.Println(os.Args) }
Run the program and pass in the two parameters hello
and world
:
$ go run main.go hello world
Output result:
[/tmp/go-build3065006307/b001/exe/main hello world]
As you can see, os.Args
contains the name of the program and two command line parameters.
Use flag to parse command line parameters
Although we can obtain all command line parameters through os.Args
, in actual development, we usually use more Flexible way to parse command line arguments. The Go standard library provides the flag
package to parse command line parameters.
flag
The package provides three types of command line parameters: boolean, string and integer. These three parameters can be defined respectively through flag.Bool()
, flag.String()
and flag.Int()
.
The following is a simple example that defines a Boolean and a string command line parameter:
package main import ( "flag" "fmt" ) func main() { // 定义命令行参数 var ( isVerbose bool name string ) flag.BoolVar(&isVerbose, "v", false, "verbose") flag.StringVar(&name, "name", "", "name of the user") // 解析命令行参数 flag.Parse() // 输出命令行参数 fmt.Printf("isVerbose=%v, name=%s ", isVerbose, name) }
In the above example, we use flag.BoolVar()
and flag.StringVar()
define a Boolean and a string command line parameter respectively. These two functions have a total of four parameters:
- The address of the variable used to store the command line parameter value;
- The name of the command line parameter, which can be a single character or multiple characters Name;
- Default value of command line parameters;
- Description information of command line parameters.
After defining the command line parameters, you need to call the flag.Parse()
function to parse the command line parameters.
Run the program and pass in the two command line parameters -v
and -name="Alice"
:
$ go run main.go -v -name=Alice
Output results:
isVerbose=true, name=Alice
We can see that the flag
package can easily parse command line parameters and store the values into corresponding variables.
Customized command line parameters
In addition to using the three types of command line parameters provided by the flag
package, we can also customize some types of command line parameters.
For example, we can define a drop-down box type command line parameter to let the user choose one from several options:
package main import ( "fmt" "github.com/AlecAivazis/survey/v2" ) func main() { // 定义下拉框选项 options := []string{"red", "blue", "green"} // 定义命令行参数 var color string prompt := &survey.Select{ Message: "Pick a color:", Options: options, } survey.AskOne(prompt, &color) // 输出命令行参数 fmt.Printf("color=%s ", color) }
In the above example, we use a third-party librarygithub.com/AlecAivazis/survey/v2
Defines a drop-down box option. Then, use the survey.AskOne()
function to display the drop-down box and let the user select.
Run the program:
$ go run main.go
Output result:
? Pick a color: ▸ red blue green Answer: red color=red
We can see that the user can select a color from several options and store the selected value in color
variable.
Summary
This article introduces how to use command line parameters in Go. We can use os.Args
to get all command line parameters, or we can use the flag
package or a custom method to parse command line parameters. Using command line parameters can make our programs more flexible and easier to use, and is also a necessary skill for writing high-quality command line tools.
The above is the detailed content of How to use command line arguments in Go?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...
