fmt.Println(“Hello Golang”)

Stefan M.
Golicious
Published in
2 min readFeb 21, 2019

The first and obvious thing you learn when you learn a new programming language is of course the “Hello World” program.

The follow code is the minimum required code to display “Hello Golang” in your terminal:

package mainimport (
"fmt"
)
func main() {
fmt.Println("Hello Golang")
}

That is… from my point of view a lot! Not because this has 71 chars and 7 lines of code. No — this code has a lot of stuff which needs to be explained.

I mean compared to an “Hello Kotlin” :

fun main() {
println("Hello Kotlin")
}

You could argue that we have package and import in Kotlin as well. But its not required for this example!

Anyway let’s go throw the Golang example it step by step.

The program starts with the package keyword— like in Kotlin when you put your code in a package. The entry point— when running it — is declared in a file with the main package which requires a func named main.

The next piece of code is the import call. This is also similar to Kotlin. You have to declare the packages you want to use in your program.
Meaning the fmt package (there should be “somewhere” a file which has declared package fmt in its header) has a func called Println.

That is an interesting point. The import “search” for files which have declared package XY in its header. With this information we could imagine that there is “somewhere” a file which looks like the following:

package fmtfunc Println(…) { }

You may have already wondered why I wrote "somewhere". Well, because I don’t know where it come from and which “default packages” exist!

Please note that there are also another style for the import which looks like import "packageName". The benefit of using the “call” style is that you can import multiple packages at once without repeating the import keyword:

import (
"fmt"
"math"
)

Last but not least the main function. This is — as I said above — the entry point and the first function which will be called when you run the code.

Please bear with me that I will explain the syntax of a func in another post. Otherwise it will explode this blog.

Function calls are actually quite similar to Kotlin. The only difference here is that you have to — in Golang — always put the package name (which we have declared in the import section) in front of the func call. This is in Kotlin more or less optional. Because you could also use some.package.afunction() instead of importing it and call the (extension) function directly.

Learning sources

I’ve learned this by reading “A Tour of Go”. To be exact from the basics sections.

--

--