在两个文件中创建Go的主包。

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

Go main package in two files

问题

$GOPATH/src/testapp目录下,我有两个文件:

  • main.go
  • otherfile.go

main.go文件内容如下:

package main

import "fmt"

func main() {
  fmt.Println(SomeFunc())
}

otherfile.go文件内容如下:

package main

func SomeFunc() string {
  return "a thing"
}

当我尝试使用go run main.go运行时,出现了错误:

./main.go:6: undefined: SomeFunc

我原以为我可以创建另一个带有package main的文件,并且main.go中的代码可以访问它的声明。为什么这样不起作用?我应该如何做类似的事情?

英文:

In $GOPATH/src/testapp I have two files

  • main.go
  • otherfile.go

main.go has

package main

import "fmt"

func main() {
  fmt.Println(SomeFunc())
}

otherfile.go has

package main

func SomeFunc() string {
  return "a thing"
}

When I try to run with go run main.go, I get an error

./main.go:6: undefined: SomeFunc

I thought I could create another file with package main and code in main.go would have access to its declarations. Why doesn't this work? How would I do something like this?

答案1

得分: -1

如果我运行go run *.go,它可以工作。
如果我使用go build然后运行./testapp也可以工作。
希望这个问题能帮助将来的某个人。

这个页面上的一些评论对我有帮助:https://github.com/go-lang-plugin-org/go-lang-idea-plugin/issues/555

英文:

If I run go run *.go it works.
It also works if I go build and then ./testapp.
Hopefully this question helps someone in the future.

Some comments on this page helped me: https://github.com/go-lang-plugin-org/go-lang-idea-plugin/issues/555

huangapple
  • 本文由 发表于 2015年2月1日 13:53:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/28259941.html
匿名

发表评论

匿名网友

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

确定