博客
关于我
初学Golang的笔记
阅读量:531 次
发布时间:2019-03-08

本文共 1701 字,大约阅读时间需要 5 分钟。

Golang 模块指南

模块的创建与初始化

一个 Go 模块是一个 Go 包的集合,用于发布和分发。通常情况下,一个 Go 仓库只包含一个模块,这个模块必须包含一个 go.mod 文件。

模块路径的重要性

模块路径不仅用于作为包的导入前缀,还帮助 go command 查找和下载模块。例如,导入 golang.org/x/tools 时,go command 会从 https://golang.org/x/tools 下载该模块。

初始化一个模块

要创建一个新的模块,可以按照以下步骤操作:

  • 创建一个目录:

    mkdir hellocd hello
  • 初始化模块:

    go mod init example.com/user/hello

    这将创建一个 go.mod 文件,内容如下:

    module example.com/user/hellogo 1.16
  • 编写 Go 源文件:

    package mainimport "fmt"func main() {    fmt.Println("Hello, world.")}
  • 构建并安装模块:

    go install example.com/user/hello

    这将编译模块并将二进制文件安装到 GOPATHGOBIN 目录中。

  • 模块依赖管理

    Go 提供了 go mod 命令来管理模块依赖。使用 go mod tidy 会下载所有引用但尚未下载的依赖,同时移除不必要的依赖。

    版本控制

    go.mod 文件中可以指定依赖的版本,确保依赖一致性。例如:

    require (    "fmt v1.0.0"    "example.com/user/hello/morestrings v1.2.3")

    测试模块

    Go 提供了 testing 包来编写单元测试。测试文件应以 _test.go 结尾,测试函数应命名为 Test*** 并带有 func(t *testing.T) 的签名。

    测试示例

    编写测试文件:

    package morestringsimport "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

    远程模块引用

    要引用远程模块,可以直接在 import 语句中使用 URL。例如,引用 github.com/google/go-cmp/cmp

    示例

    package mainimport (    "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/hellogo mod tidy

    模块管理命令

    获取模块信息

    go mod info example.com/user/hello

    移除模块缓存

    go clean -modcache

    通过以上指南,你可以轻松创建、管理和使用 Go 模块。

    转载地址:http://knyiz.baihongyu.com/

    你可能感兴趣的文章
    MySQL 内核深度优化
    查看>>
    mysql 内连接、自然连接、外连接的区别
    查看>>
    mysql 写入慢优化
    查看>>
    mysql 分组统计SQL语句
    查看>>
    Mysql 分页
    查看>>
    Mysql 分页语句 Limit原理
    查看>>
    MySQL 创建新用户及授予权限的完整流程
    查看>>
    mysql 创建表,不能包含关键字values 以及 表id自增问题
    查看>>
    mysql 删除日志文件详解
    查看>>
    mysql 判断表字段是否存在,然后修改
    查看>>
    mysql 协议的退出命令包及解析
    查看>>
    mysql 取表中分组之后最新一条数据 分组最新数据 分组取最新数据 分组数据 获取每个分类的最新数据
    查看>>
    mysql 多个表关联查询查询时间长的问题
    查看>>
    mySQL 多个表求多个count
    查看>>
    mysql 多字段删除重复数据,保留最小id数据
    查看>>
    MySQL 多表联合查询:UNION 和 JOIN 分析
    查看>>
    MySQL 大数据量快速插入方法和语句优化
    查看>>
    mysql 如何给SQL添加索引
    查看>>
    mysql 字段区分大小写
    查看>>
    mysql 字段合并问题(group_concat)
    查看>>