How to define and parse flags for file paths and directories in Go?

In Go, the flag package provides a simple way to define and parse command-line flags. Here's how you can define and parse flags for file paths and directories:

  1. Import the flag package:
import "flag"
  1. Define flags using the flag package. For file path or directory flags, you can use the flag.String function to define a string flag that accepts file paths or directories. Here's an example defining two flags for file paths and directories:
fileFlag := flag.String("file", "", "File path") dirFlag := flag.String("dir", "", "Directory path")

The first argument is the flag name, followed by the default value (an empty string in this case), and the usage string that describes the flag.

  1. Call the flag.Parse function to parse the defined flags. This function reads the command-line arguments and assigns the flag values accordingly. It must be called after all the flags have been defined.
flag.Parse()
  1. Access the flag values using the variable pointers you defined earlier. For example:
fmt.Println("File path:", *fileFlag) fmt.Println("Directory path:", *dirFlag)

The * operator is used to dereference the pointer and get the actual value.

Here's a complete example:

package main import ( "flag" "fmt" ) func main() { fileFlag := flag.String("file", "", "File path") dirFlag := flag.String("dir", "", "Directory path") flag.Parse() fmt.Println("File path:", *fileFlag) fmt.Println("Directory path:", *dirFlag) }

If you run this program with command-line flags like go run main.go -file /path/to/file -dir /path/to/dir, it will print the file and directory paths accordingly.

Keep in mind that the flag package also supports other types of flags (e.g., integers, booleans) and additional features like default values, shorthand notations, and custom value parsers. You can refer to the package documentation for more information: https://golang.org/pkg/flag/