gpt4 book ai didi

go - 在 Go 中导入自定义包

转载 作者:IT王子 更新时间:2023-10-29 02:31:08 24 4
gpt4 key购买 nike

checked out this answer出于某种原因,要么我无法正确理解,要么它不起作用

此外,在我开始之前,我知道我们如何使用 github 来做,但我想在没有 github 的情况下尝试

首先假设我有一个 main.go 文件

package main

import (
"fmt"
"math"
"subpack"
)

//You Import packages without using comma in Go, rather space or new line
//In VS Code, if you use aren't using the package and run then it will automatically removie it

func main() {
fmt.Println("hello world")
//We use math.Floor to round the nunmber
fmt.Println(math.Floor(2.7))
fmt.Println(math.Sqrt(16))
fmt.Println(subpack.Reverse)
}

注意这里的subpack,是我自定义的包。子包是这样存在的

enter image description here

并包含以下代码

package subpack

//If we make this in the same root level of our main it will throw an error

func Reverse(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}

运行我们的 go 会抛出以下错误

cannot find package "subpack" in any of:
/usr/local/go/src/subpack (from $GOROOT)
/Users/anilbhatia/go/src/subpack (from $GOPATH)

问题:是否可能,如果可以,如何在没有 github 且不将其放入 GO 主文件夹的情况下使用自定义包,而不是简单地引用包含我们的 go 的文件夹> 我们工作目录中的文件。

最佳答案

如错误所示,编译器无法从其中找到 subpack

/usr/local/go/src/subpack (from $GOROOT)

标准库包(例如fmtstrings)所在的位置,或者

/Users/anilbhatia/go/src/subpack (from $GOPATH)

用户安装/定义的包所在的位置。

要使导入工作,您只需要在 main.xml 中包含 subpack 包的相对路径(相对于 $GOPATH/src)。去

假设你的main.go/Users/anilbhatia/go/src/parentpack,那么它的import应该是

import "parentpack/subpack"

如果我理解正确,你希望 subpack 的调用者(比如 main.go)位于 subpack 的一个不相关的位置.这实际上开箱即用。您的 main.go 可以位于任何地方。当你编译它时,编译器会看到 parentpack/subpack 的导入路径,然后转到 $GOPATH/src$GOROOT/src 到找到它。

更多关于源码组织和一些典型例子,可以运行

 go help gopath

在你的 shell 中。

关于go - 在 Go 中导入自定义包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53879834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com