英文:
How to access imported items
问题
以下是翻译好的内容:
使用以下项目结构:
D:\src\go\my-app
+ internal\
| + utils.go
+ main.go
+ go.mod
以下是文件内容:
internal\utils.go
:
package internal
func GetText() string {
return "hello world"
}
main.go
:
package main
import (
"fmt"
"example.com/my_app/internal"
)
func main() {
fmt.Println(GetText())
}
go.mod
:
module example.com/my_app
go 1.17
当我从该目录运行时,出现以下编译错误:
D:\src\go\my-app>go build
# example.com/my_app
.\main.go:5:2: imported and not used: "example.com/my_app/internal"
.\main.go:9:14: undefined: GetText
有任何想法,可能出了什么问题?
PS:这个问题是可复现的,不是由于拼写错误引起的,而是由于错误的假设(在其他编程语言中,导入的项通过它们的名称访问)。
英文:
With following project structure
D:\src\go\my-app
+ internal\
| + utils.go
+ main.go
+ go.mod
with following file contents:
internal\utils.go
:
package internal
func GetText() string {
return "hello world"
}
main.go
:
package main
import (
"fmt"
"example.com/my_app/internal"
)
func main() {
fmt.Println(GetText())
}
go.mod
:
module example.com/my_app
go 1.17
I'm getting following compilation error when running from the directory:
D:\src\go\my-app>go build
# example.com/my_app
.\main.go:5:2: imported and not used: "example.com/my_app/internal"
.\main.go:9:14: undefined: GetText
Any idea, what could be wrong?
PS: This question is reproducible and not caused by a typo, but by a wrong assumption (in other programming languages the imported items are accessed by their name).
答案1
得分: 2
是的,问题非常明确:
-
你导入了
example.com/my_app/internal
,但是你没有使用它。如果你使用了它,在你的主程序中应该会有internal.<something>
的地方。 -
GetText()
函数不存在:在你的主包中没有GetText()
函数。
解决方案:
将GetText()
替换为internal.GetText()
。现在使用了example.com/my_app/internal
,并且在这个包中找到了GetText()
函数。
英文:
Yes, the problem is quite clear:
-
You import
example.com/my_app/internal
but you don't use it. If you used it, there'd beinternal.<something>
somewhere in your main. -
GetText()
does not exist: there is noGetText()
function in your main package.
Solution:
Replace GetText()
by internal.GetText()
. Now example.com/my_app/internal
is used and GetText()
is found in this package.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论