Hello, World
Just like any other programming tutorial, we'll start with the Hello World application. The code below may be the simplest code that could ever be written in GoLang. We will be dissecting each line of the code below as we go through this course. For the meantime, we will focus on compiling, running, and displaying Hello, World
in the console.
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
To start with, copy and paste the above code into a text file with any file name like main.go
or helloworld.go
as long as it has the .go
file extension.
If you are using an IDE such as GoLand or VS Code, feel free to click the Run button to execute the program. Otherwise, if you prefer using the CLI, you may run the program using the command below:
go run <filename>.go
Make sure to replace <filename>
with the filename of your program. In my case, I can run my program by executing:
go run main.go
If everything is installed and done correctly, it should have a result similar to the screenshot below:
You may also run the code from Go Playground using the link below. Most of the basic codes can be tested in this platform. Otherwise, we would need to create local files to run the codes throughout this course.
Examining the Source Code
Line 1: package main
All GoLang source file has to be in a package. A package is a logical grouping of source files. It has a similar idea to modules or packages in other programming languages.
In GoLang, a program has to have main
package as this signifies the entry point of the application.
Line 3: import "fmt"
After the package declaration, we specify the other packages that we want to import or use in the source file. In this instance, we are importing the fmt
package that contains functions that we can reuse for displaying or formatting text and reading input.
It is possible to import multiple packages and it would look like the code below:
import (
"encoding/json"
"fmt"
)
Line 5: func main()
A function is a group of statements that exists in your program. In the example above, we only have one statement which is to print Hello, World.
Similar to package main
, func main()
is a special function. It is the entry point of the application and it has to be inside package main
. So, when running a program, everything will start in package main
-> func main
.
Line 7: fmt.Println("Hello, World!")
This line prints Hello, World! in the console. It calls the Println
function of fmt
package. We will explore using functions from other packages in more detail on our later topics. For now, knowing that calling fmt.Println
and passing a text will display a text on the console.