I just started getting into Golang and wanted to run a file in the terminal with go run and then the file name which is main.go
I configured the GOPATH like so:
export GOROOT="/usr/local/go"
export GOPATH="/Users/myUsername/Desktop/gocode/"
export PATH="/Users/myUsername/Desktop/gocode/bin:$PATH"
I created a folder on my desktop named gocode, placed three folders inside named src, pkg and bin.
And code is stored in src and when I want to run the code I get the following message.
my command was go run main.go
the output I received was stat main.go: no such file or directory
I have no clue why it won't find the directory…
Best Answer
To run the
.go
file and not the compiled binary, you need to givego run
the relative source file path. Try:To compile the go program into a binary executable, use:
This will work if...
go
can be found; test this with the commandwhich go
. Does it return a path togo
?GOPATH
environment is set appropriately; test this withecho $GOPATH
. Does it return the project directory? See go wiki page on GOPATH for advice.Break Down the Problem
Open a new Terminal.app window. This will discard previous
export
commands that may be causing confusion.Test
go
can be found. Usewhich go
to ensure the binary is available. If not, fix this with anexport
command.Check the directory structure of your project. Make sure no names are mispelt and your
.go
files have the correct suffix. The Finder may be hiding the true suffix. Doesls -lR
list the contents you expect?Check you are in the right directory. The
go
commands need to be executed from within the project directory. Usepwd
to see what directory you are in? Is it the project directorygocode/
? If not, use acd
command to fix this.Project Layout
Let's assume your file structure follows the minimal go convention:
The three separate commands to run
main.go
would be:This will run the main function within
main.go
. To build an executable suitable for distribution, use the commandgo build src/main.go
.Managing GOPATH Directories
With regard to managing gopaths and projects, I have had success with Herbert Fischer's Manage multiple GOPATH dirs with ease approach.