👋 Golang Hello World

January 21, 2021
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.

✒️ Write to a CSV file in Go

Learn how to write data to a CSV or TSV file
introduction file

🙌 Case-insensitive string comparison in Go

Learn how to compare strings in a case-insensitive manner
introduction strings

🏁 Check if a string starts with a substring in Go

Learn how to use strings.HasPrefix() function
introduction strings