golang “undefined” function declared in another file?

我怕爱的太早我们不能终老 提交于 2019-11-28 15:45:52
JimB

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

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.

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!