golang 語言有一個GOPATH的概念就是當前工做目錄linux
[root@localhost golang_test]# tree . ├── bin │ └── hello ├── first.go ├── pkg ├── README.md ├── src │ └── github.com │ └── leleyao │ ├── hello │ │ └── hello.go │ ├── mymath │ │ └── mymath.go │ └── stringutil │ ├── reverse.go │ └── reverse_test.go └── statics └── timg.jpg [root@localhost golang_test]# tail -3 /etc/profile export GOPATH=/root/golang_test export PATH=$PATH:/go/bin export PATH=$PATH:$(go env GOPATH)/bin [root@localhost golang_test]# echo $GOPATH /root/golang_test [root@localhost golang_test]# echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/go/bin:/root/golang_test/bin:/root/bin
GOPATH的概念時代碼的起始目錄,當進行go install 或者代碼級別的 import 時 默認的包搜索路徑git
一般一個代碼 應該包含 src pkg bin 三個目錄再GOPATH 之下github
src 爲源碼路徑 golang
源碼有三個分類 bash
1.聲明爲package main 的包 測試
go run 可直接運行 [root@localhost hello]# go run hello.go 123 0 Hello, My lele yao ! [root@localhost hello]# cat hello.go package main import ( "fmt" . "github.com/leleyao/stringutil" ) var _lele int func main() { var _song int _song = 123 fmt.Println(_song) fmt.Println(_lele) fmt.Println(Reverse("! oay elel yM ,olleH")) } go build 會在當前目錄生成 同名二進制 [root@localhost hello]# pwd /root/golang_test/src/github.com/leleyao/hello [root@localhost hello]# go build github.com/leleyao/hello # 兩種指定方式 [root@localhost hello]# ls hello hello.go [root@localhost hello]# go build [root@localhost hello]# ls hello hello.go [root@localhost hello]# # go install [root@localhost hello]# ll $GOPATH/bin total 1952 -rwxr-xr-x. 1 root root 1997543 May 23 09:51 hello go install 會在 GOPATH bin 下 生成 同名二進制
2. 一個代碼目錄下有多個文件且有文件不是 沒有func main 則執行go install 會在對應目錄生編譯過程文件ui
ll /root/golang_test/pkg/linux_amd64/github.com/leleyao/stringutil.a -rw-r--r--. 1 root root 2902 May 23 13:07 /root/golang_test/pkg/linux_amd64/github.com/leleyao/stringutil.a [root@localhost stringutil]# rm -rf /root/golang_test/pkg/linux_amd64 [root@localhost stringutil]# cat reverse.go // Package stringutil contains utility functions for working with strings. package stringutil // Reverse returns its argument string reversed rune-wise left to right. func Reverse(s string) string { r := []rune(s) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return string(r) }
3. 以_test 結尾的文件會在執行 go test 命令時進行測試code
[root@localhost stringutil]# go test PASS ok github.com/leleyao/stringutil 0.003s [root@localhost stringutil]# ls reverse.go reverse_test.go