Skip to main content

Golang (Go)

Go is an open-source programming language developed by Google, known for its simplicity, efficiency, and strong support for concurrent programming.

Installation on Linux​

This guide covers the installation of Go on a Linux-based system.

  1. Download the latest Go package from the official downloads page.

    curl -OL https://go.dev/dl/go1.22.4.linux-amd64.tar.gz
    warning

    Ensure you download the correct package for your system architecture.

  2. Extract the archive into /usr/local, removing any previous Go installation.

    sudo rm -rf /usr/local/go && sudo tar -C /usr/local -xzf go1.22.4.linux-amd64.tar.gz
  3. Add the Go binary directory to your system's PATH. Add the following line to your ~/.profile or ~/.zshrc file:

    export PATH=$PATH:/usr/local/go/bin
  4. Apply the changes to your current session:

    source ~/.profile
  5. Verify the installation by checking the Go version:

    go version

    The output should display the installed Go version, for example: go version go1.22.4 linux/amd64.

"Hello, World!" Example​

Follow these steps to create and run a simple "Hello, World!" program.

  1. Create a new directory for your project:

    mkdir go-example
    cd go-example
  2. Initialize a new Go module:

    go mod init example/hello
  3. Create a file named hello.go with the following content:

    package main

    import "fmt"

    func main() {
    fmt.Println("Hello, World!")
    }
  4. Run the program:

    go run .

    The output will be: Hello, World!.

Using External Packages​

Go modules allow you to manage dependencies and use third-party packages from sources like pkg.go.dev.

  1. Import an external package in your code. For this example, we use rsc.io/quote:

    package main

    import (
    "fmt"
    "rsc.io/quote"
    )

    func main() {
    fmt.Println(quote.Go())
    }
  2. Run go mod tidy to add the new dependency to your go.mod file and download it:

    go mod tidy
  3. Execute your code to see the output from the external package:

    go run .

Project Structure​

A well-organized project structure is crucial for maintainability. Here are some recommended resources for structuring Go projects:

References​