Install Go on Raspberry Pi

Install Go on Raspberry Pi

Go is a programming language developed by Google. It's an open-source, statically typed, compiled language.

This tutorial shows how to install Go on Raspberry Pi.

Install Go

Connect to Raspberry Pi via SSH. Execute the following command to download the latest version of Go from official website:

curl -o go.tar.gz "https://dl.google.com/go/$(curl -sS https://go.dev/VERSION?m=text | head -n1).linux-armv6l.tar.gz"

Extract the downloaded tar.gz file to the /usr/local directory:

sudo tar xf go.tar.gz -C /usr/local

We need to specify where Go binaries are located. Add /usr/local/go/bin directory to the PATH environment variable. This variable can be set in /etc/profile file. In this case, Go will be available for all users as a system-wide command. This can be done by using the following command:

echo 'export PATH=$PATH:/usr/local/go/bin' | sudo tee -a /etc/profile

To make changes to take effect, logout and login to Raspberry Pi. Or, we can apply the changes immediately by running the following command:

source /etc/profile

Now check Go version:

go version

The GOPATH environment variable specifies the location of the workspace. By default, GOPATH is set to $HOME/go directory. So, create the go directory in your home directory:

mkdir ~/go

The tar.gz file is no longer needed, remove it:

rm -rf go.tar.gz

Testing Go

Inside the workspace, create a new project and navigate to it:

mkdir -p ~/go/src/hello && cd ~/go/src/hello

Create the main.go file:

nano main.go

Once the file is opened, add the following code:

~/go/src/hello/main.go

package main

import "fmt"

func main() {
    fmt.Printf("Hello world\n")
}

Execute the go run command to test the program:

go run main.go

We can build the program by using go build command:

go build main.go

This command will build an executable file main. Run it as follows:

./main

Uninstall Go

If you want to completely remove Go, delete the installation directory:

sudo rm -rf /usr/local/go

Remove entry from /etc/profile file:

sudo sed -i '/export PATH=\$PATH:\/usr\/local\/go\/bin/d' /etc/profile

We can also remove the workspace and cache directories:

rm -rf ~/go
rm -rf ~/.cache/go-build

Leave a Comment

Cancel reply

Your email address will not be published.