可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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).
- cd /go/src/blog ... (cd inside the folder that has your package)
- go install
- 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.