项目目录结构
calcs.go源文件
package main
import (
"fmt"
"os"
"strconv"
"myapp/simplemath"
)
var Usage = func() {
fmt.Println("USAGE: calcs command [arguments] ...")
fmt.Println("\nThe commands are:\n\tadd\tAddition of two values.\n\tsqrt\tSquare root of a ono-negative value.")
}
func main() {
args := os.Args//接受命令行参数
if args == nil || len(args) < 3 {
Usage()
return
}
switch args[1] {
case "add":
if len(args) != 4{
fmt.Println("USAGE:calcs add <integer1> <interger2>")
return
}
v1,err1 := strconv.Atoi(args[2])
v2,err2 := strconv.Atoi(args[3])
if err1 != nil || err2 != nil {
fmt.Println("USAGE: calcs add <integer1> <integer2>")
return
}
ret := simplemath.Add(v1,v2)
fmt.Println("Result: ",ret)
case "sqrt":
if len(args) != 3 {
fmt.Println("USAGE: calcs sqrt <integer>")
}
v , err := strconv.Atoi(args[2])
if err != nil {
fmt.Println("USAGE: calcs sqrt <integer>")
return
}
ret := simplemath.Sqrt(v)
fmt.Println("Result: ",ret)
default:
Usage()
}
}
add.go源文件
package simplemath
func Add (a int,b int) int {
return a + b
}
add_test.go源文件,测试程序
package simplemath
import "testing"
func TestAdd(t *testing.T) {
r := Add(1,2)
if r != 3 {
t.Errorf("Add(1,2) failed. Got %d,expected 3.",r)
}
println(r)
}
sqrt.go源文件
package simplemath
import (
"math"
)
func Sqrt(i int) int {
v := math.Sqrt(float64(i))
return int(v)
}
sqrt_test.go源文件,测试程序
package simplemath
import "testing"
func TestSqrt(t *testing.T) {
v := Sqrt(16)
if v != 4 {
t.Errorf("Sqrt(16) failed. Got %v,expected 4.",v)
}
println(v)
}
然后编译calcs.go
测试结果
|
请发表评论