程序入口

  • 必须有main包,即 package main
  • 必须有main方法,即func main(){...}
  • 文件名不一定是main.go

第一个程序helloworld.go

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. fmt.Println("hello world.")
  8. os.Exit(0)
  9. }

程序退出返回值,通过os.Exit(0)指定。

执行go run helloworld.go,即打印出hello world.

获取命令行参数

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func main() {
  7. if len(os.Args) >= 2 {
  8. fmt.Println("hello ", os.Args[1])
  9. os.Exit(0)
  10. } else {
  11. fmt.Println("hello world.")
  12. os.Exit(1)
  13. }
  14. }

os.Args是参数列表,通过os.Args[1] 获取命令行传入的第2个参数,第1个参数是程序本身。

测试程序

测试程序源码文件以_test.go结尾,像 xxx_test.go
测试方法以Test开头,像 func Testxxx(t *testing.T) {...}

  1. package test
  2. import "testing"
  3. const (
  4. Excutable = 1 << iota
  5. Writeable
  6. Readable
  7. )
  8. func TestClear(t *testing.T) {
  9. // 清零操作符,当右边为1时,结果为0;否则原样输出
  10. t.Log(1 &^ 1)
  11. t.Log(1 &^ 0)
  12. t.Log(0 &^ 1)
  13. t.Log(0 &^ 0)
  14. }
  15. func TestBitClear(t *testing.T) {
  16. t.Log("test start")
  17. stats := 7
  18. stats = stats &^ 0
  19. t.Log(stats&Excutable == Excutable, stats&Writeable == Writeable, stats&Readable == Readable)
  20. }

测试方法

  1. go test -v bitclear_test.go
  2. === RUN TestClear
  3. TestClear: a_test.go:11: 0
  4. TestClear: a_test.go:12: 1
  5. TestClear: a_test.go:13: 0
  6. TestClear: a_test.go:14: 0
  7. --- PASS: TestClear (0.00s)
  8. === RUN TestBitClear
  9. TestBitClear: a_test.go:18: test start
  10. TestBitClear: a_test.go:21: true true true
  11. --- PASS: TestBitClear (0.00s)
  12. PASS
  13. ok test-go/gotest/0729/testx 0.597s

vscode中,针对测试程序会单独在函数上面一行生成测试运行按钮,方便测试。
在命令行执行go test -v first_test.go 也可以进行测试。