How to read command line arguments in Go
Jul 10, 2025 am 11:55 AMReading command line parameters in a Go program can be achieved through the os.Args and flag packages. 1. Use os.Args to directly obtain all parameters, the first element is the program path, which is subsequently input for the user, and the program name can be skipped through os.Args[1:]; 2. For structured parameters such as -name=value, the flag package should be used, which supports binding variables, default values ??and help information. Flag.Parse() should be called to parse and access the value through pointers; 3. When processing subcommands, the value of os.Args[1] can be manually judged and different logic is executed. It is recommended to use the cobra library for complex CLI; 4. In either way, the number of parameters should be checked to avoid panic.
It is actually not difficult to read command line parameters in Go programs, and os
package in the standard library can meet basic needs. If you just want to quickly get the parameters passed in during runtime, just use os.Args
.

Use os.Args to get parameters
Go's standard library os
provides a variable Args
, which is a string slice that contains all command line parameters passed in when starting the program. The first element is the path of the program itself, and the following is the parameters you pass.
For example:

package main import ( "fmt" "os" ) func main() { args := os.Args fmt.Println("all parameters:", args) }
Run this program and pass the parameters:
go run main.go foo bar
The output will be:

All parameters: [/tmp/go-build.../exe/main foo bar]
You can see that the first parameter is the program path, followed by the content you entered. If only the parameters passed by the user are required, you can use os.Args[1:]
to skip the program name.
Use flag package to parse the tagged parameters
If you need to deal with structured command line parameters like -name=value
or --verbose
, it is recommended to use flag
package. It supports functions such as binding variables, setting default values, and automatically printing help information.
The basic usage is as follows:
package main import ( "flag" "fmt" ) func main() { name := flag.String("name", "world", "please enter a name") verbose := flag.Bool("verbose", false, "whether to output detailed information") flag.Parse() if *verbose { fmt.Println("Detailed mode is enabled") } fmt.Printf("Hello, %s!\n", *name) }
Operation mode:
go run main.go -name=Alice -verbose=true
Output:
Hello, Alice is enabled in detailed mode!
-
flag.String
creates a string type parameter, and the third parameter is description (help message) -
flag.Parse()
must be called to truly parse the parameters - Parameter values ??can be accessed through pointer dereferences, such as
*name
Note: The flag package only supports
-
starting parameters, not--
. If you have more complex needs, such as supporting double horizontal lines or subcommands, you can consider third-party libraries such aspflag
orkingpin
.
Process subcommands (such as git add/git commit)
Some tools have multiple subcommands, such as git add
and git commit
of Git. In this case, flag
package is not enough. You can manually determine which command os.Args[1]
is, and then do different processing.
Example:
package main import ( "fmt" "os" ) func main() { if len(os.Args) < 2 { fmt.Println("Please specify the command") Return } switch os.Args[1] { case "add": fmt.Println("Perform the add operation") case "commit": fmt.Println("Execute the commit operation") default: fmt.Println("Unknown Command") } }
This way, you can decide what logic to execute based on the first parameter. If you want to make more complex CLI tools, you can consider using libraries like cobra to organize command structures.
Basically that's it.
Use os.Args
for simple scenarios, use flag
for structured parameters, and use cobra for complex CLI.
What is not complicated but easy to ignore is: Don't forget to check the number of parameters, otherwise it will be easy to panic.
The above is the detailed content of How to read command line arguments in Go. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

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

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)

Go's switch statement will not be executed throughout the process by default and will automatically exit after matching the first condition. 1. Switch starts with a keyword and can carry one or no value; 2. Case matches from top to bottom in order, only the first match is run; 3. Multiple conditions can be listed by commas to match the same case; 4. There is no need to manually add break, but can be forced through; 5.default is used for unmatched cases, usually placed at the end.

AruneinGoisaUnicodecodepointrepresentedasanint32,usedtocorrectlyhandleinternationalcharacters;1.Userunesinsteadofbytestoavoidsplittingmulti-byteUnicodecharacters;2.Loopoverstringswithrangetogetrunes,notbytes;3.Convertastringto[]runetosafelymanipulate

The answer is: Go applications do not have a mandatory project layout, but the community generally adopts a standard structure to improve maintainability and scalability. 1.cmd/ stores the program entrance, each subdirectory corresponds to an executable file, such as cmd/myapp/main.go; 2.internal/ stores private code, cannot be imported by external modules, and is used to encapsulate business logic and services; 3.pkg/ stores publicly reusable libraries for importing other projects; 4.api/ optionally stores OpenAPI, Protobuf and other API definition files; 5.config/, scripts/, and web/ store configuration files, scripts and web resources respectively; 6. The root directory contains go.mod and go.sum

Using bufio.Scanner is the most common and efficient method in Go to read files line by line, and is suitable for handling scenarios such as large files, log parsing or configuration files. 1. Open the file using os.Open and make sure to close the file via deferfile.Close(). 2. Create a scanner instance through bufio.NewScanner. 3. Call scanner.Scan() in the for loop to read line by line until false is returned to indicate that the end of the file is reached or an error occurs. 4. Use scanner.Text() to get the current line content (excluding newline characters). 5. Check scanner.Err() after the loop is over to catch possible read errors. This method has memory effect

Routing in Go applications depends on project complexity. 1. The standard library net/httpServeMux is suitable for simple applications, without external dependencies and is lightweight, but does not support URL parameters and advanced matching; 2. Third-party routers such as Chi provide middleware, path parameters and nested routing, which is suitable for modular design; 3. Gin has excellent performance, built-in JSON processing and rich functions, which is suitable for APIs and microservices. It should be selected based on whether flexibility, performance or functional integration is required. Small projects use standard libraries, medium and large projects recommend Chi or Gin, and finally achieve smooth expansion from simple to complex.

To import local packages correctly, you need to use the Go module and follow the principle of matching directory structure with import paths. 1. Use gomodinit to initialize the module, such as gomodinitexample.com/myproject; 2. Place the local package in a subdirectory, such as mypkg/utils.go, and the package is declared as packagemypkg; 3. Import it in main.go through the full module path, such as import "example.com/myproject/mypkg"; 4. Avoid relative import, path mismatch or naming conflicts; 5. Use replace directive for packages outside the module. Just make sure the module is initialized

BuildconstraintsinGoarecommentslike//go:buildthatcontrolfileinclusionduringcompilationbasedonconditionssuchasOS,architecture,orcustomtags.2.TheyareplacedbeforethepackagedeclarationwithablanklineinbetweenandsupportBooleanoperatorslike&&,||,and

Go's flag package can easily parse command line parameters. 1. Use flag.Type() to define type flags such as strings, integers, and booleans; 2. You can parse flags to variables through flag.TypeVar() to avoid pointer operations; 3. After calling flag.Parse(), use flag.Args() to obtain subsequent positional parameters; 4. Implementing the flag.Value interface can support custom types to meet most simple CLI requirements. Complex scenarios can be replaced by spf13/cobra library.
