How to use default values for command-line flags in Go?

In Go, you can use the flag package to parse command-line arguments and provide default values for the flags. Here's how you can use default values for command-line flags in Go:

  1. Import the flag package:
import "flag"
  1. Define a variable for each command-line flag and assign a default value using the flag package. For example:
var someFlag = flag.String("flagname", "defaultvalue", "description")

In the above example:

  • flagname is the name of the flag.
  • defaultvalue is the default value for the flag.
  • description is an optional description for the flag.
  1. Call the flag.Parse() function to parse the command-line arguments and handle the default values. For example:
func main() { flag.Parse() // Rest of your code }
  1. Access the flag value in your program using the corresponding variable. For example:
func main() { flag.Parse() // Access the flag value fmt.Println("Flag Value:", *someFlag) }

That's it! Now, when you run your Go program without providing a value for a flag, it will use the default value defined in step 2.

Here's a complete example that demonstrates the usage of default values for command-line flags in Go:

package main import ( "flag" "fmt" ) var someFlag = flag.String("flagname", "defaultvalue", "description") func main() { flag.Parse() fmt.Println("Flag Value:", *someFlag) }

When you run this program without providing a value for the flagname flag, it will use the default value of defaultvalue.