minutes to read

 Companion Repo:

Author: A. J. Saulsberry


TechnologySkill Level
GoBeginner
PowerShell (optional)Beginner
Visual Studio CodeBeginner

This article includes links to external websites. These links are covered by the Disclaimer.

The Go programming language is an open source project begun in 2009 by a team at Google that wanted to provide a fast, modern language that has built-in support for the kinds of concurrency tasks that are a ubiquitous part of Google's computing environment: concurrent tasks running on multiple processor cores in multiple processors on multiple machines in multiple locations. The language is designed to address many of the frustrations and inefficiencies associated with programming in C++ and Java without imposing the risks associated with dynamically-typed languages like JavaScript and Python.

Go has been used for a number of projects, including the Caddy open source web server and the Docker container platform. Go has been adopted by a number of large companies with demanding IT requirements, including CloudFlare, Dropbox, Netflix, Novartis and, of course, Google. Since Go's inception the project has benefited from the contributions of many members of the open source community.

Some of the highlights of Go's design are:

  • fast compilation and execution,
  • static typing,
  • automatic garbage collection, and
  • built-in support for concurrent programming.

The Go FAQ and the Wikipedia entry, Go programming language, provide extensive background on the language's objectives, features, and conventions.

Why learn Go?

For developers who program primarily in strongly-typed languages like C# or Java, or dynamically-typed languages like JavaScript or Python, Go programming will be different in a number of important respects. Learning to write Go well will enable new ways of thinking about programming problems and solutions, particularly in relation to processing tasks that benefit from concurrent processing.

Go can be used for quotidian projects like building a website as well as more esoteric endeavors like working with large data sets on globally distributed databases. Go is supported on Linux variants, macOS, and Windows, so Go programs can be deployed to a variety of physical and virtual platforms.

Installing Go is easy. It doesn't take up a lot of space and it doesn't install yet another background process to suck away precious CPU cycles.

How is Go different?

Go has some notable differences from other languages. In particular, the Go language compiles to machine code rather than bytecode or an intermediate language and it does not use a virtual machine or virtual execution system.

In the interest of making programming in Go faster and more expressive than other languages, Go does not have a number of features common to C, C++, C#, Java, and other object-oriented languages. Go does not have:

  • header files,
  • type hierarchy,
  • inheritance,
  • generic types,
  • operator and method overloading, or
  • exceptions.

It may seem that the absence of these features limits the range of programming that can be done effectively with Go. In practice, it is liberating: Go provides alternative approaches that reduce the amount of programmatic bookkeeping associated with code. Go provides:

  • a lightweight definition of interfaces that enables a type to satisfy an interface if it implements one or more of the interface's methods;

  • a package system that combines features of libraries, namespaces, and modules into a single construct;

  • scope control through a naming convention rather than keywords; and

  • functions that can return multiple values, including an error type.

Go does not require an integrated development environment (IDE) to program, but it is supported by a wide variety of editors and IDE's. The Go Wiki on GitHub provides an extensive list of compatible programs.

Fortunately, spending time reviewing the IDE options isn't necessary. For a pleasant and effective solution, read on.

Why use VS Code with Go?

Visual Studio Code is a great polyglot editor that combines a clean, highly configurable, editing interface with an extensive ecosystem of plugins that provide support for a wide variety of programming languages and file types. Developers who already use VS Code for software development can leverage their skill to program in Go as well.

The Go for Visual Studio Code extension provides rich language support for Go in VS Code, including:

  • Type-aware IntelliSense autocompletion,
  • debugger support,
  • linting,
  • snippets,
  • CodeLens references,
  • automatic test class generation,
  • formatting on save,
  • building on save, and
  • many other features.

Mascot

The Go gopher is the official mascot of the Go language. It was designed by Renée French and is usually blue these days, although the documentation is silent on the question of an official color.

Go gopher by Renée French

Installing Go

On to the fun part! Follow these instructions to get going with Go.

This is a Windows-centric set of instructions for developers intending to use Go with Visual Studio Code. macOS and Linux users can substitute the typical alternatives particular to their operating system. The complete installation instructions can be found at: https://golang.org/doc/install.

The Go installation installs the executables for a number of command line programs, documentation, sample code, and tests.

Prerequisites

Before beginning, verify the target system for the install has:

  • a reliable internet connection with decent bandwidth,
  • 500 MB of free mass storage space, and
  • Visual Studio 1.19.3 or higher installed.

Go System Requirements

Go has very modest system requirements for this day and age:

  • Windows XP SP3 or higher,
  • Intel 64-bit processor.

For macOS and Linux flavors, see the current system requirements here.

Running the installer

Uninstall any previously installed version of Go before beginning.

  1. Download the installer from https://golang.org/dl.

    The downloaded file should be something like:

    go1.9.3.windows-amd64.msi (94 MB)

  2. Run the installer as Administrator.

The installer will create a new directory off the root of the current system drive:

C:\Go

Note the uppercase "G". Casing is important in Go, so it is best to accept this default.

The installer will also add the following to the machine environment path:

C:\Go\bin

Verify the path was modified successfully by executing the following command at a PowerShell prompt:

Get-ChildItem env:path | format-list

The Go path may not be appended to the very end of the path, so it may be necessary to scan the entire path carefully to confirm the addition has been made.

Creating the Go workspace

The Go workspace is the place for all the source code and compiled applications created on a specific system. Because paths are part of the identity of packages in Go, the folder structure of the workspace is important and should conform to certain rules.

The Go workspace is installed at the root of the current user's profile. The user profile is typically found in the Users folder of the system drive, like this:

C:\Users\Dave Bowman

  1. Identify the current user profile path by opening a PowerShell window and executing the following command:
Get-ChildItem env:userprofile

The results should be the same regardless of whether the PowerShell window is run under the current user account or as Administrator.

  1. Create the go directory in the user profile by executing the following PowerShell command:
New-Item -ItemType "directory" -Path $((Get-Item env:userprofile).value + "\go")

Alternately, this can be done from the Windows command prompt by executing the following commands:

> cd %userprofile%
> md go

The result should be something like this:

C:\Users\Dave Bowman\go

The name of the current user (user profile) should appear in the place of the name of the astronaut/starchild.

Testing the installation

Do not skip this step: it does important configuration work.

  1. Using any appropriate tool, create a "hello" directory under the "go" directory.

  2. Using a text editor, create a file named "hello.go" in the hello directory.

  3. Enter the following text in the file and save it.

package main

import "fmt"
func main() {
    fmt.Printf("hello, world\n")
}
  1. Open a PowerShell or command prompt window in the "hello" directory and execute the following command:

go build

  1. Execute the following command:

hello

The command line output should be:

hello, world

There will also be three new directories under the go directory:

bin
pkg
src

If all the above occurs as expected (and it's highly likely that it will) Go has been installed correctly.

Setting environment variables

There are two additions to the user environment that make working with Go much easier:

  1. the GOPATH user environment variable and
  2. the addition of %USERPROFILE%\go\bin directory to the PATH variable for the user.

Note that these user environment variables are in addition to the addition to the machine PATH environment variable added when the Go installer was run.

Make these changes as follows:

GOPATH user environment variable

Important: These instructions include modifications to the Windows Registry. It is always a good idea to make a Registry backup or create a System Restore Point before making changes to the Registry.

Open a PowerShell window and execute the following commands:

New-Item -Path 'Registry::HKEY_CURRENT_USER\Environment' -Name GOPATH -Value $((Get-Item env:userprofile).value + "\go")

The result displayed should be something like this if the command completed successfully:

    Hive: HKEY_CURRENT_USER\Environment

Name                           Property
----                           --------
GOPATH                         (default) : C:\Users\Dave Bowman\go

— Or —

Perform the following actions from the user interface:

  1. Start (button) > Windows System (folder) > Control Panel (program).
  2. Select System and Security, then click on System.
  3. From the menu on the left, select Advanced systems settings.
  4. Click the Environment Variables button at the bottom.
  5. Click New from the User variables section.
  6. Type "GOPATH" into the Variable name field.
  7. Type "%USERPROFILE%\go" into the Variable value field.
  8. Click OK to close the New User Variable dialog box.
  9. Click OK to close the *Environment Variables dialog box.
  10. Click OK to close the System Properties dialog box.

To verify the path was set correctly execute the following command at a PowerShell prompt :

Get-ChildItem env:gopath

The results should look something like this:

Name                           Value
----                           -----
GOPATH                         C:\Users\Dave Bowman\go

Again, the user/profile name of the logged in user should appear in place of the name of the intrepid Discovery crew member.

Go workspace bin path

The third environment variable Go needs is the addition of the go\bin directory in the Go workspace to the PATH environment variable for the user.

$oldpath = (Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Environment' -Name PATH).path
$newpath = $($oldpath;(get-item env:userprofile).value + "\go\bin")
Set-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Environment' -Name PATH -Value $newPath

— Or —

Perform the following actions from the user interface:

  1. Start (button) > Windows System (folder) > Control Panel (program).
  2. Select System and Security, then click on System.
  3. From the menu on the left, select Advanced systems settings.
  4. Click the Environment Variables button at the bottom.
  5. Select Path from the User variables section.
  6. Click Edit immediately below the User variables section.
  7. Click New.
  8. Type "%USERPROFILE%\go\bin" into the new field at the bottom of the list.
  9. Click OK to close the Edit Environment variable dialog box.
  10. Click OK to close the Environment Variables dialog box.
  11. Click OK to close the System Properties dialog box.

To verify the path was set correctly close any open PowerShell windows, open a new PowerShell window, and execute the following PowerShell command:

($env:path).split(";")

The result should be something like:

Ellipsis (...) indicate redactions for brevity and clarity.

C:\WINDOWS\system32
C:\WINDOWS
...
C:\Go\bin
...
C:\Users\Dave Bowman\AppData\Local\Code\bin
...
C:\Users\Dave Bowman\go\bin

Both the \Go\bin and the Go workspace go\bin paths appear as part of the user environment PATH parameter.

Setting up VS Code for Go

Now that Go has been installed, the Go workspace has been created, and all the necessary environment variables set, it is time to configure Visual Studio Code for Go support.

If Visual Studio Code has not already been installed, it can be downloaded from https://code.visualstudio.com/download Downloads are available for Windows, Linux (Debian, Ubuntu, Red Hat, Fedora, and SUSE), and macOS 10.9+.

Installing the Go extension

Start Visual Studio Code and open the Extensions pane (Ctrl + Shift + X). The top of the pane should read "EXTENSIONS: MARKETPLACE".

Type "go lang" in the search box.

The first result should be Go 0.6.76 (or higher) by lukehoban. Select this extension. A window will appear with the extension information. If the number of downloads is more than 2,500,000 this is the correct extension.

Click the green Install button. The extension should install.

When the extension is finished installing, click the blue Reload button.

The Go extension should appear in the list of INSTALLED extensions in the Extensions pane.

Installing Go packages

The Go extension for Visual Studio Code makes use of a number of Go command line tools. They are not installed with the extension, but there is an installation process that provides a convenient way of adding them to the configuration.

  1. Open Visual Studio Code.

  2. Select File > Open Folder... (Ctrl + K Ctrl + O)

  3. Navigate to go\src\hello and select Open Folder.... Note that the "go" folder to open is the workspace folder, not the "Go" (uppercase "G") folder off the root of the system drive.

  4. In the VS Code Explorer pane, expand the Hello folder and click on the hello.go file. A new editor window should open and display the contents of the hello.go file created earlier in these instructions.

  5. VS Code should display a notification box at the top of the editor window that says:

    The "gopkgs" command is not available. Use "go get -v github.com/uudashr/gopkgs/cmd/gopkgs" to install.

    Click the blue Install All button.

    An output pane should appear below the editor window. The following will appear:

     Installing 10 tools at C:\Users\Dave Bowman\go\bin
         gocode
         gopkgs
         go-outline
         go-symbols
         guru
         gorename
         godef
         goreturns
         golint
         dlv
    
         Installing github.com/nsf/gocode SUCCEEDED
         Installing github.com/uudashr/gopkgs/cmd/gopkgs SUCCEEDED
         Installing github.com/ramya-rao-a/go-outline SUCCEEDED
         Installing github.com/acroca/go-symbols SUCCEEDED
         Installing golang.org/x/tools/cmd/guru SUCCEEDED
         Installing golang.org/x/tools/cmd/gorename SUCCEEDED
         Installing github.com/rogpeppe/godef SUCCEEDED
         Installing sourcegraph.com/sqs/goreturns SUCCEEDED
         Installing github.com/golang/lint/golint SUCCEEDED
         Installing github.com/derekparker/delve/cmd/dlv SUCCEEDED
    
         All tools successfully installed. You're ready to Go :).
    

To confirm that the installation completed successfully, perform the following steps:

  1. Close the hello.go editor window, then close and reopen Visual Studio Code.

  2. Re-open the hello folder.

  3. Open an Output window (Ctrl + Shift + U)

  4. Open the hello.go file.

    The Output window should display the following:

     Finished running tool: C:\Users\Dave Bowman\go\bin\golint.exe
     Finished running tool: C:\Go\bin\go.exe build -i -o C:\Users\DAVE~1.BOW\AppData\Local\Temp\go-code-check hello
     Finished running tool: C:\Go\bin\go.exe vet ./...
    

If the output shown above appears (adjusted for the current user's profile), the installation has completed successfully and the VS Code Go extension can find all the tooling in the system drive \Go\bin directory and the current user's workspace go\bin directory. VS Code is now configured for Go development.

Learning Go

For developers new to Go, the next step is learning the language. Because Go offers new ways of handling a variety of programming tasks, it's worth taking the time to create a solid foundation for developing in Go. There are three recommended steps in the process, a guided tour and two documents:

Go Guided Tour - The tour can be used online or downloaded and executed locally. See below for instructions. The download contains a Git repository of the source code used in the tour, making it convenient to follow along in VS Code and revert the code to its original state.

How to write Go code - This document provides a walk-through of creating a Go package and provides essential information about organizing code properly. It includes an explanation of the purpose of the directories created during the installation process.

Effective Go - The third must-read document, Effective Go provides coding standards and explains coding best practices.

Taken together, these resources can be gotten through in about the time it takes to fly from Boston to San Francisco. For best results while airborne, be sure to download the tour before boarding.

Further learning and news

The Go Wiki - a community repository of Go knowledge, including an extensive list of books, documents, classroom courses, online training, and other resources for learning Go.

FAQ - frequently asked questions about Go.

Official Go blog - The Go blog provides announcements about new releases and other developments in the Go world, including projects developed with Go. It's a great source of links to more information.

golang-announce Google Group - Follow this group to receive notifications of new releases.

Installing the tour locally

To install the Go tour locally and make air travel more productive and pleasant, follow these short instructions:

  1. Open a PowerShell or command prompt window at the go directory in the current user workspace.

  2. Execute the following command: go get golang.org/x/tour/gotour

    This will install the tour at a location similar to: C:\Users\Dave Bowman\go\src\golang.org\x\tour. The Git repository for the tour code is located here.

  3. Execute the following command: gotour

    This will start a local Go web server, and display the tour in a new browser tab. The command window will contain something like this:

2018/02/16 13:02:19 Serving content from C:\Users\Dave Bowman\go\src\golang.org\x\tour
2018/02/16 13:02:19 A browser window should open. If not, please visit http://127.0.0.1:3999
2018/02/16 13:02:20 accepting connection from: 127.0.0.1:60189

To end the tour and the web server, make the PowerShell or command window active and press Ctrl + C.

It may be convenient to create a shortcut for the tour: C:\Users\Dave Bowman\go\bin\gotour.exe.

Go Reference Material

Language Specification - the canonical documentation for the Go language.

Package Documentation - reference information for Go standard library.

Command Documentation - reference information for the Go command line executables.

The Go Memory Model - essential information for communicating safely between concurrent processes.

The complete list of Go reference material is available at: https://golang.org/doc/.

Disclaimer

The author disclaims all liability for the reliability, accuracy, and completeness of information presented by third-parties.