Go: Hello World!
Overview
We will write our first go program "Hello, World!".
Prerequisites
Before starting, ensure you have:
- Go installed on your system
- A text editor or IDE
- Basic understanding of using the terminal
Checking Your Go Installation
First, verify that Go is properly installed on your system by running this command in your terminal:
You should see output similar to this:
Not Installed?
If you see a "command not found" error, you'll need to download and install Go first.
If not, for now, you can visit Go Playground
Writing Your First Go Program
Let's create a simple program that prints "Hello, World!" to the console.
Assumption: You are using Linux, Mac, or WSL.
Open a directory of your choice in your terminal and Create a new file named hello.go in your preferred directory. If you are on linux you can type touch hello.go in your terminal.
Understanding the Code
Breakdown the code:
Code Structure
- Every Go program starts with a package declaration
mainpackage creates an executable program- Other packages create reusable libraries
- Imports the formatting package
fmt. It Provides functions for i/o operation. - Essential for console interaction.
Extra Jargon: If you have noticed in the program, the line fmt.Println("Hello, World!"), you may wonder why the Println function p is in caps. This is because Println is a function from the fmt package that is used to print text to the console. The fmt package is part of the Go standard library and provides functions for formatted I/O.
The Println function is one of the most commonly used functions in the fmt package. It stands for "Print Line" and is used to print text to the console with a newline at the end. The Println function is case-sensitive and must be written in caps for the first letter, that way the Go compiler knows that you are referring to the Println function from the fmt package.
Running our Program
There are two ways to run your Go program.
Use go run to compile and execute in one step:
| Terminal | |
|---|---|
| Output | |
|---|---|
Quick Development
This method is perfect for development and testing as it's faster for quick iterations.
Print Functions
Go provides several ways to output text. Here are some variations of our Hello World program:
Print Variations
| hello.go | |
|---|---|
Tip
Printf allows formatted strings using placeholders like %s, %d, etc.
What's Next?
Congratulations!
We've successfully written and run our first Go program! Here's what we've learned:
- Setting up Go
- Creating a Go source file
- Understanding basic Go syntax
- Running Go programs
- Using different print functions
Next Steps
Continue learning:
- Go to the compiler section to learn more about the Go compiler.