In this example, you will learn how to write the classic “Hello World” program. “Hello World” is a simple program that displays the word Hello World
on the screen. Traditionally, this is the first program written by people learning to code in a new programming language.
Let’s check how to write Golang “Hello World” program step by step.
If you don’t have Golang installed, visit the official Go website and install the version appropriate for your operating system.
Golang “Hello World” program
- Create
hello-world
directoryIt is a good practice that each new project has its own directory.
- Save the following program as
main.go
in thehello-world
directorypackage main import "fmt" func main() { fmt.Println("Hello World!") }
- Run your program
$ go run hello-world/main.go
Output
Hello World!
Congratulations! You have just created your first program in Go π.
How Golang “Hello World” program works
package main
In Go, every program starts with a package declaration. A package is a collection of source files used to organize related code into a single unit. We are declaring a package called main
here because we will need to declare the main()
function, which can only be declared in a package named main
.
import "fmt"
Next, we have the package import statement. In our program, the fmt
package has been imported and will be used in the main()
function to print the “Hello World” text to the standard output (your screen).
func main() {
//...
}
The func main()
starts the definition of the main()
function. The main()
is a special function that is executed first when the program starts. As you already know, the main()
function in Go should always be declared in the main
package.
fmt.Println("Hello World!")
The main()
calls the Println()
function of the fmt
package. After starting the program, it prints the passed argument (our text “Hello World!”) to the standard output together with a new line.