程序入口
- 必须有
main
包,即package main
; - 必须有
main
方法,即func main(){...}
; - 文件名不一定是
main.go
。
第一个程序helloworld.go
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("hello world.")
os.Exit(0)
}
程序退出返回值,通过
os.Exit(0)
指定。
执行go run helloworld.go
,即打印出hello world.
。
获取命令行参数
package main
import (
"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 test
import "testing"
const (
Excutable = 1 << iota
Writeable
Readable
)
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 := 7
stats = stats &^ 0
t.Log(stats&Excutable == Excutable, stats&Writeable == Writeable, stats&Readable == Readable)
}
测试方法
go test -v bitclear_test.go
=== RUN TestClear
TestClear: a_test.go:11: 0
TestClear: a_test.go:12: 1
TestClear: a_test.go:13: 0
TestClear: a_test.go:14: 0
--- PASS: TestClear (0.00s)
=== RUN TestBitClear
TestBitClear: a_test.go:18: test start
TestBitClear: a_test.go:21: true true true
--- PASS: TestBitClear (0.00s)
PASS
ok test-go/gotest/0729/testx 0.597s
在vscode
中,针对测试程序会单独在函数上面一行生成测试运行按钮,方便测试。
在命令行执行go test -v first_test.go
也可以进行测试。