search
HomeBackend DevelopmentGolangHow to use command line arguments in Go?

How to use command line arguments in Go?

May 10, 2023 pm 07:03 PM
go languageCommand line parametersInstructions

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.

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)
}

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

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

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!

Statement
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
Go vs. Other Languages: A Comparative AnalysisGo vs. Other Languages: A Comparative AnalysisApr 28, 2025 am 12:17 AM

Goisastrongchoiceforprojectsneedingsimplicity,performance,andconcurrency,butitmaylackinadvancedfeaturesandecosystemmaturity.1)Go'ssyntaxissimpleandeasytolearn,leadingtofewerbugsandmoremaintainablecode,thoughitlacksfeatureslikemethodoverloading.2)Itpe

Comparing init Functions in Go to Static Initializers in Other LanguagesComparing init Functions in Go to Static Initializers in Other LanguagesApr 28, 2025 am 12:16 AM

Go'sinitfunctionandJava'sstaticinitializersbothservetosetupenvironmentsbeforethemainfunction,buttheydifferinexecutionandcontrol.Go'sinitissimpleandautomatic,suitableforbasicsetupsbutcanleadtocomplexityifoverused.Java'sstaticinitializersoffermorecontr

Common Use Cases for the init Function in GoCommon Use Cases for the init Function in GoApr 28, 2025 am 12:13 AM

ThecommonusecasesfortheinitfunctioninGoare:1)loadingconfigurationfilesbeforethemainprogramstarts,2)initializingglobalvariables,and3)runningpre-checksorvalidationsbeforetheprogramproceeds.Theinitfunctionisautomaticallycalledbeforethemainfunction,makin

Channels in Go: Mastering Inter-Goroutine CommunicationChannels in Go: Mastering Inter-Goroutine CommunicationApr 28, 2025 am 12:04 AM

ChannelsarecrucialinGoforenablingsafeandefficientcommunicationbetweengoroutines.Theyfacilitatesynchronizationandmanagegoroutinelifecycle,essentialforconcurrentprogramming.Channelsallowsendingandreceivingvalues,actassignalsforsynchronization,andsuppor

Wrapping Errors in Go: Adding Context to Error ChainsWrapping Errors in Go: Adding Context to Error ChainsApr 28, 2025 am 12:02 AM

In Go, errors can be wrapped and context can be added via errors.Wrap and errors.Unwrap methods. 1) Using the new feature of the errors package, you can add context information during error propagation. 2) Help locate the problem by wrapping errors through fmt.Errorf and %w. 3) Custom error types can create more semantic errors and enhance the expressive ability of error handling.

Security Considerations When Developing with GoSecurity Considerations When Developing with GoApr 27, 2025 am 12:18 AM

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Understanding Go's error InterfaceUnderstanding Go's error InterfaceApr 27, 2025 am 12:16 AM

Go's error interface is defined as typeerrorinterface{Error()string}, allowing any type that implements the Error() method to be considered an error. The steps for use are as follows: 1. Basically check and log errors, such as iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}. 2. Create a custom error type to provide more information, such as typeMyErrorstruct{MsgstringDetailstring}. 3. Use error wrappers (since Go1.13) to add context without losing the original error message,

Error Handling in Concurrent Go ProgramsError Handling in Concurrent Go ProgramsApr 27, 2025 am 12:13 AM

ToeffectivelyhandleerrorsinconcurrentGoprograms,usechannelstocommunicateerrors,implementerrorwatchers,considertimeouts,usebufferedchannels,andprovideclearerrormessages.1)Usechannelstopasserrorsfromgoroutinestothemainfunction.2)Implementanerrorwatcher

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function