Welcome to your journey into the world of Go programming! If you’re new to this language, the first step is to create a simple “Hello, World!” program. This guide will walk you through setting up your Go environment, writing your first program, and running it successfully.
Setting up your Go environment
Before you can write a “Hello, World!” program, you need to set up your Go environment. Follow these steps to get started:
- Install Go: Visit the official Go website at golang.org/dl/ to download the latest version of Go. Follow the installation instructions specific to your operating system.
- Set up your workspace: Create a directory for your Go projects. It’s common to use a path like
~/goto store your source files. - Configure your environment variables: Set the
GOROOTto point to your Go installation directory andGOPATHto your workspace directory. - Verify your installation: Open a terminal and type
go version. If Go is installed correctly, you should see the version number.
Writing your first Go program
Now that your environment is ready, it’s time to write your first Go program. Follow these steps:
- Create a new file: In your workspace directory, create a file named
hello.go. - Write the program: Open
hello.goin your preferred text editor and enter the following code:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
This code defines the main package, imports the fmt package for formatted I/O, and uses fmt.Println to print “Hello, World!” to the console.
Running the ‘Hello, World!’ program
With your program written, the next step is to run it:
- Navigate to your workspace: Open your terminal and navigate to the directory where
hello.gois located. - Compile the program: Use the command
go build hello.go. This creates an executable file namedhello(orhello.exeon Windows). - Run the executable: Type
./hello(orhello.exeon Windows) in your terminal. You should see “Hello, World!” printed on the screen.
Congratulations! You’ve successfully set up your environment, written your first Go program, and executed it. This foundational exercise is the first step in exploring more complex Go applications. Enjoy coding in Go!
