程序入口
- 必须有
main包,即package main; - 必须有
main方法,即func main(){...}; - 文件名不一定是
main.go。
第一个程序helloworld.go
package mainimport ("fmt""os")func main() {fmt.Println("hello world.")os.Exit(0)}
程序退出返回值,通过
os.Exit(0)指定。
执行go run helloworld.go,即打印出hello world.。
获取命令行参数
package mainimport ("fmt""os")func main() {if len(os.Args) >= 2 {fmt.Println("hello ", os.Args[1])os.Exit(0)} else {fmt.Println("hello world.")os.Exit(1)}}
os.Args是参数列表,通过os.Args[1] 获取命令行传入的第2个参数,第1个参数是程序本身。
测试程序
测试程序源码文件以_test.go结尾,像 xxx_test.go。
测试方法以Test开头,像 func Testxxx(t *testing.T) {...}。
package testimport "testing"const (Excutable = 1 << iotaWriteableReadable)func TestClear(t *testing.T) {// 清零操作符,当右边为1时,结果为0;否则原样输出t.Log(1 &^ 1)t.Log(1 &^ 0)t.Log(0 &^ 1)t.Log(0 &^ 0)}func TestBitClear(t *testing.T) {t.Log("test start")stats := 7stats = stats &^ 0t.Log(stats&Excutable == Excutable, stats&Writeable == Writeable, stats&Readable == Readable)}
测试方法
go test -v bitclear_test.go=== RUN TestClearTestClear: a_test.go:11: 0TestClear: a_test.go:12: 1TestClear: a_test.go:13: 0TestClear: a_test.go:14: 0--- PASS: TestClear (0.00s)=== RUN TestBitClearTestBitClear: a_test.go:18: test startTestBitClear: a_test.go:21: true true true--- PASS: TestBitClear (0.00s)PASSok test-go/gotest/0729/testx 0.597s
在vscode中,针对测试程序会单独在函数上面一行生成测试运行按钮,方便测试。
在命令行执行go test -v first_test.go 也可以进行测试。
