Home > Backend Development > Golang > How Do I Retrieve and Use Command-Line Arguments in Go?

How Do I Retrieve and Use Command-Line Arguments in Go?

Linda Hamilton
Release: 2024-12-13 14:43:17
Original
708 people have browsed it

How Do I Retrieve and Use Command-Line Arguments in Go?

Retrieving Command-Line Arguments in Go Programs

In Go, command-line arguments are not directly passed as parameters to the main function. To access them, the os.Args variable provides a slice of strings representing the arguments passed to the program.

Accessing Arguments with os.Args

The os.Args variable is available within the main function and holds the following information:

  • os.Args[0]: Program name
  • os.Args[1:]: Command-line arguments

Example:

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Program name:", os.Args[0])
    fmt.Println("Arguments:", os.Args[1:])
}
Copy after login

This program prints the name of the program and the command-line arguments passed to it.

Using the flag Package

Go also provides the flag package, which simplifies command-line argument parsing. The flag package allows you to define and parse flags, which are named parameters that can be set when the program is invoked.

Example:

package main

import (
    "flag"
    "fmt"
)

var name string

func init() {
    flag.StringVar(&name, "name", "Default name", "Set the program's name")
}

func main() {
    flag.Parse()
    fmt.Println("Hello", name)
}
Copy after login

In this example, the -name flag can be used to specify a name. The flag is parsed and assigned to the name variable in the init function.

The above is the detailed content of How Do I Retrieve and Use Command-Line Arguments in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template