Go Flags
#Go
Fábio Miranda
Learning a new programming language is always exciting! Go is elegant and easy to learn. I simply executed the install staps and dove in the Hello World and the Modules Tutorial mentioned at the bottom of the page. The Go By Example is also being a rich resource.
My initial interest in Go was motivated by finding a good WebSocket programming API and I learned the standard lib is powerful and easy to use. This post shows how the flag package provides a clean syntax to parse command-line arguments.
Flag Calculator
A very basic calculator is implemented by the following code, where the arguments are passed to the program using some command-line arguments.
package main
import (
"fmt"
"flag"
)
func main() {
x := flag.Int("x", 1234, "Arg 1")
y := flag.Int("y", 8765, "Arg 2")
o := flag.String("o", "+", "One of +, -, *, /")
flag.Parse()
a, b, c := *x, *y, *o
fmt.Println("x:", a)
fmt.Println("y:", b)
fmt.Println("o:", c)
fmt.Println("tail:", flag.Args())
calculate := func(c string, a, b int) (int, string) {
switch c {
case "+":
return a + b, ""
case "-":
return a - b, ""
case "*":
return a * b, ""
case "/":
return a / b, ""
default:
return 0, fmt.Sprintf("[%v]", c)
}
}
output, err := calculate(c, a, b)
if err == "" {
msg := fmt.Sprintf("%d %v %d = %d", a, c, b, output)
fmt.Println(msg)
} else {
fmt.Println("Invalid Operand:", err)
}
}
Lets first run the program with --help
flag:
/app# go run . --help
Usage of /tmp/go-build621157370/b001/exe/app:
-o string
One of +, -, *, / (default "+")
-x int
Arg 1 (default 1234)
-y int
Arg 2 (default 8765)
exit status 2
In the absence of arguments, the default values are applied:
go run .
x: 1234
y: 8765
o: +
tail: []
9999
In the presence of arguments, the calculations uses the flag operands:
# go run . -x 20 -y 10 -o "+" Anything Else
x: 20
y: 10
o: +
tail: [Anything Else]
20 + 10 = 30
# go run . -x 20 -y 10 -o "-" Anything Else
x: 20
y: 10
o: -
tail: [Anything Else]
20 - 10 = 10
# go run . -x 20 -y 10 -o "*" Anything Else
x: 20
y: 10
o: *
tail: [Anything Else]
20 * 10 = 200
# go run . -x 20 -y 10 -o "/" Anything Else
x: 20
y: 10
o: /
tail: [Anything Else]
20 / 10 = 2
# go run . -x 20 -y 10 -o ":" Anything Else
x: 20
y: 10
o: :
tail: [Anything Else]
Invalid Operand: [:]