最后的效果大概是:
./calc add 1 2
Result 3
====================
./calc sub 1 2
Result -1
====================
./calc mul 10 20
Result 200
===================
./calc sqrt 2
Result 1.4142135623730951
2. flag 获取命令行参数
flag 包比 os 读取参数更方便。可以自定义传入的参数的类型:比如字符串,整型,浮点型,默认参数设置等
基本的使用方法如下:
var operate string
flag.StringVar(&operate,"o", "add", "operation for calc")
# 解释
绑定 operate 变量, name="o", value="add" , usage="operation for calc"
也可以这样定义为指针变量
var operate := flag.String("o", "add", "operation for calc")
同时还可以自定义 flag 类型
所有变量注册之后,调用 flag.Parse() 来解析命令行参数, 如果是绑定变量的方式,直接使用变量进行操作,
如果使用指针变量型,需要 *operate 这样使用。
flag.Args() 表示接收的所有命令行参数集, 也是一个切片
for index, value := range flag.Args {
fmt.Println(index, value)
}
func CalcByFlag() error {
var operation string
var numberone float64
var numbertwo float64
flag.StringVar(&operation, "o", "add", "operation for this tool")
flag.Float64Var(&numberone, "n1", 0, "The first number")
flag.Float64Var(&numbertwo, "n2", 0, "The second number")
flag.Parse()
fmt.Println(numberone, numbertwo)
if operation == "add" {
rt := numberone + numbertwo
fmt.Println("Result ", rt)
} else if operation == "sub" {
rt := numberone - numbertwo
fmt.Println("Result ", rt)
} else if operation == "mul" {
rt := numberone * numbertwo
fmt.Println("Result ", rt)
} else if operation == "sqrt" {
rt := math.Sqrt(numberone)
fmt.Println("Result ", rt)
} else {
help()
}
return nil
}
最后的结果效果如下:
./calc -o add -n1 1 -n2 2
Result 3
=============================
./calc -o sub -n1 2 -n2 3
Result -1
============================
./calc -o mul -n1 10 -n2 20
Result 200
===========================
./calc -o sqrt -n1 2
Result 1.4142135623730951
3. CLI 框架
cli 是一款业界比较流行的命令行框架。
所以你首先需要安装:
go get github.com/urfave/cli
# 一个简单的示例如下:
package main
import (
"fmt"
"os"
"github.com/urfave/cli"
)
func main() {
app := cli.NewApp()
app.Name = "boom"
app.Usage = "make an explosive entrance"
app.Action = func(c *cli.Context) error {
fmt.Println("boom! I say!")
return nil
}
app.Run(os.Args)
}
好,为实现 “简单数学计算” 的功能,我们应该怎么实现呢?
主要是 使用 框架中的 Flag 功能,对参数进行设置









