SoFunction
Updated on 2025-03-05

Golang flag introduction and use examples

In Go,flagPackages are used to parse command line flags. It provides an easy way to handle the program's input parameters. The following is correctflagIntroduction and usage examples of packages.

1. Basic concepts

  • Flag (Flag): Command line arguments, usually dashed-Start by controlling the behavior of the program.
  • Parse: Read and parse command line parameters.

2. Common functions

  • : Define a string flag.
  • : Define an integer flag.
  • : Define a boolean flag.
  • (): parse command line parameters.

3. Sample code

Here is a simple example that demonstrates how to use itflagBag:

package main
import (
    "flag"
    "fmt"
)
type Options struct {
    Name string
    Age  int
    DB   bool
}
func main() {
    // Create an Options structure instance    var option Options
    // Define the flag    (&, "name", "Guest", "User Name")
    (&, "age", 18, "User Age")
    (&, "db", false, "Initialize the database")
    // parse command line parameters    ()
    // Output parameters    ("Name: %s\n", )
    ("Age: %d\n", )
    ("DB initialized: %v\n", )
}

4. How to run

Assume the file name is, can be run from the command line:

go run  -name=John -age=30 -db

5. Output result

After running the above command, the output will be similar to:

Name: John
Age: 30
DB initialized: true

6. Help information

Can be added by-hor--helpParameters to view help information:

go run  -h

The output will display all defined flags and their descriptions.

7. Summary

  • flagPackages provide a convenient way to handle command line parameters.
  • useflagDifferent types of flags can be defined and these parameters can be used after parsing.
  • Remember to call()to parse command line parameters.

This is the article about the introduction and use of golang flags. For more related content on using golang flags, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!