全文来自How to Write Go Code 自己跟着写了一遍,并记录了其中的过程。
go官方文档
go的github地址
go下载安装地址
go命令文档地址
一,创建go.mod
$ mkdir hello
$ cd hello
$ go mod init example.com/user/hello
hello.go
package main
import "fmt"
func main() {
fmt.Println("Hello, world.")
}
写完后,安装构建go语言:
go install example.com/user/hello
构建的程序在$HOME/go/bin/
这个目录下,如果要修改这个目录,更改GOPATH=XXX
环境变量就可以
如果在你的代码目录下面,这三个命令代表的意义一样
$ go install example.com/user/hello
$ go install .
$ go install
//初始化go项目到git
$ git init
$ git add go.mod hello.go
$ git commit -m "initial commit"
二,如何导入本地其他的模块,构成一个整体项目
vim $HOME/hello/morestrings/reverse.go // 创建morestrings文件夹并创建reverse.go文件
// 内容如下
// 1.注意函数名称是大写开头,这样就意思是可以被导出,并可以被其他的文件导入
func ReverseRunes(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)
}
$ cd $HOME/hello/morestrings
$ go build // 这样构建reverse.go会被保存在本地缓存中
在hello.go中使用reverse.go包函数
package main
import (
"fmt"
"example.com/user/hello/morestrings"
)
func main() {
fmt.Println(morestrings.ReverseRunes("!oG ,olleH"))
}
// 从新构建并执行
$ go install example.com/user/hello
$ hello
二,如何导入远程的模块,构成一个整体项目
package main
import (
"fmt"
"example.com/user/hello/morestrings"
"github.com/google/go-cmp/cmp"
)
func main() {
fmt.Println(morestrings.ReverseRunes("!oG ,olleH"))
fmt.Println(cmp.Diff("Hello World", "Hello Go"))
}
$ go install example.com/user/hello
// 执行失败解决办法如下
https://shockerli.net/post/go-get-golang-org-x-solution/
最后是清理工程下不需要的文件依赖啦
$ go clean -modcache
整体创建一个go项目的流程已经跑完了。最后就是测试部分,测试也是很重要的。
vim $HOME/hello/morestrings/reverse_test.go
package morestrings
import "testing"
func TestReverseRunes(t *testing.T) {
cases := []struct {
in, want string
}{
{"Hello, world", "dlrow ,olleH"},
{"Hello, 世界", "界世 ,olleH"},
{"", ""},
}
for _, c := range cases {
got := ReverseRunes(c.in)
if got != c.want {
t.Errorf("ReverseRunes(%q) == %q, want %q", c.in, got, c.want)
}
}
}
$ go test
PASS
ok example.com/user/morestrings 0.165s