从另一个模块调用您的代码

上一节中,您创建了一个greetings模块。在本节中,您将编写代码来调用您刚刚编写的模块中的Hello函数。您将编写可以作为应用程序执行的代码,该代码调用greetings模块中的代码。

  1. 为您的 Go 模块源代码创建一个hello目录。您将在其中编写调用方。

    创建此目录后,您的目录结构中应该有同级的 hello 和 greetings 目录,如下所示:

    <home>/
     |-- greetings/
     |-- hello/

    例如,如果您的命令提示符位于 greetings 目录中,您可以使用以下命令:

    cd ..
    mkdir hello
    cd hello
    
  2. 为即将编写的代码启用依赖项跟踪。

    要为您的代码启用依赖项跟踪,请运行go mod init命令,并提供您的代码所属模块的名称。

    在本教程中,请使用 example.com/hello 作为模块路径。

    $ go mod init example.com/hello
    go: creating new go.mod: module example.com/hello
    
  3. 在您的文本编辑器中,在 hello 目录中创建一个文件来编写代码,并将其命名为 hello.go。
  4. 编写代码以调用 Hello 函数,然后打印该函数的返回值。

    为此,请将以下代码粘贴到 hello.go 中。

    package main
    
    import (
        "fmt"
    
        "example.com/greetings"
    )
    
    func main() {
        // Get a greeting message and print it.
        message := greetings.Hello("Gladys")
        fmt.Println(message)
    }
    

    在此代码中,您

    • 声明一个 main 包。在 Go 中,作为应用程序执行的代码必须位于 main 包中。
    • 导入两个包:example.com/greetingsfmt。这使您的代码可以访问这些包中的函数。导入 example.com/greetings(您之前创建的模块中包含的包)可以访问 Hello 函数。您还导入了 fmt,它包含处理输入和输出文本(如将文本打印到控制台)的函数。
    • 通过调用 greetings 包的 Hello 函数来获取问候语。
  5. 编辑 example.com/hello 模块以使用您本地的 example.com/greetings 模块。

    对于生产环境,您将从其存储库发布 example.com/greetings 模块(使用反映其发布位置的模块路径),Go 工具可以从中下载它。目前,由于您尚未发布该模块,因此需要调整 example.com/hello 模块,以便它可以找到您本地文件系统上的 example.com/greetings 代码。

    为此,请使用go mod edit命令编辑 example.com/hello 模块,将 Go 工具从其模块路径(模块不存在的位置)重定向到本地目录(模块所在的位置)。

    1. 在 hello 目录的命令提示符下,运行以下命令:
      $ go mod edit -replace example.com/greetings=../greetings
      

      该命令指定 example.com/greetings 应被替换为 ../greetings,以便定位依赖项。运行命令后,hello 目录中的 go.mod 文件应包含一个 replace 指令

      module example.com/hello
      
      go 1.16
      
      replace example.com/greetings => ../greetings
      
    2. 在 hello 目录的命令提示符下,运行 go mod tidy 命令来同步 example.com/hello 模块的依赖项,添加代码所需的但尚未在模块中跟踪的依赖项。
      $ go mod tidy
      go: found example.com/greetings in example.com/greetings v0.0.0-00010101000000-000000000000
      

      命令完成后,example.com/hello 模块的 go.mod 文件应如下所示:

      module example.com/hello
      
      go 1.16
      
      replace example.com/greetings => ../greetings
      
      require example.com/greetings v0.0.0-00010101000000-000000000000

      该命令在 greetings 目录中找到了本地代码,然后添加了一个 require 指令来指定 example.com/hello 需要 example.com/greetings。您在 hello.go 中导入 greetings 包时创建了此依赖项。

      模块路径后面的数字是伪版本号 — 一个生成的数字,用于替代语义版本号(该模块尚不具备)。

      要引用一个已发布的模块,go.mod 文件通常会省略 replace 指令,并使用带有标记版本号的 require 指令。

      require example.com/greetings v1.1.0

      有关版本号的更多信息,请参阅 模块版本编号

  6. hello 目录的命令提示符下,运行您的代码以确认它正常工作。
    $ go run .
    Hi, Gladys. Welcome!
    

恭喜!您已经编写了两个功能模块。

在下一节中,您将添加一些错误处理。