Golang, also known as Go, is a powerful and efficient programming language developed by Google. It’s gaining popularity among developers for its simplicity, performance, and built-in concurrency features. In this article, we’ll walk you through the steps to create your first Golang app: a classic “Hello, World!” program.
Prerequisites
Before we begin, make sure you have Golang installed on your system. If you haven’t installed it yet, you can refer to our previous article on How to Install Golang on Debian 12 (Bookworm): A Step-by-Step Guide
Step 1: Create a New Directory
First, create a new directory for your Golang project. Open your terminal and run the following command:
mkdir hello-world
cd hello-world
Step 2: Create the Golang Source File
Inside the hello-world
directory, create a new file named main.go
using your favorite text editor. For example, you can use nano
:
nano main.go
Step 3: Write the Golang Code
In the main.go
file, add the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Let’s break down the code:
package main
: This line declares the package name as “main”. Every Golang program starts with a package declaration, and the “main” package is used for executable programs.import "fmt"
: This line imports the “fmt” package, which provides functions for formatted I/O operations.func main()
: This is the main function where the execution of the program begins. It is the entry point of every Golang program.fmt.Println("Hello, World!")
: This line uses thePrintln
function from the “fmt” package to print the string “Hello, World!” to the console.
Save the file and exit the text editor.
Step 4: Compile and Run the Program
Now, let’s compile and run our program. In the terminal, while still in the hello-world
directory, run the following command:
go run main.go
This command compiles and executes the main.go
file. You should see the output:
Hello, World!
Congratulations! You’ve just created and run your first Golang app.
Step 5: Building an Executable (Optional)
If you want to create an executable binary of your Golang program, you can use the go build
command:
go build main.go
This command compiles the main.go
file and generates an executable named main
(or main.exe
on Windows). You can run the executable directly:
./main
The program will output “Hello, World!” just like before.
Official documentation
You can check the official documentation here: https://go.dev/doc/
Conclusion
Creating your first Golang app is a simple and straightforward process. With just a few lines of code, you can have a working program that prints “Hello, World!” to the console. This example serves as a foundation for building more complex applications in the future.
Remember to explore the official documentation and resources to learn more about the language and its capabilities. Happy coding!