Go programming language setup and Hello World example

Creating a ‘Hello, World!’ Program in Go

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:

  1. 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.
  2. Set up your workspace: Create a directory for your Go projects. It’s common to use a path like ~/go to store your source files.
  3. Configure your environment variables: Set the GOROOT to point to your Go installation directory and GOPATH to your workspace directory.
  4. 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:

  1. Create a new file: In your workspace directory, create a file named hello.go.
  2. Write the program: Open hello.go in 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:

  1. Navigate to your workspace: Open your terminal and navigate to the directory where hello.go is located.
  2. Compile the program: Use the command go build hello.go. This creates an executable file named hello (or hello.exe on Windows).
  3. Run the executable: Type ./hello (or hello.exe on 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!