Go简介
Go是Google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的编程语言。因其天生并发、编译后的二进制文件可以直接移植运行,这使得其与Docker相结合可以创建完美的微服务。
编程风格
Go有几项强制性的编程规定,可以帮助程序员强制养成书写可阅读的代码和减少程序中的bug(C语言中忘记(;)是最广泛的bug)
- 每行程序结束后不需要撰写分号(;)。
- 大括号({)不能够换行放置。
- if判断式和for循环不需要以小括号包覆起来。
代码组织
Go的代码组织结构如下,Go与其他语言代码组织不同的是Go内置使用Git进行版本控制,在编写库文件时可以直接放在自己的Github上,然后供自己和其他人下载使用。
$GOPATH
├─── bin/ # 放置 go install 生成的可执行文件
| └─── hello
├─── pkg/ # 放置 go install 生成的库对象文件
| └─── linux_amd64/github.com/
| ├─── gorilla/mux/
| | └─── mux.a
| └─── lucky-loki/rect/
| └─── rect.a
└─── src/ # 放置库文件
└─── github.com
├─── gorilla/mux/ # 外部 Git 库
| ├─── .git/
| ├─── mux.go
| └─── ...
└─── lucky-loki/ # 工作区
├─── hello/
| └─── hello.go # 主程序
└─── rect/
├─── rect.go # 自己编写的库文件
└─── rect_test.go # 自己编写的单元测试文件
示例
编写你的第一个库
mkdir -p $GOPATH/src/github.com/lucky-loki/rect
cd $GOPATH/src/github.com/lucky-loki/rect
vim rect.go
package rect
import "fmt"
type rect struct {
width int
height int
}
func (r *rect) area() int {
return r.width * r.height
}
func Print() bool{
r := rect{ width:10, height:5}
fmt.Printf("area: %d\n", r.area())
return true
}
# 单元测试*_test.go
vim rect_test.go
package rect
import (
"fmt"
"testing"
)
// 测试函数模版 func TestXXX(t *testing.T), 测试失败使用t.Error或者t.Fail
func TestRect(t *testing.T) {
fmt.Println("In test rect")
ret := Print()
if ret != true {
t.Errorf("one error happened")
}
}
-
go build
不会产生输出文件,它会将编译后的包放在本地编译缓存中。 -
go install
会将编译后的包放在pkg
文件夹中。
# 编译库文件,成功后进行单元测试
cd $GOPATH/src/github.com/lucky-loki/rect
go build && go test
# 或者
go build github.com/lucky-loki/rect
go test github.com/lucky-loki/rect
编写主程序
mkdir -p $GOPATH/src/github.com/lucky-loki/hello
cd $GOPATH/src/github.com/lucky-loki/hello
vim hello.go
- 主程序必须使用
package main
作为包名。 -
import "<package>"
会在$GOROOT/src
和$GOPATH/src
下进行包查找。
package main
import (
"fmt"
"github.com/lucky-loki/rect"
)
func main() {
fmt.Print("Hello World!")
rect.Print()
}
# 编译主程序,运行
cd $GOPATH/src/github.com/lucky-loki/hello
go build && ./hello
# 或者
go build github.com/lucky-loki/hello && ./hello
go install github.com/lucky-loki/hello && $GOPATH/bin/hello
发布你的库
cd $GOPATH/src/github.com/lucky-loki/rect
git init
git add rect.go rect_test.go
git commit -m "initial commit"
git remote add origin https://github.com/lucky-loki/rect.git
git push -u origin master
下载远程库
go get
会先将远程库下载存储到$GOPATH/src
下,然后执行go install
进行库编译生成对象文件放在$GOPATH/pkg
下或者执行主程序编译放在$GOPATH/bin
下。
go get github.com/gorilla/mux
# 如何导入
# import "github.com/gorilla/mux"
网友评论