The Hello World program is usually the first program created after installing Go. It demonstrates how to write a basic Go program, use the main package, define the main() function and display output on the screen using the fmt package.
Steps to Create a Program
Step 1: Create a Go File
Open any code editor and create a new file with the .go extension, for example:
first.go
Step 2: Write the Program
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Step 3: Run the Program
Open a terminal or command prompt, navigate to the folder containing the file and run:
go run first.go
Output
Hello, World!
Understanding the Program
- package main: Every executable Go program starts with the main package. It tells the Go compiler that this program can be run directly.
- import "fmt": fmt package provides functions for formatted input and output. Here, it is imported to display text on the screen.
- func main(): The main() function is the entry point of a Go program. Program execution starts from this function.
- fmt.Println(): The Println() function prints the given text to the console and automatically moves the cursor to the next line.
Common Mistakes
- Saving the file without the .go extension.
- Using a package name other than main for an executable program.
- Forgetting to import the fmt package before using fmt.Println().
- Running the command from the wrong directory.