Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"undefined" function declared in another file?

Tags:

undefined

go

func

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.


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.


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.


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.

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.


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.