2.golang应用目录结构和GOPATH概念
golang 语言有一个GOPATH的概念就是当前工作目录
[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 时 默认的包搜索路径
通常一个代码 应该包含 src pkg bin 三个目录再GOPATH 之下
src 为源码路径
源码有三个分类
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 会在对应目录生编译过程文件
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 命令时进行测试
[root@localhost stringutil]# go test PASS ok github.com/leleyao/stringutil 0.003s [root@localhost stringutil]# ls reverse.go reverse_test.go
golang跨平台编译
CGO_ENABLE=0 GOOS=linux GOARCH=amd64 go build
跨平台编译是关闭C的依赖
GOOS 指定平台类型 linux window darwin
GOARCH 指定服务器架构 amd64 arm
本文来自博客园,作者:萱乐庆foreverlove,转载请注明原文链接:https://www.cnblogs.com/leleyao/p/10911342.html

浙公网安备 33010602011771号