Table of Contents
Importing and Defining Flags
Parsing the Arguments
Handling Positional Arguments
Custom Usage and Validation
Home Backend Development Golang How to use the flag package in Golang

How to use the flag package in Golang

Sep 18, 2025 am 05:23 AM
golang flag

The flag package in Go parses command-line arguments by defining flags like string, int, or bool using flag.StringVar, flag.IntVar, etc., such as flag.StringVar(&host, "host", "localhost", "server address"); after declaring flags, call flag.Parse() to process inputs, enabling access to flag values and positional arguments via flag.Args(); customize help messages by setting flag.Usage for clearer user guidance.

How to use the flag package in Golang

The flag package in Go is used to parse command-line arguments. It allows you to define flags for your program, making it easy to accept user input when running the application from the terminal. Here's how to use it effectively.

Importing and Defining Flags

Start by importing the flag package. You can define flags using functions like flag.String, flag.Int, or flag.Bool. These declare a flag with a name, default value, and usage description.

Example:

flag.StringVar(&host, "host", "localhost", "server address")
flag.IntVar(&port, "port", 8080, "server port")

This creates two flags: host (string) and port (int). The variables must be declared beforehand or passed as references directly.

Parsing the Arguments

After defining flags, call flag.Parse() to process the command-line inputs. This should come after all flag declarations and before using the flag values.

Anything that comes after the command name when running the program will be parsed. For example:

go run main.go -host=192.168.1.1 -port=3000

After flag.Parse(), the values of host and port will reflect the provided inputs or fall back to defaults.

Handling Positional Arguments

After parsing flags, any remaining arguments are called positional arguments. Use flag.Args() to get them as a slice.

For instance, in:

go run main.go -port=9000 file1.txt file2.txt

flag.Args() returns []string{"file1.txt", "file2.txt"}.

If you need the count, use flag.NArg() and flag.Arg(i) for individual access.

Custom Usage and Validation

You can customize the help message by assigning to flag.Usage. This function runs when the user requests help or provides invalid input.

flag.Usage = func() {
  fmt.Println("Usage: myapp [options] ")
  flag.PrintDefaults()
}
flag.Parse()

This gives clearer instructions than the default output.

Basically, define your flags, parse them, then access their values. Add custom usage if needed. The flag package keeps CLI tools simple and consistent.

The above is the detailed content of How to use the flag package in Golang. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

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)

Hot Topics

What is the empty struct struct{} used for in Golang What is the empty struct struct{} used for in Golang Sep 18, 2025 am 05:47 AM

struct{} is a fieldless structure in Go, which occupies zero bytes and is often used in scenarios where data is not required. It is used as a signal in the channel, such as goroutine synchronization; 2. Used as a collection of value types of maps to achieve key existence checks in efficient memory; 3. Definable stateless method receivers, suitable for dependency injection or organization functions. This type is widely used to express control flow and clear intentions.

How do you read and write files in Golang? How do you read and write files in Golang? Sep 21, 2025 am 01:59 AM

Goprovidessimpleandefficientfilehandlingusingtheosandbufiopackages.Toreadasmallfileentirely,useos.ReadFile,whichloadsthecontentintomemorysafelyandautomaticallymanagesfileoperations.Forlargefilesorincrementalprocessing,bufio.Scannerallowsline-by-liner

What are middleware in the context of Golang web servers? What are middleware in the context of Golang web servers? Sep 16, 2025 am 02:16 AM

MiddlewareinGowebserversarefunctionsthatinterceptHTTPrequestsbeforetheyreachthehandler,enablingreusablecross-cuttingfunctionality;theyworkbywrappinghandlerstoaddpre-andpost-processinglogicsuchaslogging,authentication,CORS,orerrorrecovery,andcanbechai

How to integrate with a message queue like RabbitMQ in Golang How to integrate with a message queue like RabbitMQ in Golang Sep 02, 2025 am 07:46 AM

The answer is to use the amqp091-go library to connect RabbitMQ, declare queues and switches, securely publish messages, message consumption with QoS and manual acknowledgement, and reconnect mechanisms to achieve reliable message queue integration in Go. The complete example includes connection, production, consumption and error handling processes, ensuring that messages are not lost and supporting disconnection and reconnection, and finally running RabbitMQ through Docker to complete end-to-end integration.

How do you handle graceful shutdowns in a Golang application? How do you handle graceful shutdowns in a Golang application? Sep 21, 2025 am 02:30 AM

GracefulshutdownsinGoapplicationsareessentialforreliability,achievedbyinterceptingOSsignalslikeSIGINTandSIGTERMusingtheos/signalpackagetoinitiateshutdownprocedures,thenstoppingHTTPserversgracefullywithhttp.Server’sShutdown()methodtoallowactiverequest

What is CGO and when to use it in Golang What is CGO and when to use it in Golang Sep 21, 2025 am 02:55 AM

CGOenablesGotocallCcode,allowingintegrationwithClibrarieslikeOpenSSL,accesstolow-levelsystemAPIs,andperformanceoptimization;itrequiresimporting"C"withCheadersincomments,usesC.function()syntax,anddemandscarefulmemorymanagement.However,CGOinc

How to create a custom marshaller/unmarshaller for JSON in Golang How to create a custom marshaller/unmarshaller for JSON in Golang Sep 19, 2025 am 12:01 AM

Implements JSON serialization and deserialization of customizable Go structures for MarshalJSON and UnmarshalJSON, suitable for handling non-standard formats or compatible with old data. 2. Control the output structure through MarshalJSON, such as converting field formats; 3. Parsing special format data through UnmarshalJSON, such as custom dates; 4. Pay attention to avoid infinite loops caused by recursive calls, and use type alias to bypass custom methods.

How to use generics in Golang How to use generics in Golang Sep 19, 2025 am 05:29 AM

GenericsinGoenabletype-safe,reusablefunctionsanddatastructures.IntroducedinGo1.18,theyreducecodeduplicationbyallowingfunctionslikefuncMax[Tcomparable](a,bT)Ttoworkacrossmultipletypeswhileenforcingconstraints.Typeparametersinsquarebrackets,suchas[Tcom

See all articles