go - "undefined" function declared in another file?

ID : 20260

viewed : 10

Tags : goundefinedfuncgo

Top 5 Answer for go - "undefined" function declared in another file?

vote vote

97

Please read "How to Write Go Code".

Use go build or go install within the package directory, or supply an import path for the package. Do not use file arguments for build or install.

While you can use file arguments for go run, you should build a package instead, usually with go run ., though you should almost always use go install, or go build.

vote vote

89

I just had the same problem in GoLand (which is Intellij IDEA for Go) and worked out 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.

Eg: for package ~/go/src/a_package, use a Package path of a_package and a Directory of ~/go/src/a_package and Run kind of Package or Directory.

vote vote

74

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.

vote vote

60

You can try one of the following:

Method 1:

  • Assume that your project name is MyProject
  • Go to your path, run go build
  • It will create an executable file as your project name ("MyProject")
  • Then run the executable using ./MyProject

You can do both steps at once by typing go build && ./MyProject. Go files of the package main are compiled to an executable.

Method 2:

  • Just run go run *.go. It won't create any executable but it runs.
vote vote

52

go run . will run all of your files. The entry point is the function main() which has to be unique to the main package.

Another option is to build the binary with go build and run it.

Top 3 video Explaining go - "undefined" function declared in another file?

Related QUESTION?