【问题标题】:How to provide version number for go local packages to mention in `go.mod` file如何在“go.mod”文件中为本地包提供版本号
【发布时间】:2020-06-13 00:36:47
【问题描述】:

我的意图是在 go.mod 文件中提及本地包,但停留在包版本部分。 (Go 版本为go1.14.4 linux/amd64

错误:

arun@debian:~/experiments$ go build
go: errors parsing go.mod:
/home/arun/experiments/go.mod:8: usage: require module/path v1.2.3

如果在执行go build时盲目地给出版本号(例如:go.mod中的github.com/kcarun/local_pkg/app v1.2.3,则会给出未知版本错误)

go.mod:

module github.com/kcarun/gitlandfill

go 1.14

replace github.com/kcarun/local_pkg/ => /home/arun/experiments/local_pkg/

require (
        github.com/kcarun/local_pkg/app
)

main.go:

package main

import "fmt"
import "local_pkg"

func main(){
        fmt.Println("Ok")
        app.SayHello()
}

app.go:

package app

import "fmt"

func SayHello(){
        fmt.Println("Is working!!")
}

目录结构:

arun@debian:~/experiments$ pwd
/home/arun/experiments
arun@debian:~/experiments$ tree
.
|-- go.mod
|-- local_pkg
|   `-- app.go
`-- main.go

【问题讨论】:

  • 你可能想看看this
  • import "local_pkg" 100% 错误。如果该包位于模块中,则为 github.com/kcarun/local_pkg 您必须像这样导入它。请注意,替换指令也是错误的:导入路径不以 / 结尾。请阅读如何编写 Go 代码并坚持下去。
  • go mod 应该通过 git 与版本控制一起工作,使用本地包的这个功能主要用于开发,但是当你的模块正常工作时,只需推送它并使用来自 git 的版本信息
  • 嗨@Volker 正如你所建议的,我修改了代码,但仍然无法正常工作。见Error
  • @Volker ,好的,我开始阅读该文件了!!,

标签: go


【解决方案1】:

将“本地”包导入为的正确方法

.
├── go.mod
├── local_pkg
│   └── app.go
└── main.go

package main

import "fmt"
import "github.com/kcarun/gitlandfill/local_pkg"

func main(){
    fmt.Println("Ok")
    local_pkg.SayHello()
}

,没有在go.mod中声明:

module github.com/kcarun/gitlandfill

go 1.14

如果package声明与目录名不同(例如:dir是/home/arun/experiments/local_pkg,pages是app),你应该导入包使用目录名,但调用它使用包名:

package main

import "fmt"
import "github.com/kcarun/gitlandfill/local_pkg"

func main(){
    fmt.Println("Ok")
    app.SayHello()
}

【讨论】:

  • 我尝试了这个建议的修改,但仍然出现错误 [i.imgur.com/Pk8CYcw.png]
  • @Arun - 已修复 => 尝试。
  • 成功了,我这边也有错误,在本地系统中我的用户名是arun,在github中是kcarun,这在go.mod文件和我的导入语句
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
  • 1970-01-01
  • 2020-12-30
  • 2023-01-22
  • 2023-02-01
  • 2012-05-08
  • 1970-01-01
相关资源
最近更新 更多