Back to blog

Saturday, March 1, 2025

How to Write Your First Program in Go

cover

How to Write Your First Program in Go

Go, also known as Golang, is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. It is known for its simplicity, efficiency, and powerful standard library. In this blog, you'll learn how to write your first program in Go, from setting up your environment to running your first piece of code.

Introduction to Go

Go is designed to make it easy to build simple, reliable, and efficient software. It combines the best of both statically and dynamically typed languages, offering safety and performance along with fast development and deployment. Go's syntax is clean and concise, making it a great choice for beginners.

Key Features of Go

  • Static Typing: Variables must have a declared type, which helps catch errors at compile time.
  • Concurrent Programming: Go includes built-in support for concurrent programming, which makes it suitable for writing high-performance applications.
  • Garbage Collection: Go’s garbage collector automatically manages memory allocation and deallocation, reducing the risk of memory leaks.
  • Rich Standard Library: Go’s standard library provides a set of packages that can be used for a variety of purposes, from file I/O to networking.
  • Simplicity: Go’s simplicity makes it easy to learn and read, especially for beginners.
  • Package Management: Go has a built-in package management system that makes it easy to install, update, and version control dependencies.

Setting Up Your Go Environment

Before you can start writing Go programs, you need to set up your Go environment. Here are the steps to install Go on your system:

Installing Go

  1. Download Go: Visit the official Go website and download the version of Go that matches your operating system (Windows, macOS, or Linux).

  2. Install Go:

    • Windows: Run the downloaded MSI installer and follow the instructions.
    • macOS: You can use a package manager like Homebrew:
      brew install go
      
    • Linux: Use your distribution's package manager, for example on Ubuntu:
      sudo apt update
      sudo apt install golang
      
  3. Verify Installation: Open a terminal or command prompt and type the following command to verify the installation:

    go version
    

    This should display the version of Go that you installed.

Setting Up Your Workspace

Go uses a specific directory layout called the workspace. Your workspace is a directory hierarchy with three directories at its root:

  • src: Contains Go source files.
  • pkg: Contains package objects.
  • bin: Contains executable commands.

To set up your workspace, follow these steps:

  1. Create a Workspace Directory:

    mkdir -p $HOME/go/{bin,src,pkg}
    
  2. Set the GOPATH and GOROOT Environment Variables:

    • On Windows, you can manually set these environment variables via the System Properties > Environment Variables.
    • On Unix-like systems, add the following lines to your .bashrc or .bash_profile:
      export GOPATH=$HOME/go
      export PATH=$PATH:$GOPATH/bin
      export PATH=$PATH:/usr/local/go/bin
      
  3. Reload Your Shell Configuration:

    source ~/.bashrc
    

Writing Your First Go Program

Now that your Go environment is set up, you are ready to start writing your first program. In this example, we'll write a simple "Hello, World!" program.

Creating the Source File

  1. Create a Project Directory: Inside your src directory, create a new directory for your project.

    mkdir -p $GOPATH/src/hello
    
  2. Navigate to the Project Directory:

    cd $GOPATH/src/hello
    
  3. Create a Source File: Create a new file named main.go.

    touch main.go
    

Writing the Code

Open main.go in your favorite text editor and add the following code:

// main.go
package main

import "fmt"

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

Explanation of the Code

  • Package Declaration: package main declares that this package is the main package (entry point of the program).
  • Import Statement: import "fmt" imports the fmt package, which contains functions for formatted I/O, including printing to the console.
  • Main Function: func main() is the entry point of the program. It is where the execution begins.
  • Println Function: fmt.Println("Hello, World!") prints the string "Hello, World!" to the console.

Running Your Program

To run your program, use the go run command followed by the file name:

go run main.go

This command compiles and runs the program. If everything is set up correctly, you should see the following output:

Hello, World!

Building Your Program

To compile your Go code into a binary, use the go build command. This will produce an executable file that you can run without the Go toolchain.

  1. Build the Program:

    go build
    
  2. Run the Compiled Program:

    ./hello
    

On Windows, the executable file will have a .exe extension:

.\hello.exe

This should also display:

Hello, World!

Understanding Go Syntax

Now that you have written and run your first Go program, let’s look at some basic Go syntax that will help you write more complex programs.

Variables

Go is a statically typed language, meaning you must declare the type of each variable at compile time. Here are a few examples:

package main

import "fmt"

func main() {
    // Declare and initialize a variable
    var name string = "Alice"
    fmt.Println("Name:", name)

    // Short variable declaration
    age := 30
    fmt.Println("Age:", age)

    // Multiple variable declarations
    var x, y int = 1, 2
    fmt.Println("x:", x, "y:", y)
}

Control Structures

Go supports the usual control structures found in most programming languages:

  • If Statements:

    package main
    
    import "fmt"
    
    func main() {
        num := 10
    
        if num > 5 {
            fmt.Println("num is greater than 5")
        } else {
            fmt.Println("num is less than or equal to 5")
        }
    }
    
  • Switch Statements:

    package main
    
    import "fmt"
    
    func main() {
        num := 3
    
        switch num {
        case 1:
            fmt.Println("One")
        case 2:
            fmt.Println("Two")
        case 3:
            fmt.Println("Three")
        default:
            fmt.Println("Unknown number")
        }
    }
    
  • For Loops:

    package main
    
    import "fmt"
    
    func main() {
        // Traditional for loop
        for i := 0; i < 5; i++ {
            fmt.Println(i)
        }
    
        // While loop using for
        j := 0
        for j < 5 {
            fmt.Println(j)
            j++
        }
    
        // Infinite loop
        // for {
        //     fmt.Println("Infinite loop")
        // }
    }
    

Arrays and Slices

Arrays have a fixed size, while slices can grow and shrink dynamically.

  • Arrays:

    package main
    
    import "fmt"
    
    func main() {
        var arr [5]int
        arr[0] = 1
        arr[1] = 2
        fmt.Println("Array:", arr)
    }
    
  • Slices:

    package main
    
    import "fmt"
    
    func main() {
        slice := []int{1, 2, 3, 4, 5}
        fmt.Println("Slice:", slice)
    
        slice = append(slice, 6)
        fmt.Println("Slice after appending 6:", slice)
    }
    

Functions

Functions are blocks of code that perform a specific task. Here is a basic example:

package main

import "fmt"

// Function to add two integers
func add(a int, b int) int {
    return a + b
}

func main() {
    result := add(5, 3)
    fmt.Println("Sum:", result)
}

Structs and Interfaces

Go does not have classes, but it has structs and interfaces for creating and managing data.

  • Structs:

    package main
    
    import "fmt"
    
    // Define a struct type
    type Person struct {
        Name string
        Age  int
    }
    
    func main() {
        p := Person{Name: "Bob", Age: 25}
        fmt.Println("Person:", p)
    }
    
  • Interfaces:

    package main
    
    import "fmt"
    
    // Define an interface
    type Greeter interface {
        Greet()
    }
    
    // Person struct implementing the Greeter interface
    type Person struct {
        Name string
    }
    
    func (p Person) Greet() {
        fmt.Printf("Hello, my name is %s!\n", p.Name)
    }
    
    func main() {
        p := Person{Name: "Alice"}
        var gr Greeter = p
        gr.Greet()
    }
    

Basic Project Structure

As your Go programs grow, it’s important to organize them properly. Here is a basic project structure:

myproject/
├── main.go
├── go.mod
└── pkg/
    └── utils/
        └── util.go
  • main.go: The entry point of your application.
  • go.mod: A file to manage dependencies.
  • pkg/: A directory to store your other Go source files, grouped by functionality.

Creating a go.mod File

To manage dependencies, create a go.mod file in your project directory:

go mod init myproject

This command creates a go.mod file with your module name.

Installing External Packages

To use external packages in your Go program, you can use the go get command. For example, to use the fmt package, which is part of the standard library, you don’t need to install it. However, if you want to use a package from the internet, such as github.com/gorilla/mux for HTTP routing, you can do the following:

  1. Install the Package:

    go get github.com/gorilla/mux
    
  2. Use the Package:

    package main
    
    import (
        "fmt"
        "net/http"
        "github.com/gorilla/mux"
    )
    
    func helloHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    }
    
    func main() {
        r := mux.NewRouter()
        r.HandleFunc("/", helloHandler)
        http.ListenAndServe(":8080", r)
    }
    

Writing a Simple HTTP Server

Let’s write a simple HTTP server to handle incoming HTTP requests. This will give you a taste of how to work with external packages.

  1. Create a New Directory for Your Server:

    mkdir -p $GOPATH/src/server
    cd $GOPATH/src/server
    
  2. Create a main.go File:

    touch main.go
    
  3. Write the Server Code:

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func helloHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Welcome to my Go server!")
    }
    
    func main() {
        http.HandleFunc("/", helloHandler)
        fmt.Println("Starting server at port 8080")
        if err := http.ListenAndServe(":8080", nil); err != nil {
            fmt.Println(err)
        }
    }
    
  4. Run the Server:

    go run main.go
    
  5. Access the Server: Open a web browser and go to http://localhost:8080. You should see the message "Welcome to my Go server!" displayed in the browser.

Best Practices for Writing Go Code

Here are some best practices to keep in mind when writing Go code:

  • Conciseness: Write clear and concise code. Avoid unnecessary complexity.
  • Formatting: Go has a built-in tool called gofmt that enforces a consistent code style. Run go fmt to format your code.
  • Testing: Write tests for your code using Go’s built-in testing framework. Create files with a _test.go suffix.
  • Concurrency: Take advantage of Go’s goroutines and channels for concurrent programming.
  • Comments: Use comments to explain your code. Single-line comments start with //, and multi-line comments are enclosed in /* ... */.

Conclusion

Congratulations! You have now learned how to write and run your first Go program. You have learned about setting up your Go environment, writing basic Go code, and creating a simple HTTP server. Go is a powerful and efficient language that is well-suited for building scalable applications. As you continue to learn, you can explore more advanced topics like interfaces, packages, and concurrency.

Check out the official Go documentation for more detailed information and examples.

Happy coding with Go!