首页 文章

使用模块时,Go get找不到本地包

提问于
浏览
4

我是'm having issues with go'的新模块系统,因为我想定义一个本地模块并将其导入主程序中 . 本地程序包驻留在主程序包/根文件夹的文件夹中 . 想象一下 $GOPATH 之外的以下项目结构 .

项目结构

./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)
}

./model/person.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 的方法,所以我分别选择 example.com/localModule/example.com/localModule/model .

我在运行MacOS 10.13.6的Macbook上使用 go1.11 darwin/amd64 .

2 回答

  • 0

    我能够运行你的代码 .

    • 只有我遇到 Person.namePerson.age 的可见性的问题 . 所以它适用于我的以下结构:
    type Person struct {
        Name string
        Age int
    }
    
    • go.mod 仅存在于主包中 .

    模块是相关Go包的集合,它们作为单个单元一起版本化 .

    所以这里只有一个模块,不需要执行 go mod init example.com/localModule/model

    模块版本由源文件树定义,其根目录中包含go.mod文件 . 当运行go命令时,它会查找当前目录,然后查找连续的父目录,以查找标记主(当前)模块根目录的go.mod .

  • 3

    您可以通过在go.mod中添加require语句和匹配的replace语句以及相对文件路径来获得您所要求的本地“子”模块 .

    在"root" ./go.mod中:

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

相关问题