How to install Go [golang] on Ubuntu Linux

How do I install Golang on Ubuntu Linux for developing apps in Go?

Go programming language (also known as “Golang”) originated at Google by Ken Thompson, Rob Pike, and others. The Go lang syntax shares many similarities with the C programming language but comes with many safety features such as:

  • Free and open source
  • Statically typed
  • Memory safety
  • Garbage collection
  • structural typing
  • CSP-style
  • Python/JS like readability and usability
  • Strong support for mulicore and networked systems
  • Concurrency, and more.

Popular Linux apps such as Docker, Kubernetes, and many more are written in Go. Let us see how to install Go [Golang] Ubuntu Linux.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements Ubuntu Linux
Est. reading time 4 minutes

Warning: Please use only one method to install Golang on Ubuntu.

Installing Golang using snap on Ubuntu (method # 1)

Open the terminal window and then type the following snap command to install the latest Go lang:
$ sudo snap install go --classic
This will install Go programming language compiler, linker, and stdlib. You will see confirmation as follows:

go 1.15.5 from Michael Hudson-Doyle (mwhudson) installedk

Now, jump to testing section.

Using apt-get/apt command to install Go (method # 2)

First, update Ubuntu Linux packages for security and apply pending patches. Run:
$ sudo apt update
$ sudo apt upgrade

Search for Go:
$ sudo apt search golang-go
$ sudo apt search gccgo-go

Install Golang version 1.13 on Ubuntu Linux 20.04 LTS:
$ sudo apt install golang-go
How to install Go [golang] on Ubuntu Linux
It is time to test Go, see testing section below.

How to Install Go binary on Ubuntu from Google (method # 3)

Visit official downloads page and grab file using either wget command or curl command:
# let us download a file with curl on Linux command line #
$ VERSION="1.15.5" # go version
$ ARCH="amd64" # go archicture
$ curl -O -L "https://golang.org/dl/go${VERSION}.linux-${ARCH}.tar.gz"
$ ls -l

Extract the tarball using the tar command:
$ tar -xf "go${VERSION}.linux-${ARCH}.tar.gz"
$ ls -l
$ cd go/
$ ls -l
$ cd ..

Set up the permissions using the chown command/chmod command:
$ sudo chown -R root:root ./go
Use the mv command to move go binary to /usr/local/ directory:
$ sudo mv -v go /usr/local
Finally edit the ~/.profile or ~/.bash_profile:
$ vim ~/.bash_profile
Append the following 2 lines:

# set up Go lang path #
export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin

Save and close the file when using vim. Run the source command into the current bash/shell to load environment variables on Ubuntu:
$ source ~/.bash_profile
$ go version

How to Install Go on Ubuntu Linux 20.04 LTS latest version
Finally, test the installation.

How to display Go version on Ubuntu

Execute the following command:
$ go version

Testing your Go environment by writing simple program

Create a new file called hello.go:
$ vim hello.go
Append the following code:

// Hello Word in Go by Vivek Gite
package main
 
// Import OS and fmt packages
import ( 
	"fmt" 
	"os" 
)
 
// Let us start
func main() {
    fmt.Println("Hello, world!")  // Print simple text on screen
    fmt.Println(os.Getenv("USER"), ", Let's be friends!") // Read Linux $USER environment variable 
}

Compile and run Go program:
$ go run hello.go
Build/compile packages and dependencies:
$ go build hello.go
$ ls -l hello*
$ ./hello

Go lang hello world test programme on ubuntu linux

Basic directory structure (workspace) for your Go project on Ubuntu

First make a directory named go:
$ cd
$ mkdir -p -v go/src/my-project
$ vim go/src/my-project/test.go

Build it:
$ go build go/src/my-project/test.go
Run it:
$ ./test

IDEs for Go software development

I use vim as IDE (integrated development environment) along with vim-go plugin, which provides Go programming language support. But, you may want to use easy to use GUI/TUI based IDEs such as Emacs, Gedit, Nano, GoLand, and others.

Setting up variables in go

The syntax is

// we use var that declares one or more variables with or without type
var name type
var name = value
//shorthand syntax 
name := value
 
// define i
var i int
// set value for i
i = 10
// we can also set value as follows
var y = 5
var msg = "Remote host found."
var foo, bar int = 100, 200
// shorthand syntax
vehicle := "Mercedes"
age := 52
// Bool true or false
var is_job_failed = false
// print it
fmt.Printf("%d %d %s\n", i,y,msg)
fmt.Println(foo)
fmt.Println(age)
fmt.Println(vehicle)

Where type can be int, int32, int64, float32, float64, bool, string and others.

Creating constants is easy in go

We use the const keyword to declare a constant value. We can set it to character, string, boolean, and numeric values. For instance:

// syntax 
const var type = value
// define constant  pi with as float32 with 3.14159 value
const pi float32 = 3.14159
// create constant string variable 
const error_msg string = "Docker is not installed"
fmt.Println(pi)
fmt.Println(error_msg)

Simple for loop in golang

package main
 
import "fmt"
 
func main() {
    // single condition for loop
    m := 1
    for m <= 5 {
        fmt.Printf("Welcome %d times.\n",m)
        m = m + 1
    }
    // classic for loop example 
    for i := 6; i <= 10; i++ {
        fmt.Printf("Welcome %d times.\n",i)
    }
}

Using If and else in go

The syntax is:

if condition {
  // do-something when condition is true
}
else {
  // do-something when condition is false 
}

Here is our go for loop example but with condition added :

package main
import "fmt"
func main() {
    for i := 1; i <= 10; i++ {
        fmt.Printf("Welcome %d times.\n",i)
	// break out of for loop when i is 5
	if i == 5 {
		break
	}
    }
}

In this example, read int number from your keyboard and print message:

package main
 
import "fmt"
 
func main() {
    var n int
    fmt.Print("Enter your number: ")
    fmt.Scanf("%d", &n)
    fmt.Println(n)
    if n >= 0 {
	    fmt.Println("Number is positive")
    } else {
	    fmt.Println("Number is negative")
    }
 
}

Creating array in Go lang

package main
 
import "fmt"
 
func main() {
    // define array named domains as string type
    var domains [2]string
    fmt.Println("current values for array:", domains)
 
    // add value and print it
    domains[0] = "cyberciti.biz"
    fmt.Println("Set value : ", domains)
    fmt.Println("Get value for 0 element : ", domains[0])
    // get array length 
    fmt.Println("Array length : ", len(domains))
    // add one more value 
    domains[1] = "nixcraft.com"
    // use for loop to print our array
    for i := 0; i < len(domains); i++ {
	    fmt.Println("Get value for element ", i, " is ", domains[i])
    }
}

It will produce output as follows:

current values for array: [ ]
Set value :  [cyberciti.biz ]
Get value for 0 element :  cyberciti.biz
Array lenght :  2
Get value for element  0  is  cyberciti.biz
Get value for element  1  is  nixcraft.com

Creating user defined function in Golang

package main
 
import "fmt"
// define function named total that accept int values and returns int 
func total(x int, y int) int {
    return x + y
}
 
func main() {
    // call our function and store result in the answer variable 
    answer := total(10, 20)
    fmt.Println("10 + 20  = ", answer)
    fmt.Println("100 + 500 = ", total(100,500))
}

That is all for now. As you can see from quick examples if you know C or a similar language picking up Go is easy.

Wrapping up

Go lang is a trendy choice for DevOps, large scale distributed systems, cloud workloads, and system programming work. We learned how to install Go on Ubuntu Linux. Both methods #1 and #3 install the latest version of Go. However, I prefer method # 1 as it is fast and easy to use. Check out this webpage and Go Programming Language book by Alan Donovan & Brian Kernighan , which has many hands-on introductions to Go for new developers and Linux sysadmins.


🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 3 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
3 comments… add one
  • Joe Klemmer Dec 2, 2020 @ 13:12

    WRT Basic directory structure (workspace).

    Out of curiosity, why not something like:

    $ mkdir -p ~/src/go/my-project
    $ vim go/src/my-project/test.go

  • jack007 Jan 5, 2021 @ 10:51

    I create a workspace on Ubuntu:
    mkdir hello && cd hello
    Then I create and initialize a Go module:
    go mod init hello
    Finally use IDE to write code. Say a file called main.go in the directory hello I created
    emacs main.go
    Now build it:
    go build
    I have a hello binary in my workspace:
    ls -l hello
    ./hello

  • Nosmo King Apr 23, 2021 @ 19:07

    $ sudo apt search golang-go
    $ sudo apt search gccgo-go

    Install Golang version 1.13 on Ubuntu Linux 20.04 LTS:
    $ sudo apt install golang-go

    $ sudo apt install gccgo #LOL seemed to work

    $ gccgo --version

    gccgo (Ubuntu 10.2.0-5ubuntu1~20.04) 10.2.0
    Copyright (C) 2020 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions.  There is NO
    warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum