Getting Started

Getting Started

Installing Go

Before you can start writing Go code, you’ll need to install the Go programming language on your computer. Here’s how to do it:

Download Go

Visit the official Go website at https://golang.org/dl/ and download the installer for your operating system (Windows, macOS, or Linux).

Run Installer

Run the installer and follow the on-screen instructions. This will install the Go compiler (go) and other tools on your system.

Verify Installation

To ensure Go was installed correctly, open a terminal or command prompt and run the following command:

go version

You should see the installed Go version displayed on the screen.

Congratulations, you’ve successfully installed Go on your computer!

Setting Up Your Workspace

Once Go is installed, you’ll want to set up your workspace. Go has a unique approach to organizing code called the workspace or GOPATH. It’s where your Go projects and packages will live.

Create a Workspace

Choose a directory on your computer where you want to store your Go projects. This will be your workspace. For example, you can create a directory like this:

mkdir ~/go-workspace

Set GOPATH

You need to tell Go where your workspace is. You can do this by setting the GOPATH environment variable. Add the following line to your shell profile configuration file (e.g., ~/.bashrc, ~/.bash_profile, or ~/.zshrc):

export GOPATH=~/go-workspace

Save the file, and then run source ~/.bashrc (or the appropriate file for your shell) to apply the changes.

Workspace Structure

Inside your workspace, create three directories: src, bin, and pkg. The src directory is where your Go source code will reside, bin is for executable binaries, and pkg stores compiled package objects.

mkdir -p ~/go-workspace/{src,bin,pkg}

Your Go workspace is now ready for action!

Writing Your First Go Program

Let’s create a simple “Hello, World!” program to get a taste of Go:

Create a Go Source File

Inside your src directory, create a new folder for your project. For example:

mkdir -p ~/go-workspace/src/hello

Then, create a file named hello.go within this folder:

touch ~/go-workspace/src/hello/hello.go

Edit hello.go

Open hello.go in your favorite code editor and add the following Go code:

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

Compile and Run

To compile and run your Go program, open a terminal, navigate to the hello directory, and enter the following command:

go run hello.go

You should see "Hello, World!" printed to the console.

Congratulations! You’ve just written and executed your first Go program.