Go - 第六章 | 調用模塊
簡要
在上一節中,建立了一個greetings模塊。在本節,你將寫程式碼調用Hello寫的模塊中的函數。你將寫可以為應用程序執行的程式碼,並在 greetings模塊中調用程式碼。
開始
建立一個
hello原始碼的目錄. 這是寫你呼叫程式碼的地方.- 例如,如果命令提示字元下的當前目錄是
greetings目錄,則可以使用以下命令:1
2
3cd ..
mkdir hello
cd hello
- 例如,如果命令提示字元下的當前目錄是
在你的編輯器(在
hello目錄),建立一個hello.go檔案用於寫你的程式碼寫一個調用
hello函數的程式碼,輸出函數回傳的值。- 為此,請將以下程式碼貼到
hello.go中。1
2
3
4
5
6
7
8
9
10
11
12
13package 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函數獲得問候。
From the command line at the hello directory, run the go mod init command, giving it the name of the module your code will be in (here, just use “hello”).
- 聲明
- 為此,請將以下程式碼貼到
為
hello包建立一個新的模塊。- 在
hello目錄的命令行中,運行go mod init指令,為其指定程式碼所在模塊的名稱(在這裡,只需使用“ hello”即可)。1
2$ go mod init hello
go: creating new go.mod: module hello
- 在
編輯
hello模塊以使用未發布的greetings模塊。對於正式環境,你可以將模塊發佈在公司內部或
Internet上的服務器上,然後Go命令將從那裡下載它們。現在,你需要調整調用者的模塊,以便它可以在本地文件系統上找到問候語程式碼。為此,請對
hello模塊的go.mod文件進行少量更改。在hello目錄中,打開go.mod文件,對其進行更改,使其如下所示,然後保存該文件。
1
2
3
4
5module hello
go 1.14
replace example.com/greetings => ../greetings在這裡,
replace指令example.com/greetings用你指定的路徑替換模塊路徑(URL)。在這種情況下,這是hello目錄旁邊的greetings目錄。在
hello目錄中,運行go build以使Go找到該模塊並將其作為依賴項添加到go.mod文件中。1
2$ go build
go: found example.com/greetings in example.com/greetings v0.0.0-00010101000000-000000000000再次查看
go.mod,以查看所做的更改go build,包括require添加的Go指令。為了構建該模塊,
Go在../greetings目錄中找到了本地程式碼,然後添加了一個require指令 來指定它hello依賴於(requires)example.com/greetings。greetings在hello.go中導入包(包含在greetings模塊中)時,便建立了此依賴關係。該replace指令告訴Go在哪裡可以找到該greetings模塊,因為它尚未發布。要引用已發布的模塊,
go.mod文件將忽略該replace指令,並使用require末尾帶有標記版本號的指令。1
require example.com/greetings v1.1.0
在
hello目錄中,執行hello可執行文件(go build建立的),以確認程式碼有效。- 指令
1
2$ ./hello
Hi, Gladys. Welcome!
- 指令
過程
這邊簡單示範一下上述官方的教學。
註:這邊的路徑使用的是本地某個暫存資料夾做示範。

單字/句子
以下單字,有的其實都看得懂,純粹就是想要加強紀錄、練習發音、翻譯意思。
| 單字/句子 | 翻譯 |
|---|---|
| previous section | 上一節 |
| prompt | 提示 |
| earlier | 較早 |
| handling | 處理 |
| such as | 如 |
| adapt | 適應 |
| directive | 指示 |
| tells | 告訴 |
| directive | 指示 |
| reference | 參考 |
| omit | 忽略 |
| tagged | 標記的 |
| executable | 可執行文件 |
結語
這邊主要學習了,如何去呼叫不同模塊下的函數,要注意函數需要是大寫開頭(表示公開),還有學習到mod.go在使用未發佈的模塊時候,可以使用replace來做使用。
這次的翻譯,大量借助翻譯軟體的幫助,因為很多句子翻譯上沒麼直覺,在自己翻譯過一次後,再用翻譯軟體,在編修一次;希望透過這樣反覆練習,可以大大提升自己的閱讀理解能力。
註:以上參考了
Golang Documentation
