Cookies management by TermsFeed Cookie Consent

πŸ‘‹ Hello World - Write your first application in Go

Last updated:
introduction

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

  1. Create hello-world directory

    It is a good practice that each new project has its own 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 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.


Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

♾️ Infinite loop in Go

Learn how to define a “while true” loop
introduction loop

πŸ“” Convert a struct to io.Reader in Go

Learn how to convert a struct to io.Reader and send it as an HTTP POST request body
introduction http

πŸ“Ÿ Convert HTTP response io.ReadCloser to string in Go

Learn how to convert a HTTP client response body to string
introduction http