Understanding any programming language is begins with the "Hello World!" program. A simple "Hello, World!" program in the Go programming language (Golang).
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Now, let's break it down:
Package Declaration:
package main
The
package
keyword is used to declare the package to which this Go file belongs.In Go, there are two types of packages: executable and non-executable. The
main
package is special—it's the entry point for the executable programs.
Import Statement:
import "fmt"
The
import
keyword is used to include other packages in your program.Here, we import the "fmt" package, which provides functions for formatting input and output. In this program, we use it for printing.
Main Function:
func main() { // Code goes here }
Every executable Go program must have a
main
function.The program starts executing from the
main
function.
Printing to Console:
fmt.Println("Hello, World!")
fmt.Println
is a function from the "fmt" package used to print a line to the console.In this case, it prints the string "Hello, World!" followed by a newline character.
Running the Program:
To run this program, save it in a file with a
.go
extension, for example,hello.go
. Open a terminal or command prompt, navigate to the directory containing the file, and run the following commandgo run hello.go
This will compile and execute the program, and you should see the output:
Hello, World!
Understanding
main
Function:The
main
function is the entry point of the program.Statements inside the
main
function are executed sequentially when the program runs.
Comments:
Comments in Go start with
//
for single-line comments or/*
and*/
for multi-line comments.Comments are ignored by the Go compiler and are there to provide information to developers.
File Naming Convention:
Go files typically have a
.go
extension. The file name (excluding the extension) can be different from thepackage
name, but it's a good practice to keep them the same.
Understanding the structure of this simple "Hello, World!" program provides a foundation for working with more complex Go programs. It introduces the concept of packages, imports, functions, and basic I/O operations.