我对go的新模块系统有问题,因为我想定义一个本地模块并将其导入主程序.本地包位于主包/根文件夹的文件夹中.想象一下在$GOPATH之外的项目 struct .

项目 struct

./main.go

package main

import "fmt"
import "example.com/localModule/model"

func main() {
    var p = model.Person{name: "Dieter", age:25}
    fmt.Printf("Hello %s\n", p.name)
}

/模特/人.go

package model

type Person struct {
    name string
    age int
}

在根文件夹中,我通过调用

go mod init example.com/localModule

model/文件夹中,我通过调用

go mod init example.com/localModule/model

这个错误

在根文件夹中调用以下命令失败.

$ go get
go build example.com/localModule/model: no Go files in

$ go build
main.go:4:8: unknown import path "example.com/localModule/model": cannot find module providing package example.com/localModule/model

Go Get的错误消息被切断,我不会错误地解析它.

我不打算将模块推送到服务器上,只是需要一种引用本地包model的方式,所以我分别 Select 了example.com/localModule/example.com/localModule/model.

我在一台运行MacOS10.13.6的Macbook上使用go1.11 darwin/amd64.

推荐答案

通过在go中添加一个require语句和一个匹配的replace语句以及一个相对文件路径,您可以像您所要求的那样拥有本地"子"模块.摩登派青年

In the "root" ./go.mod:

module example.com/localModule

require example.com/localModule/model v0.0.0

replace example.com/localModule/model v0.0.0 => ./model

Go相关问答推荐

如何在Go中使用a-h/tempson渲染预格式的内容?

将Go程序导出到WASM—构建约束排除所有Go文件

获取作为类型参数传递给方法接收方中的类型参数的切片的基础类型

map 中的多个函数类型,Golang

按键值排序字符串- Golang

Go SQLCMD比Windows本机版本慢吗?

如何找到一个空闲的TPM句柄来保存新的密钥对对象?

有没有办法让sqlc生成可以使用pgxpool的代码

Go 中的sync.Cond 与 Wait 方法

无法从主域访问子域:无Access-Control-Allow-Origin

如何以干净的方式在中间件中注入 repo 或服务?

也许在 golang 中包(字符串和字符串类型不匹配)

在嵌套模板中使用变量,它也被定义为 go 模板中的变量?

grpc-gateway:重定向与定义不匹配(原始文件)

不能在 *gorm.db 而不是 gorm.db 上使用 WithContext(ctx) 方法

Go 泛型:自引用接口约束

如何在 Windows 上使用 cgo 为 386 arch 构建 lib?

具有相同提前返回语句的函数的不同基准测试结果

如何优雅地映射到 Go 中返回可变长度数组的方法?

Go/Golang:如何从 big.Float 中提取最低有效数字?