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:
flag
package:import "flag"
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.flag.Parse()
function to parse the command-line arguments and handle the default values. For example:func main() {
flag.Parse()
// Rest of your code
}
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
.