英文:
Installing local go package
问题
我想在本地安装一个Go包。假设我不使用git,也没有网络连接。我只想编写以下示例"库":
mkdir mylib && cd mylib && go mod init locallib/mylib
package main
func GetSecretNumber() int {
return 3
}
现在我只想在我的机器上安装这个"库"。这样,在一个完全独立的包中,我可以这样做:
package main
import (
"fmt"
"locallib/mylib"
)
func main() {
fmt.Printf("The secret number from the lib is: %d\n", mylib.GetSecretNumber())
}
我只希望这个简单的示例在本地工作。我不关心git、github、发布或版本控制。Go工具是否允许我使用任何可用的命令编译mylib包并在本地安装它?
英文:
I want to install a go package locally. Let's pretend I'm not using git and I have no network connection. I just want to write the following demo "library":
mkdir mylib && cd mylib && go mod init locallib/mylib
package main
func GetSecretNumber() int {
return 3
}
Now I just want to install this "library" on my machine. So that in a completely separate package I can do:
package main
import (
"fmt"
"locallib/mylib"
)
func main() {
fmt.Printf("The secret number from the lib is: %d\n", mylib.GetSecretNumber())
}
I just want this trivial example to work locally. I don't care about git, github, publishing or versioning. Do the go tool allow me to compile the mylib package and install it locally using any available commands?
答案1
得分: 2
现在我只想在我的机器上安装这个“库”。
这是a) 不必要的,b) 对于Go代码来说也不明智。Go代码总是从源代码编译的,你不需要“安装库”。
我不关心git、github、发布或版本控制。
好的,没有人强迫你关心这些。
go工具允许我使用任何可用的命令编译mylib包并在本地安装吗?
同样的答案是不,因为这是不必要的。
我只是想让这个简单的例子在本地工作。
好的,要么:
- 将它们放在一个模块中:不需要额外的工作(除了为你的库使用适当的导入路径。不要像你之前那样搞砸)。或者
- 将它们放在两个模块中,然后你可以:
- 使用go.work文件将两个模块链接到一个工作区,或者
- 替换包含的模块。
非常简单和琐碎。
请参考go.dev/doc上的教程,详细解释如何设置模块并从中导入。
英文:
> Now I just want to install this "library" on my machine.
This is a) not necessary and b) not sensible for Go code. Go code is always compiled from source and you do not "install libraries".
> I don't care about git, github, publishing or versioning.
Fine. nobody force you to care about this.
> Do the go tool allow me to compile the mylib package and install it locally using any available commands?
Again no, because that is unnecessary
> I just want this trivial example to work locally.
Fine. Either:
- Put both in one module: No more work needed (except using a proper import path for your library. Don't botch that up like you did). Or
- Put them into two modules in which case you:
- Use a go.work file to link both module into one workspace, or
- You replace the included module.
Dead simple and trivial.
Please consult the Tutorials on go.dev/doc which explain how to set up moduels and import from them in detail.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论