Q1 - Why
works? but
and does not work. Vice versa the same thing is taking place
Q2 - As I stated that both the files namely "my-fist" and "my-fist.go" are in the "hello-world" folder, now the instructor has come to that "hello world" folder and doing 2 things like
and
What he would have done had he not given the
command to run that "my-fist" executable file
It’s been a while since I did anything with go. I took a look at it a couple of years ago, but haven’t actually taken time to learn it properly yet.
But if memory serves, the command
go run my-fist.go
will build/compile your
my-fist.go
source file into a native, binary, ELF executable called
my-fist
and will then run the executable. But only if the source code compiles and links cleanly into an executable, without errors, or warnings. If there are any errors/warnings, the build process will stop and will list any errors/warnings.
The command
./my-fist
will just run the pre-compiled executable called
my-fist
, but only if it exists.
If it doesn’t exist, you will have to compile it first with the go compiler.
If the instructor didn’t use the
./
prefix before
my-fist
, the shell (bash, or zsh, or whatever they’re using) would throw an error message, because the shell looks for all commands in directories that are listed in the $PATH environment variable (e.g.
/usr/bin; /usr/local/bin;/usr/local/share/bin;
etc. etc.)
In other words, because the instructor is in the
/home/user/helloworld/
directory and the
/home/user/helloworld
directory is
not listed in $PATH, the shell does not know where the
my-fist
executable is. So they have to specify the path to the executable using a relative path.
./
is the relative path for the current working directory (the directory we’re currently in).
So
./my-fist
means run the executable file
my-fist
in the current directory.
They could also run the executable by using an absolute path too. Which is the complete path to the executable.
E.g.
/home/user/helloworld/my-fist
But as the instructor is already in the
/home/user/helloworld/
directory, it’s quicker, easier and less typing to use a relative path to run the executable:
./my-fist
.
Does that make sense?!
Also, running
./my-fist.go
will not work because it is a go source file.
Go is a compiled language. It’s not an interpreted scripting language. Go source code needs to be compiled into an executable before it can be ran.
If you want to run a
.go
file, you’d need to use
go run /path/to/mainfile.go
, where
/path/to/mainfile.go
is the path to the main .go file in your project.
That will invoke the go compiler and will compile the .go source code into an executable that can be ran.
Once the executable has been built, you can simply run the executable directly, without needing to compile again.
And obviously, if you edit the .go file at any point, you will need to re-compile the source code and re-build the executable, in order to see any changes in action.