Command-Line Arguments in Go

Go: Command-Line Arguments

Go provides a simple way to access command-line arguments using the os package.

Get the value of a command-line argument

Here's an example of how to get the value of a command-line argument:

    package main

    import (
        "fmt"
        "os"
    )

    func main() {
        args := os.Args
        if len(args) < 2 {
            fmt.Println("Please provide a name as an argument")
            return
        }
        name := args[1]
        fmt.Printf("Hello, %s!\n", name)
    }

This code uses the os.Args variable to get the command-line arguments passed to the program. If the length of the arguments slice is less than 2 (meaning no arguments were provided), the program prints a message asking the user to provide a name as an argument. Otherwise, it uses the first argument as the name and prints a personalized greeting.

Parse command-line flags

You can also use the flag package to parse command-line flags and options. Here's an example of how to use flag to parse a -name flag:

    package main

    import (
        "flag"
        "fmt"
    )

    func main() {
        name := flag.String("name", "", "a name to greet")
        flag.Parse()
        if *name == "" {
            fmt.Println("Please provide a name using the -name flag")
            return
        }
        fmt.Printf("Hello, %s!\n", *name)
    }

This code defines a name variable as a string flag using the flag.Stringfunction. It then calls flag.Parse to parse the command-line arguments and set the value of the name variable. If the flag is not provided, the program prints a message asking the user to provide a name using the -name flag. Otherwise, it uses the value of the flag as the name and prints a personalized greeting.

I hope that helps you get started with working with command-line arguments in Go! Let me know if you have any more questions.

Previous Article

Next Article