Table of Contents
What are command line parameters
Use flag to parse command line parameters
Customized command line parameters
Summary
Home Backend Development Golang How to use command line arguments in Go?

How to use command line arguments in Go?

May 10, 2023 pm 07:03 PM
go language Command line parameters Instructions

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)
}
Copy after login

Run the program and pass in the two parameters hello and world:

$ go run main.go hello world
Copy after login

Output result:

[/tmp/go-build3065006307/b001/exe/main hello world]
Copy after login

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.

flagThe 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)
}
Copy after login

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:

  1. The address of the variable used to store the command line parameter value;
  2. The name of the command line parameter, which can be a single character or multiple characters Name;
  3. Default value of command line parameters;
  4. 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
Copy after login

Output results:

isVerbose=true, name=Alice
Copy after login

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)
}
Copy after login

In the above example, we use a third-party librarygithub.com/AlecAivazis/survey/v2Defines 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
Copy after login

Output result:

? Pick a color: 
  ▸ red
    blue
    green
  Answer: red
color=red
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

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. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

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? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

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...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

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 provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

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, ...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

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

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

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...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

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...

See all articles