How to print "Hello, World" in Golang

Overview

In this shot, we will learn how to print Hello, World in Golang.

Hello, World is the primary program in every programming language.

First, we must understand some basic concepts in Golang:

  • Every Golang file ends with the .go file extension.
  • We need to provide the package name at the top of the Go file.
  • We need to import the necessary packages using the import keyword.

Before diving into code, we should understand the use of packages in Golang:

  • Packages are used to organize and reuse code in other packages.
  • Golang programs can be divided into two categories:
    • Executable code: These programs run as executable. They contain a main package that tells the compiler that this program is executable.
    • Library code: These programs are not executable; they can be used in other programs.

Example

//provide the package main
package main
//import the packages
import(
"fmt"
)
//Program execution starts here
func main(){
//Print statement
fmt.Println("Hello, World")
}

Explanation

In the code snippet above:

  • Line 2: We declare the package name. We declare it as a main package, and the compiler then understands that this program is executable and not a library code.

  • Line 5: We import the format package, which helps format input and output.

  • Line 10: We use func to declare a function. Here, we declare and define the main function. The program execution starts from the main function in Golang.

  • Line 13: We use the Println() function provided by the fmt package to print the statement, Hello, World.

Free Resources