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.String
function. 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
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go