Introduction
Printing "Hello, World!" is one of the simplest and most common exercises when learning a new programming language. This guide will show you how to write a basic Go program that prints "Hello, World!" to the console.
Problem Statement
Create a Go program that:
- Prints the message "Hello, World!" to the console.
Example:
- Output:
Hello, World!
Solution Steps
- Import the fmt Package: Use
import "fmt"to include the fmt package, which provides I/O formatting functions likePrintln. - Write the Main Function: Define the
mainfunction, which is the entry point of every Go program. - Print the Message: Use
fmt.Printlnto print "Hello, World!" to the console.
Go Program
package main
import "fmt"
/**
* Go Program to Print "Hello, World!"
* Author: https://www.javaguides.net/
*/
func main() {
// Step 1: Print the message "Hello, World!" to the console
fmt.Println("Hello, World!")
}
Explanation
Step 1: Import the fmt Package
- The
fmtpackage is imported to provide functions for formatted I/O, such asPrintlnfor printing to the console.
Step 2: Write the Main Function
- The
mainfunction is the starting point of the Go program. It is defined using thefunckeyword, followed by the function namemain.
Step 3: Print the Message
- The
fmt.Printlnfunction is used to print the string "Hello, World!" to the console. ThePrintlnfunction automatically adds a newline at the end of the output.
Output Example
Example:
Hello, World!
Conclusion
This Go program demonstrates how to print "Hello, World!" to the console, which is a fundamental exercise when starting with Go programming. It introduces basic concepts such as importing packages, defining the main function, and printing output, making it a perfect example for beginners learning Go.