從另一個模組呼叫您的程式碼
在上一節中,您建立了一個greetings
模組。在本節中,您將編寫程式碼來呼叫您剛剛編寫的模組中的Hello
函式。您將編寫可以作為應用程式執行的程式碼,該程式碼呼叫greetings
模組中的程式碼。
- 為您的 Go 模組原始碼建立一個
hello
目錄。您將在其中編寫呼叫方。建立此目錄後,您的目錄結構中應該有同級的 hello 和 greetings 目錄,如下所示:
<home>/ |-- greetings/ |-- hello/
例如,如果您的命令提示符位於 greetings 目錄中,您可以使用以下命令:
cd .. mkdir hello cd hello
- 為即將編寫的程式碼啟用依賴項跟蹤。
要為您的程式碼啟用依賴項跟蹤,請執行
go mod init
命令,並提供您的程式碼所屬模組的名稱。在本教程中,請使用
example.com/hello
作為模組路徑。$ go mod init example.com/hello go: creating new go.mod: module example.com/hello
- 在您的文字編輯器中,在 hello 目錄中建立一個檔案來編寫程式碼,並將其命名為 hello.go。
- 編寫程式碼以呼叫
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/greetings
和fmt
包。這使您的程式碼可以訪問這些包中的函式。匯入example.com/greetings
(您之前建立的模組中包含的包)可以訪問Hello
函式。您還匯入了fmt
,它包含處理輸入和輸出文字(如將文字列印到控制檯)的函式。 - 透過呼叫
greetings
包的Hello
函式來獲取問候語。
- 宣告一個
- 編輯
example.com/hello
模組以使用您本地的example.com/greetings
模組。對於生產環境,您將從其儲存庫釋出
example.com/greetings
模組(使用反映其釋出位置的模組路徑),Go 工具可以從中下載它。目前,由於您尚未釋出該模組,因此需要調整example.com/hello
模組,以便它可以找到您本地檔案系統上的example.com/greetings
程式碼。為此,請使用
go mod edit
命令編輯example.com/hello
模組,將 Go 工具從其模組路徑(模組不存在的位置)重定向到本地目錄(模組所在的位置)。- 在 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
- 在 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
有關版本號的更多資訊,請參閱 模組版本編號。
- 在 hello 目錄的命令提示符下,執行以下命令:
- 在
hello
目錄的命令提示符下,執行您的程式碼以確認它正常工作。$ go run . Hi, Gladys. Welcome!
恭喜!您已經編寫了兩個功能模組。
在下一節中,您將新增一些錯誤處理。