如何访问导入的项目

huangapple go评论80阅读模式
英文:

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 be internal.&lt;something&gt; somewhere in your main.

  • GetText() does not exist: there is no GetText() 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.

huangapple
  • 本文由 发表于 2022年1月29日 19:34:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/70904909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定