无法在另一个包的主函数main中导入主包main的函数A()。有两个主包。

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

Unable to import func A() of package main, inside another package main func main. There are 2 package main

问题

main包级别上,我有两个文件hello.gomain.go

  1. |- hello.go
  2. |- main.go

这两个文件都在package main级别,但与其他包不同的是,我无法在func main中导入hello中定义的funcpackage main只能有一个文件吗?

  1. // hello.go
  2. package main
  3. import "fmt"
  4. func Hello() {
  5. fmt.Println("hello world")
  6. }
  7. // main.go
  8. package main
  9. func main() {
  10. Hello()
  11. }

错误信息:

  1. ./main.go:4:2: undefined: Hello
英文:

At package level main I have 2 files hello.go and main.go.

  1. |- hello.go
  2. |- main.go

Both the files are in package main level but unlike other packages I am unable to import a func defined in the hello in the func main. Can there be only 1 file with package main?

  1. // hello.go
  2. package main
  3. import "fmt"
  4. func Hello() {
  5. fmt.Println("hello world")
  6. }
  7. // main.go
  8. package main
  9. func main() {
  10. Hello()
  11. }

Error

  1. ./main.go:4:2: undefined: Hello

答案1

得分: 1

两种方法可以使其正常工作:

1)使用命令"go build ."编译代码,然后执行生成的可执行文件。

2)使用go mod:

a) 运行命令"go mod init main"初始化模块。

b) 运行命令"go mod tidy"整理模块依赖。

c) 运行命令"go run main"执行代码。

如果build命令无法解析模块到当前目录,那么你需要告诉go模块的位置。

英文:

two ways to make this work ok

  1. go build . then execute the binary

  2. with go mod:

> go mod init main
> go mod tidy
> go run main

looks like build can resolve the module to the current directory.
Otherwise, you have to tell go where the module is

答案2

得分: 0

在终端中,你应该使用

  1. go run .

而不是

  1. go run main.go
英文:

In the terminal, you should use

  1. go run .

instead of

  1. go run main.go

huangapple
  • 本文由 发表于 2021年6月7日 19:42:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/67871011.html
匿名

发表评论

匿名网友

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

确定