Objective
In this lesson, we will introduce the Go programming language and write a simple program that prints “Hello, World!” to the console.
The “Hello, World!” program is often used as the first step in learning a new programming language, as it helps familiarize you with the basic syntax and structure of the language.
Go Program: Hello, World!
// Go program to print "Hello, World!" to the console
package main
import "fmt"
// main function is the entry point for the program
func main() {
fmt.Println("Hello, World!")
}
Explanation of the Program Structure
The Go program is divided into several important components:
- package main: Every Go program starts with a package declaration. “main” is a special package in Go that indicates this file is an executable program.
- import “fmt”: This imports the
fmt
package, which provides functions for formatted I/O. In this case, we are usingfmt.Println
to print to the console. - func main(): This is the main function, which serves as the entry point of the program. The execution of the program starts from here.
- fmt.Println(“Hello, World!”): This function prints the string “Hello, World!” to the console. The
fmt.Println
function is used for outputting data to the standard output (in this case, the console).
How to Run the Program
Follow these steps to run the program:
- Install Go: Before running the program, make sure Go is installed on your system. You can download Go from the official website: Go Downloads.
- Create a New Go File: Create a new file with the name
hello.go
using any text editor or IDE of your choice. - Write the Code: Copy and paste the Go code provided above into the
hello.go
file. - Open a Terminal: Open a terminal (Command Prompt or PowerShell on Windows, Terminal on macOS and Linux) and navigate to the directory where the
hello.go
file is located. - Run the Program: To execute the program, run the following command:
go run hello.go
This will compile and run the program, and you should see the output: Hello, World! printed in the terminal.