业务代码被拆分为多个文件时,编译或运行就要带上那个文件(同包的情况);
如果需要调用其他包里的方法,需要先import进来
代码示例:
main.go文件
package main
import (
"fmt"
"os"
"strconv"
"time"
)
func main() {
num,_ := strconv.ParseInt(os.Args[1], 10, 16) // 将命令行参数的第一个参数转为int类型
if IsOdd(int(num)) {
fmt.Println("是奇数")
} else{
fmt.Println("是偶数")
}
// 死循环, 类似while(1)
count := 1 // 计数
for{
fmt.Printf("循环了 %d 次, 值到达20次停止.\n", count)
count++
time.Sleep(time.Second) // 每秒循环一次, 如果想2秒或更久, 可以n * time.Second
if count == 20{
break
}
}
}
unit.go文件
package main
// IsOdd 判断奇偶数
func IsOdd(num int) bool {
return num%2!=0
}
运行 go run main.go unit.go 【int参数】
编译 go build main.go unit.go
运行编译后的文件 main.exe 【int参数】
评论