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
.gofile extension. - We need to provide the package name at the top of the Go file.
- We need to import the necessary packages using the
importkeyword.
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
mainpackage that tells the compiler that this program is executable. - Library code: These programs are not executable; they can be used in other programs.
- Executable code: These programs run as executable. They contain a
Example
//provide the package mainpackage main//import the packagesimport("fmt")//Program execution starts herefunc main(){//Print statementfmt.Println("Hello, World")}
Explanation
In the code snippet above:
-
Line 2: We declare the package name. We declare it as a
mainpackage, and the compiler then understands that this program is executable and not a library code. -
Line 5: We import the
formatpackage, which helps format input and output. -
Line 10: We use
functo declare a function. Here, we declare and define themainfunction. The program execution starts from themainfunction in Golang. -
Line 13: We use the
Println()function provided by thefmtpackage to print the statement,Hello, World.