從另一個模組呼叫您的程式碼

上一節 中,您建立了一個 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!
    

恭喜!您已撰寫兩個運作正常的模組。

在下一主題中,您將加入一些錯誤處理。