Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most concise way of passing named arguments to a Golang tool and to use them?

Aim: to pass named arguments to a Golang tool and to use the passed arguments as variables


Attempt

Compiling the following example:

package main

import (
  "fmt"
  "os"
)

func main() {
  argsWithProg := os.Args
  argsWithoutProg := os.Args[1:]
  arg := os.Args[3]

  fmt.Println(argsWithProg)
  fmt.Println(argsWithoutProg)
  fmt.Println(arg)
}

build it and pass arguments, e.g.: ./args -a=1 -b=2 -c=3 -d=4 -e=5 -f=6, results in:

[./args -a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
[-a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
-c=3

Based on this answer, the following snippet was added to the example:

s := strings.Split(arg, "=")
variable, value := s[0], s[1]
fmt.Println(variable, value)

and after building it and passing arguments the output is as follows:

[./args -a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
[-a=1 -b=2 -c=3 -d=4 -e=5 -f=6]
-c=3
-c 3

Question

Although the aim has been accomplished I wonder whether this is the most concise way to pass named arguments and to use them in Golang.

like image 676
030 Avatar asked Nov 05 '25 11:11

030


1 Answers

Package flag

import "flag" 

Package flag implements command-line flag parsing.

Try the flag and other similar packages.

like image 62
peterSO Avatar answered Nov 07 '25 01:11

peterSO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!