golang “undefined” function declared in another fi

2019-01-16 10:17发布

问题:

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 GoLand and my solution worked out. 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.



回答3:

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.



回答4:

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.



回答5:

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.



回答6:

You can try one of followings.

Method 01 : assume that your project name is MyProject

  • go to you path, type go build and hit enter.
  • it will creates an executable file as your project name ("MyProject")
  • then in your terminal type ./MyProject and hit enter

you 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.