Golang中如何在另一个模块使用GOPATH之外的模块?

Golang中如何在另一个模块使用GOPATH之外的模块? 我在"database"文件夹中(位于GOPATH之外)创建了一个模块作为个人使用的库,使用了命令 go mod init database,但我不知道:

  • 如何在另一个模块中使用/导入这个模块?

操作系统:Windows,Go版本:v1.11

func main() {
    fmt.Println("hello world")
}
2 回复

根据您的工作空间结构,有几种不同的选择方案。
相关内容已在此处总结:https://golang.org/cmd/go/#hdr-GOPATH_and_Modules
在 Windows 系统中,通常可以使用相对路径。

更多关于Golang中如何在另一个模块使用GOPATH之外的模块?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go 1.11中,要在另一个模块中使用GOPATH之外的模块,有几种方法可以实现。以下是具体的解决方案:

方法1:使用replace指令(推荐)

在需要使用该模块的项目中,修改go.mod文件:

module myapp

go 1.11

require database v0.0.0

replace database => ../database

然后在代码中正常导入:

package main

import (
    "fmt"
    "database" // 导入你的自定义模块
)

func main() {
    fmt.Println("hello world")
    db := database.New() // 使用database模块的功能
    fmt.Println(db)
}

方法2:使用相对路径导入

直接在代码中使用相对路径导入:

package main

import (
    "fmt"
    "./../database" // 相对路径导入
)

func main() {
    fmt.Println("hello world")
    db := database.New()
    fmt.Println(db)
}

方法3:发布到版本控制系统

如果模块在Git仓库中,可以直接通过Git地址导入:

module myapp

go 1.11

require database v0.0.0

replace database => github.com/yourusername/database v0.0.0

完整示例

假设你的项目结构如下:

/myprojects
  /database (你的模块)
    go.mod
    database.go
  /myapp (你的应用)
    go.mod
    main.go

在myapp/go.mod中:

module myapp

go 1.11

require database v0.0.0

replace database => ../database

在myapp/main.go中:

package main

import (
    "fmt"
    "database"
)

func main() {
    fmt.Println("hello world")
    conn := database.Connect()
    fmt.Println("Database connected:", conn)
}

在database/database.go中:

package database

func Connect() string {
    return "Connected to database"
}

运行命令:

cd myapp
go run main.go

这样就可以成功在GOPATH之外使用自定义模块了。

回到顶部