Go: golang get command line arguments

Trabla: Go: golang get command line arguments


Solving:

os.Args provides access to raw command-line arguments.

Example - demo1.go:

package main

import "os"
import "fmt"

func main() {

    
    allArguments := os.Args
    allExceptFirstArguments := os.Args[1:]

    // Concrete arg using index
    arg0 := os.Args[0] // Programm name
    arg1 := os.Args[1] 
    arg2 := os.Args[2]
    arg3 := os.Args[3]
    arg4 := os.Args[4]

    fmt.Println( allArguments)
    fmt.Println( allExceptFirstArguments )

    fmt.Println( arg0 )
    fmt.Println( arg1 )
    fmt.Println( arg2 )
    fmt.Println( arg3 )
    fmt.Println( arg4 )
}

Go golang get command line arguments tutorial screenshot 1

Build and run

Go golang get command line arguments tutorial screenshot 2

C:\Users\samuraikit>cd C:\Users\samuraikit\Desktop\gotest
C:\Users\samuraikit\Desktop\gotest>go build demo1.go
C:\Users\samuraikit\Desktop\gotest>demo1 Arg0 Arg1 Arg2 Arg3
[demo1 Arg0 Arg1 Arg2 Arg3]
[Arg0 Arg1 Arg2 Arg3]
demo1
Arg0
Arg1
Arg2
Arg3
C:\Users\samuraikit\Desktop\gotest>

Go golang get command line arguments tutorial screenshot 3



No comments:

Post a Comment