Let’s GO! Part 3: Hello, world!
Alright let’s do it!
Things to know before we start:
- Any files containing the GO codes should have
.go
extension. - Any
.go
file should start with apackage
decorator which we’ll see in a moment. (You know, it should say what package it belongs to.) - Any applications written in GO should have a
main
function that is the entry point of your application. - Functions are defined with the
func
keyword. Yeah the language tries so hard to look cool. :)) - You can import packages inside other packages by using the
import
keyword.
Create a directory called hello-world
or whatever name you prefer, and then open your IDE/Text Editor inside that directory. Create a new file called main.go
with the following code inside it:
What’s happening up there?
- At line 1, we’re defining our package name which is
main
. It can be any other names but we do it like this for convention. - At line 3, we’re importing the standard I/O package of GO which is named
fmt
. - At line 5 we’re defining a function called
main
with no arguments which is necessary to exist in every GO program. - And finally at line 6 which is our function’s body, we’re calling the
Println
method of thefmt
package which is responsible for printing a single line to the console.
Note1: The GO language server will automatically add the line 3 while writing line 6 if you forget to mention it and if you have enabled Autocomplete Unimported Packages which was talked about in Part 2.
Note2: You can replace fmt
package with log
package and they’re almost the same. You can see how they differ here.
Run it:
Open a terminal window at the root level of the project where the main.go
file exists and simply run:
go run main.go
You should now see the Hello, world!
printed to the console.
Compile it:
Now we said that GO is a compiled language. So why don’t we try to compile what we did now to see the magic? Run this line in your terminal:
go build -o hw main.go
You’re basically telling the official GO compiler to compile the entry point of your application which is main.go
in this case into a file named hw
. Now that’ll work for Linux and macOS but if you tend to compile it for Windows just replace hw
with hw.exe
. Then you can run the compiled file with ./hw
on macOS and Linux and ./hw.exe
on Windows.
Alright you did it! Was it hard? Nah I don’t think so. Let’s progress into more concepts and we’ll see what happens next.