博客
关于我
初学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/

    你可能感兴趣的文章
    php页面静态化技术;学习笔记
    查看>>
    php项目心得以及总结
    查看>>
    R&Python Data Science 系列:数据处理(4)长宽格式数据转换
    查看>>
    PHP项目集成支付宝PC端扫码支付API(国内支付)
    查看>>
    php预定义常量&变量
    查看>>
    R 集成算法③ 随机森林
    查看>>
    php验证码背景色设置无效
    查看>>
    php验证邮箱是否有效
    查看>>
    PHP高性能分布式应用服务器框架-SwooleDistributed
    查看>>
    PHP高效、轻量级表格数据处理库 OpenSpout
    查看>>
    R 数据缺失的处理
    查看>>
    php,nginx重启
    查看>>
    php:$_ENV 和 getenv区别
    查看>>
    PHP:cURL error 60: SSL certificate unable to get local issuer certificate
    查看>>
    PHP:PDOStatement::bindValue参数类型php5和php7问题
    查看>>
    Q媒体播放器.如何播放具有多个音频的视频?
    查看>>
    pickle
    查看>>
    Pickle thread.lock(Pymongo)
    查看>>
    pickle模块
    查看>>
    qYKVEtqdDg
    查看>>