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!"
}
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)
I just had the same problem in GoLand and found a solution. You need to change the Run kind
from File
to Package
or Directory
. You can choose this from a drop-down if you go into Run/Edit
Configurations.
For package ~/go/src/a_package
, the Package path
is a_package
and the Directory
is ~/go/src/a_package
. You can choose the Run kind
that you like.
If your source folder is structured /go/src/blog (assuming the name of your source folder is 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.
If you're using go run
, do go run *.go
. It will automatically find all go files in the current working directory, compile and then run your main function.
If you want to call a function from another go file and you are using Goland, then find the option 'Edit configuration' from the Run menu and change the run kind from File to Directory. It clears all the errors and allows you to call functions from other go files.
You can try one of followings.
Method 01 : assume that your project name is MyProject
go build
and hit enter../MyProject
and hit enteryou can do both steps at once by typing go build && ./MyProject
. it will run your project properly with all go
files.
Method 02
just type go run *.go
and hit enter. this will execute all your go files
.
Hope this will help to someone.
I ran into the same issue with Go11
, just wanted to share how I did solve it for helping others just in case they run into the same issue.
I had my Go project outside $GOPATH
, so I had to turned on GO111MODULE=on
without this option turned on, it will give you this issue; even if you you try to build or test the whole package
or directory
it won't be solved without GO111MODULE=on