2 回答

TA貢獻1796條經驗 獲得超7個贊
最簡單且開箱即用的解決方案是將您的database
包/模塊放入 VCS(例如 github.com),因此其他包(在其他模塊內)可以通過導入來簡單地引用它,例如:
import?"github.com/someone/database"
如果你這樣做,你甚至不必go.mod
手動擺弄文件,一切都將由 go 工具來處理:它會自動識別并解決這種依賴關系,下載并安裝所需的包,并自動go.mod
更新.
完全留在本地磁盤上
您database
在 之外創建了一個文件夾GOPATH
,并在其中創建了一個模塊。你創建了另一個模塊,我們稱它為main
,你想使用這個database
包。
你必須做的是:
go.mod
您的main
模塊必須將database
包列為“要求”。給你的database
包一個臨時的 VCS 名稱:require?( ????example.com/me/database?v0.0.0)
你必須告訴 go 工具這個包所在的位置,因為我們使用的完整包名只是一個臨時/幻想的名字。使用
replace
指令使這個database
包指向本地磁盤上的文件夾;您可以使用絕對路徑和相對路徑:replace?example.com/me/database?=>?../database
就這樣。
工作示例
讓我們看一個工作示例。讓我們創建一個pretty
模塊。創建一個pretty
包含 2 個文件的文件夾:
漂亮去:
package pretty
import "fmt"
func Pretty(v ...interface{}) {
? ? fmt.Println(v...)
}
go.mod(可以通過運行創建go mod init pretty):
module pretty
現在讓我們創建另一個主模塊。讓我們在文件夾osinf旁邊創建一個文件夾(可以是任何文件夾)pretty。里面有2個文件:
osinf.go(注意我們打算使用我們的pretty包/模塊,我們通過導入它"example.com/me/pretty"):
package main
import "example.com/me/pretty"
func main() {
? ? pretty.Pretty("hi")
? ? pretty.Pretty([]int{1, 3, 5})
}
去.mod:
module main
require example.com/me/pretty v0.0.0
replace example.com/me/pretty => ../pretty
就這樣。
go run osinf.go在文件夾中運行osinf,輸出為:
hi
[1 3 5]

TA貢獻1802條經驗 獲得超6個贊
跑步:
go mod init yellow
然后創建一個文件yellow.go:
package yellow
func Mix(s string) string {
return s + "Yellow"
}
然后創建一個文件orange/orange.go:
package main
import "yellow"
func main() {
s := yellow.Mix("Red")
println(s)
}
然后構建:
go build
https://golang.org/doc/code.html
- 2 回答
- 0 關注
- 149 瀏覽
添加回答
舉報