R
R
Rodion Yurchenko2018-03-20 13:13:20
go
Rodion Yurchenko, 2018-03-20 13:13:20

How to pass named parameters from the command line to GOlang?

Good afternoon I'm studying
GO , I
ran into the problem that I can't transfer the parameters along with the keys
That is, they are transferred, but how to get them exactly by the name of the key - it doesn't work
Example:
my_prog.exe a=2 dump="hello"
well, in the program would like to work with args["a"] and get the value 2
argsWithProg := os.Args
log.Print("argsWithProg = ", argsWithProg)
log.Print("argsWithProg = ", argsWithProg[1]["dump"] )
Crashes with an error non-integer string index "dump"
help me figure it out

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2018-03-20
@aassdds

There is a flag package for this. It
can also generate default values ​​and generate usage.
In your case it will be like this:

package main

import (
  "flag"
  "fmt"
)

func main() {
  var a int
  var dump string

  flag.IntVar(&a, "a", 0, "The integer param")
  flag.StringVar(&dump, "dump", "default_dump", "The name of a dump")

  flag.Parse()

  fmt.Println("a:", a)
  fmt.Println("dump:", dump)
}

$ go run main.go -a=2 -dump="hello"
a: 2
dump: hello
$ go run main.go
a: 0
dump: default_dump
$ go run main.go -a=sdf
invalid value "sdf" for flag -a: strconv.ParseInt: parsing "sdf": invalid syntax
Usage of /tmp/go-build682528613/command-line-arguments/_obj/exe/main:
  -a int
        The integer param
  -dump string
        The name of a dump (default "default_dump")
exit status 2

R
RidgeA, 2018-03-20
@RidgeA

https://golang.org/pkg/flag/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question