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

How Do I Access and Parse Command-Line Arguments in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-12-18 21:48:12892browse

How Do I Access and Parse Command-Line Arguments in Go?

Accessing Command-Line Arguments in Go

In Go, command-line arguments are available through the os.Args variable. This variable is a slice of strings containing the path to the executable and the arguments passed to it.

Syntax:

import "os"

func main() {
    fmt.Println(len(os.Args), os.Args)
}

Output:

3 [./myprogram arg1 arg2]

The first element of the slice, os.Args[0], is the path to the executable. The remaining elements, os.Args[1:], contain the arguments passed to the program.

Example Usage:

The following Go program reads and prints the command-line arguments passed to it:

package main

import (
    "fmt"
    "os"
)

func main() {
    for i, arg := range os.Args {
        fmt.Printf("%d: %s\n", i, arg)
    }
}

Using the Flag Package

The Go standard library also provides the flag package for parsing command-line flags. Flags can be defined and then used to parse the input arguments.

Syntax:

import "flag"

var myflag bool

func init() {
    flag.BoolVar(&myflag, "myflag", false, "Enable my flag")
}

func main() {
    flag.Parse()
}

By defining a flag named "myflag", the program can be called with the --myflag option to enable it.

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

Statement:
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