golang “undefined” function declared in another file?

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

I'm trying to write a basic go program that calls a function on a different file, but a part of the same package. However, it returns:

undefined: NewEmployee 

Here is the source code:

main.go:

package main  func main() { emp := NewEmployee()     } 

employee.go:

package main  type Employee struct {     name string     age int }     func NewEmployee() *Employee {     p := &Employee{}     return p }  func PrintEmployee (p *Employee)  {     return "Hello world!" } 

Thanks in advance

回答1:

Please read "How to Write Go Code".

Don't use /src in your GOPATH. Packages are located in $GOPATH/src.

For build or install you need to have your files in a package directory.

For go run, you need to supply all files as argument:

go run main.go employee.go 

But, you should almost always use go install, or go build (and preferably the former, as go build causes confusion when working with non-main packages)



回答2:

I just had the same problem in Gogland and worked out that you need to change the "Run Kind:" from File to Package. You can choose this from a drop-down if you go into Run/Edit Configurations...



回答3:

If your source folder is structured /go/src/blog (assuming the name of your source folder is blog).

  1. cd /go/src/blog ... (cd inside the folder that has your package)
  2. go install
  3. blog

That should run all of your files at the same time, instead of you having to list the files manually or "bashing" a method on the command line.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!