SoFunction
Updated on 2025-03-05

A brief talk about the specific use of Flag packages in Golang

introduce

flagPackage is a package in the Go language standard library that parses command line parameters. It provides a convenient way to define and parse command line parameters, making developing command line tools and applications simpler and more flexible.

flagThe main functions of the package include:

  • Define the type and default values ​​of command line parameters
  • Parses command line parameters and assigns them to the corresponding variable
  • Provide help information and usage instructions

Simple example

Here is an example, suppose we are writing a simple command line tool that calculates the sum of two integers. We can useflagPackage to define and parse command line parameters.

package main

import (
	"flag"
	"fmt"
)

func main() {
	// Define command line parameters	num1 := ("num1", 0, "First integer")
	num2 := ("num2", 0, "Second integer")

	// parse command line parameters	()

	// Calculate and	sum := *num1 + *num2

	// Output result	("and:", sum)
}

In the example above, we first useThe function defines two command line parametersnum1andnum2, respectively represent two integers. The default value for these parameters is 0, and the third parameter is the description used for help information.

Next, we call()Functions to parse command line parameters. It will look for defined parameters in the command line and assign the corresponding value to the corresponding variable.

Finally, we add two integers and output the result.

Now we can run the program on the command line and specify command line parameters:

$ go run -num1=10 -num2=20
and: 30

The above example demonstrates how to use itflagPackages define and parse command line parameters, allowing us to flexibly control program behavior through the command line. We can passflagPackage further develops its own command line tools and applications.

flagThe package also supports the following commonly used command line parameter types:

1. Boolean type (bool):

  • usage:(name string, value bool, usage string) *bool
  • Example:verbose := ("verbose", false, "Show details")
  • Description: Boolean type command line arguments are used to indicate whether an option is on or off. If this option is specified on the command line, the corresponding Boolean variable will be set totrue, otherwisefalse

2. Integer type (int):

  • usage:(name string, value int, usage string) *int
  • Example:count := ("count", 0, "Retry times")
  • Description: Command line parameters of integer type are used to represent integer values. The integer value specified through the command line will be parsed and assigned to the corresponding integer variable.

3. String type (string):

  • usage:(name string, value string, usage string) *string
  • Example:name := ("name", "", "name")
  • Description: The command line argument of the string type is used to represent a text string. The string value specified in the command line will be parsed and assigned to the corresponding string variable.

4. Floating point number type (float64):

  • usage:flag.Float64(name string, value float64, usage string) *float64
  • Example:price := flag.Float64("price", 0.0, "price")
  • Description: Command line parameters of type floating point number are used to represent floating point values. The floating point value specified in the command line will be parsed and assigned to the corresponding floating point variable.

5. Other types:

  • Int64UintUint64: Similar to integer types, but supports larger integer ranges.
  • Duration: The type used to represent a time period, which can parse a string containing time units, such as"10s""1h30m"
  • IPIPMask: The type used to represent the IP address and IP subnet mask.
  • Var: Command line parameters for custom types, need to be implementedinterface.

By using these different types of command line parameters, the needs of various types of data can be met, andflagPackages provide easy-to-use ways to parse and process these command line parameters.

Here is an example showingflagCommonly used command line parameter types in the package:

package main

import (
	"flag"
	"fmt"
)

func main() {
	// Define command line parameters	verbose := ("verbose", false, "Show details")
	count := ("count", 0, "Retry times")
	name := ("name", "", "Name")
	price := flag.Float64("price", 0.0, "price")

	// parse command line parameters	()

	// Output the parsed command line parameters	("Verbose:", *verbose)
	("Count:", *count)
	("Name:", *name)
	("Price:", *price)
}

In the above example, we define four different types of command line parameters:

  • verboseis a Boolean parameter that indicates whether details are displayed.
  • countis an integer type parameter used to represent the number of retryes.
  • nameis a string type parameter used to represent a name.
  • priceis a floating point parameter that represents the price.

By usingandflag.Float64Functions, we define these different types of command line parameters and specify names, default values, and help information for each parameter.

Next, we call()Functions to parse command line parameters. Then, we use pointer dereference to get the value of each command line parameter and print it out.

Now we can run the program in the command line and specify different command line parameters:

$ go run -verbose -count=3 -name=John -price=9.99
Verbose: true
Count: 3
Name: John
Price: 9.99

By modifying the value of the command line parameter, you can try different types of parameters and observe the output results.

Var Form

flagNot only supports direct type formal parsing, but also supports direct parsing overlay values ​​to parse command line data, such asBoolVar

Example

package main

import (
	"flag"
	"fmt"
)

func main() {
	// Define command line parameters	var verbose bool
	(&verbose, "verbose", false, "Show details")

	var count int
	(&count, "count", 0, "Retry times")

	// parse command line parameters	()

	// Output the parsed command line parameters	("Verbose:", verbose)
	("Count:", count)
}

In the above example, we useBoolVarandIntVarThe function creates command-line parameters of boolean and integer types.

BoolVarFunctions are used to create a Boolean command line parameter and store the parsed value in the corresponding Boolean variable. Its parameters include a pointer to a Boolean variable, the name of the command line parameter, the default value of the command line parameter, and a brief description of the command line parameter.

IntVarFunctions are used to create a command line parameter of integer type and store the parsed value in the corresponding integer variable. Its parameters include a pointer to an integer variable, the name of the command line parameter, the default value of the command line parameter, and a brief description of the command line parameter.

By calling()Functions, we can parse command line parameters and assign them to the corresponding variable.

Here is an example of running the program on the command line and specifying different command line parameters:

$ go run -verbose -count=3
Verbose: true
Count: 3

By modifying the value of the command line parameter, you can try different boolean and integer values ​​and observe the output. This will help you better understand and useflagIn the packageBoolVarandIntVarfunction.

Custom type resolution

is a function in the flag package for command line arguments for custom types. By implementing the interface, we can create our own types and use them in command line parameters.

interface:

type Value interface {
	String() string
	Set(string) error
}

Here is an example showing how to use the command line parameters to create custom types:

yesflagFunctions in the package for custom type command line parameters. By implementingInterface, we can create our own types and use them in command line parameters.

package main

import (
	"flag"
	"fmt"
	"strconv"
)

// CustomType is a custom typetype CustomType int

// String returns the string representation of CustomTypefunc (c CustomType) String() string {
	return (int(c))
}

// Set parses command line parameters and sets the value of CustomTypefunc (c *CustomType) Set(value string) error {
	// Here you can parse and process custom types	// Here we simply convert the command line parameters into integers and assign values ​​to CustomType	num, err := (value)
	if err != nil {
		return err
	}
	*c = CustomType(num)
	return nil
}

func main() {
	// Define command line parameters	var custom CustomType
	(&custom, "custom", "Custom Parameters")

	// parse command line parameters	()

	// Output the parsed command line parameters	("Custom:", custom)
}

In the example above, we define a name calledCustomTypeCustom types and implementTwo methods of interface:StringandSet

StringMethods are used to return custom typesCustomTypeThe string representation of , here we convert it to an integer type string.

SetMethods are used to parse command line parameters and set custom typesCustomTypevalue. In this example, we convert the command line argument to an integer and assign it toCustomTypevariable.

Next, we useFunction registers command line parameters of custom types. By passing in oneWe tell the pointer of the interface variableflagHow should a package parse and process command line parameters of this type?

Finally, we call()Functions to parse command line parameters. After the parsing is completed, we can directly access the variable of the custom type to get the parsed value and print it out.

Now we can run the program on the command line and specify command line parameters of the custom type:

$ go run -custom=42
Custom: 42

Of course, if you just want to get command line parameters, you don't need toflagPacked,It can be solved:

is a string slice that is used to access command line parameters. It stores all command line parameters passed to the program when the program starts, including the program name itself.

Here is an example showing how to use itTo get and traverse command line parameters:

package main

import (
	"fmt"
	"os"
)

func main() {
	// Get command line parameters	args := 

	// traverse command line parameters	for index, arg := range args {
		("Parameter %d: %s\\n", index, arg)
	}
}

In the above example, we useGet all command line parameters and store them inargsin variable.

Then, we userangeLoop traversalargsSlice to get the index and value of each command line parameter. pass%dand%sPlaceholder, we print out the index and value of the parameter.

Now we can run the program in the command line and specify different command line parameters:

$ go run arg1 arg2 arg3
Parameter 0:
Parameter 1: arg1
Parameter 2: arg2
Parameter 3: arg3

In the example above,is the name of the program.arg1arg2andarg3is a custom command line parameter passed to the program by the user. Through traversalSlice, we can get and process these command line parameters.

useCommand line parameters can be accessed and processed to perform corresponding logical operations according to the needs of the program.

The above is a brief discussion on the detailed use of the Flag package in Golang. For more information about the Golang Flag package, please follow my other related articles!