👋 Golang Hello World

introduction

In this example, you learn how to write the classic “Hello World” program. “Hello World” is a simple program that outputs Hello World on the screen. It’s traditionally 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 version that suits your operating system.


Golang “Hello World” program

  1. Create hello-world directory

    It is a good practice that each new project has its directory.

  2. Save the following program as main.go in the hello-world directory
    package main
    
    import "fmt"
    
    func main() {
        fmt.Println("Hello World!")
    }
  3. Run your program
    $ go run hello-world/main.go

    Output

    Hello World!

    Congratulations! You just created your first program in Go 🚀.


How Golang “Hello World” program works

package main

In Golang every program starts with a package declaration. Package is a collection of source files used to orgranize related code into a single unit.

import "fmt"

Declaration of package import. In our program, fmt package is imported and will be used in the main() function to print the “Hello World” text to standard output (your screen).

func main() {
    
}

Definition of the main() function. The main() is a special function that is executed first when a program starts. The main() function in Golang should always be declared in the main package.

fmt.Println("Hello World!")

Content of the main() is the call to the Println() function of the fmt package. After running the program, it prints passed argument (our “Hello World!” text) to the standard output along with a new line.

🖨️ Convert string to []byte or []byte to string in Go

Learn the difference between a string and a byte slice
introduction strings slice

🧠 Print the memory address of a variable in Go

Learn how to find and print the address of a variable or pointer
introduction pointer slice

🏟️ Capacity and length of a slice in Go

Learn what is the difference between length and capacity of a slice
introduction slice array