How to define and parse floating-point number command-line flags in Go?

To define and parse floating-point number command-line flags in Go, you can make use of the flag package provided by the standard library. Here's an example code that demonstrates how to define and parse floating-point number flags:

package main import ( "flag" "fmt" ) func main() { // Define the floating-point number flag with a default value of 0.0 floatFlag := flag.Float64("floatFlag", 0.0, "floating-point number flag") // Parse the command-line flags flag.Parse() // Access the parsed value of the floating-point number flag fmt.Println("floatFlag:", *floatFlag) }

In the above code:

  1. We import the flag package and fmt package.
  2. We define a floatFlag variable using the flag.Float64 function. This function takes three arguments – the name of the flag, the default value, and a description of the flag.
  3. We call flag.Parse() to parse the command-line flags and set the values of the defined flag variables.
  4. We use *floatFlag to access the parsed value of the floating-point number flag and print it.

To run the program with a command-line argument, you can pass the flag using the -flagName syntax. For example:

$ go run main.go -floatFlag 3.14

This will output:

floatFlag: 3.14

If you don't provide a value for the flag, the default value (0.0 in this case) will be used.