By Mark Summerfield, Published May 4, 2012 by Addison-Wesley Professional. Part of the Developer's Library series. Copyright 2012

Book ISBN-10: 0-321-77463-9 ISBN-13: 978-0-321-77463-7.

Mark Summerfield provides a series of five explained examples of the Go programming language. Although the examples are tiny, each of them (apart from "hello who?") does something useful, and between them they provide a rapid overview of Go's key features and some of its key packages.

  • 1.1. Getting Going ? 7
  • 1.2. Editing, Compiling, and Running ? 9
  • 1.3. Hello Who? ? 14
  • 1.4. Big Digits-Two-Dimensional Slices ? 16
  • 1.5. Stack-Custom Types with Methods ? 21
  • 1.6. Americanise-Files, Maps, and Closures ? 29
  • 1.7. Polar to Cartesian-Concurrency ? 40

This chapter provides a series of five explained examples. Although the examples are tiny, each of them (apart from “Hello Who?”) does something useful, and between them they provide a rapid overview of Go’s key features and some of its key packages. (What other languages often call “modules” or “libraries” are called packages in Go terminology, and all the packages supplied with Go as standard are collectively known as the Go standard library.) The chapter’s purpose is to provide a flavor of Go and to give a feel for the scope of what needs to be learned to program successfully in Go. Don’t worry if some of the syntax or idioms are not immediately understandable; everything shown in this chapter is covered thoroughly in subsequent chapters.

Learning to program Go the Go way will take a certain amount of time and practice. For those wanting to port substantial C, C++, Java, Python, and other programs to Go, taking the time to learn Go-and in particular how its object-orientation and concurrency features work-will save time and effort in the long run. And for those wanting to create Go applications from scratch it is best to do so making the most of all that Go offers, so again the upfront investment in learning time is important-and will pay back later.

1.1. Getting Going

Go programs are compiled rather than interpreted so as to have the best possible performance. Compilation is very fast-dramatically faster than can be the case with some other languages, most notably compared with C and C++.

The Go Documentation

Go’s official web site is golang.org which hosts the most up-to-date Go documentation. The “Packages” link provides access to the documentation on all the Go standard library’s packages-and to their source code, which can be very helpful when the documentation itself is sparse. The “Commands” link leads to the documentation for the programs distributed with Go (e.g., the compilers, build tools, etc.). The “Specification” link leads to an accessible, informal, and quite thorough Go language specification. And the “Effective Go” link leads to a document that explains many best practices.

The web site also features a sandbox in which small (somewhat limited) Go programs can be written, compiled, and run, all online. This is useful for beginners for checking odd bits of syntax and for learning the Go fmt package’s sophisticated text formatting facilities or theregexppackage’s regular expression engine. The Go web site’s search box searches only the Go documentation; to search for Go resources generally, visit go-lang.cat-v.org/go-search.

The Go documentation can also be viewed locally, for example, in a web browser. To do this, run Go’s godoc tool with a command-line argument that tells it to operate as a web server. Here’s how to do this in a Unix console (xterm, gnome-terminal, konsole, Terminal.app, or similar):

$ godoc -http=:8000

Or in a Windows console (i.e., a Command Prompt or MS-DOS Prompt window):

C:\>godoc -http=:8000

The port number used here is arbitrary-simply use a different one if it conflicts with an existing server. This assumes that godoc is in your PATH.

To view the served documentation, open a web browser and give it a location of http://localhost:8000. This will present a page that looks very similar to the golang.org web site’s front page. The “Packages” link will show the documentation for Go’s standard library, plus any third-party packages that have been installed under GOROOT. If GOPATH is defined (e.g., for local programs and packages), a link will appear beside the “Packages” link through which the relevant documentation can be accessed. (The GOROOT and GOPATH environment variables are discussed later in this chapter and in Chapter 9.)

It is also possible to view the documentation for a whole package or a single item in a package in the console using godoc on the command line. For example, executing godoc image NewRGBA will output the documentation for the image.NewRGBA() function, and executing godoc image/pngwill output the documentation for the entire image/png package.

The standard Go compiler is called gc and its toolchain includes programs such as 5g, 6g, and 8g for compiling, 5l, 6l, and 8l for linking, and godoc for viewing the Go documentation. (These are 5g.exe, 6l.exe, etc., on Windows.) The strange names follow the Plan 9 operating system’s compiler naming conventions where the digit identifies the processor architecture (e.g., “5” for ARM, “6” for AMD64-including Intel 64-bit processors-and “8” for Intel 386.) Fortunately, we don’t need to concern ourselves with these tools, since Go provides the high-level go build tool that handles the compiling and linking for us.

All the examples in this book-available from http://www.qtrac.eu/gobook.html-have been tested using gc on Linux, Mac OS X, and Windows using Go 1. The Go developers intend to make all subsequent Go 1.x versions backward compatible with Go 1, so the book’s text and examples should be valid for the entire 1.x series. (If incompatible changes occur, the book’s examples will be updated to the latest Go release, so as time goes by, they may differ from the code shown in the book.)

To download and install Go, visit golang.org/doc/install.html which provides instructions and download links. At the time of this writing, Go 1 is available in source and binary form for FreeBSD 7+, Linux 2.6+, Mac OS X (Snow Leopard and Lion), and Windows 2000+, in all cases for Intel 32-bit and AMD 64-bit processor architectures. There is also support for Linux on ARM processors. Go prebuilt packages are available for the Ubuntu Linux distribution, and may be available for other Linuxes by the time you read this. For learning to program in Go it is easier to install a binary version than to build Go from scratch.

Programs built with gc use a particular calling convention. This means that programs compiled with gc can be linked only to external libraries that use the same calling convention-unless a suitable tool is used to bridge the difference. Go comes with support for using external C code from Go programs in the form of the cgo tool (golang.org/cmd/cgo), and at least on Linux and BSD systems, both C and C++ code can be used in Go programs using the SWIG tool (http://www.swig.org).

In addition to gc there is also the gccgo compiler. This is a Go-specific front end to gcc (the GNU Compiler Collection) available for gcc from version 4.6. Like gc, gccgo may be available prebuilt for some Linux distributions. Instructions for building and installing gccgo are given atgolang.org/doc/gccgo_install.html.

1.2. Editing, Compiling, and Running

Go programs are written as plain text Unicode using the UTF-8 encoding.1 Most modern text editors can handle this automatically, and some of the most popular may even have support for Go color syntax highlighting and automatic indentation. If your editor doesn’t have Go support, try entering the editor’s name in the Go search engine to see if there are suitable add-ons. For editing convenience, all of Go’s keywords and operators use ASCII characters; however, Go identifiers can start with any Unicode letter followed by any Unicode letters or digits, so Go programmers can freely use their native language.

Go Shebang Scripts

One side effect of Go's fast compilation is that it makes it realistic to write Go programs that can be treated as shebang #! scripts on Unix-like systems. This requires a one-off step of installing a suitable tool. At the time of this writing, two rival tools provide the necessary functionality:gonow (github.com/kless/gonow), and gorun (wiki.ubuntu.com/gorun).

Once gonow or gorun is available, we can make any Go program into a shebang script. This is done with two simple steps. First, add either #!/usr/bin/env gonow or #!/usr/bin/env gorun, as the very first line of the .go file that contains the main() function (in package main). Second, make the file executable (e.g., with chmod +x). Such files can only be compiled by gonow or gorun rather than in the normal way since the #! line is not legal in Go.

When gonow or gorun executes a .go file for the first time, it will compile the file (extremely fast, of course), and then run it. On subsequent uses, the program will only be recompiled if the .go source file has been modified since the previous compilation. This makes it possible to use Go to quickly and conveniently create various small utility programs, for example, for system administration tasks.

To get a feel for how we edit, compile, and run a Go program we’ll start with the classic “Hello World” program-although we’ll make it a tiny bit more sophisticated than usual. First we will discuss compiling and running, then in the next section we will go through the source code-in file hello/hello.go-in detail, since it incorporates some basic Go ideas and features.

All of the book’s examples are available from http://www.qtrac.eu/gobook.html and unpack to directory goeg. So file hello.go’s full path (assuming the examples were unpacked in the home directory-although anywhere will do) is $HOME/goeg/src/hello/hello.go. When referring to files the book always assumes the first three components of the path, which is why in this case the path is given only as hello/hello.go. (Windows users must, of course, read “/”s as “\”s and use the directory they unpacked the examples into, such as C:\goeg or %HOMEPATH%\goeg.)

If you have installed Go from a binary package or built it from source and installed it as root or Administrator, you should have at least one environment variable, GOROOT, which contains the path to the Go installation, and your PATH should now include $GOROOT/bin or %GOROOT%\bin. To check that Go is installed correctly, enter the following in a console (xterm, gnome-terminal, konsole, Terminal.app, or similar):

$ go version

Or on Windows in an MS-DOS Prompt or Command Prompt window:

C:/>go version

If you get a “command not found” or “‘go’ is not recognized...” error message then it means that Go isn’t in the PATH. The easiest way to solve this on Unix-like systems (including Mac OS X) is to set the environment variables in .bashrc (or the equivalent file for other shells). For example, the author’s .bashrc file contains these lines:

export GOROOT=$HOME/opt/go
export PATH=$PATH:$GOROOT/bin

Naturally, you must adjust the values to match your own system. (And, of course, this is only necessary if the go version command fails.)

On Windows, one solution is to create a batch file that sets up the environment for Go, and to execute this every time you start a console for Go programming. However, it is much more convenient to set the environment variables once and for all through the Control Panel. To do this, click Start (the Windows logo), then Control Panel, then System and Security, then System, then Advanced system settings, and in the System Properties dialog click the Environment Variables button, then the New... button, and add a variable with the name GOROOT and a suitable value, such as C:\Go. In the same dialog, edit the PATH environment variable by adding the text ;C:\Go\bin at the end-the leading semicolon is vital! In both cases replace the C:\Go path component with the actual path where Go is installed if it isn’t C:\Go. (Again, this is only necessary if thego version command failed.)

From now on we will assume that Go is installed and the Go bin directory containing all the Go tools is in the PATH. (It may be necessary-once only-to open a new console window for the new settings to take effect.)

Two steps are required to build Go programs: compiling and linking.2 Both of these steps are handled by the go tool which can not only build local programs and packages, but can also fetch, build, and install third-party programs and packages.

For the go tool to be able to build local programs and packages, there are three requirements. First, the Go bin directory ($GOROOT/bin or %GOROOT%\bin) must be in the path. Second, there must be a directory tree that has an src directory and under which the source code for the local programs and packages resides. For example, the book’s examples unpack to goeg/src/hello, goeg/src/bigdigits, and so on. Third, the directory above the src directory must be in the GOPATH environment variable. For example, to build the book’s hello example using the go tool, we must do this:

$ export GOPATH=$HOME/goeg
$ cd $GOPATH/src/hello
$ go build

We can do almost exactly the same on Windows:

C:\>set GOPATH=C:\goeg
C:\>cd %gopath%\src\hello
C:\goeg\src\hell0>go build

In both cases we assume that the PATH includes $GOROOT/bin or %GOROOT%\bin. Once the go tool has built the program we can run it. By default the executable is given the same name as the directory it is in (e.g., helloon Unix-like systems and hello.exe on Windows). Once built, we can run the program in the usual way.

$ ./hello
Hello World!

Or:

$ ./hello Go Programmers!
Hello Go Programmers!
    

On Windows it is very similar:

C:\goeg\src\hello>hello Windows Go Programmers!
Hello Windos Go Programmers!

We have shown what must be typed in bold and the console’s text in roman. We have also assumed a $ prompt, but it doesn’t matter what it is (e.g., C:\>).

Note that we do not need to compile-or even explicitly link-any other packages (even though as we will see, hello.go uses three standard library packages). This is another reason why Go programs build so quickly.

If we have several Go programs, it would be convenient if all their executables could be in a single directory that we could add to our PATH. Fortunately, the go tool supports this as follows:

$ export GOPATH=$HOME/goeg
$ cd $GOPATH/src/hello
$ go install

Again, we can do the same on Windows:

C:>set GOPATH=C/goeg
C:>cd %gopath%/src/hello
C:\goeg\src\hello>go install

The go install command does the same as go build only it puts the executable in a standard location ($GOPATH/bin or %GOPATH%\bin). This means that by adding a single path ($GOPATH/bin or %GOPATH%\bin) to our PATH, all the Go programs that we install will conveniently be in the PATH.

In addition to the book’s examples, we are likely to want to develop our own Go programs and packages in our own directory. This can easily be accommodated by setting the GOPATH environment variable to two (or more) colon-separated paths (semicolon-separated on Windows); for example, export GOPATH=$HOME/app/go:$HOME/goeg or SET GOPATH=C:\app\go;C:\goeg. 3 In this case we must put all our program and package’s source code in $HOME/app/go/src or C:\app\go\src. So, if we develop a program called myapp, its .go source files would go in$HOME/app/go/src/myapp or C:\app\go\src\myapp. And if we use go install to build a program in a GOPATH directory where the GOPATH has two or more directories, the executable will be put in the corresponding directory’s bin directory.

Naturally, it would be tedious to export or set the GOPATH every time we wanted to build a Go program, so it is best to set this environment variable permanently. This can be done by setting GOPATH in the .bashrc file (or similar) on Unix-like systems (see the book’s example’s gopath.shfile). On Windows it can be done either by writing a batch file (see the book’s example’s gopath.bat file), or by adding it to the system’s environment variables: Click Start (the Windows logo), then Control Panel, then System and Security, then System, then Advanced system settings, and in the System Properties dialog click the Environment Variables button, then the New... button, and add a variable with the name GOPATH and a suitable value, such as C:\goeg or C:\app\go;C:\goeg.

Although Go uses the go tool as its standard build tool, it is perfectly possible to use make or some of the modern build tools, or to use alternative Go-specific build tools, or add-ons for popular IDEs (Integrated Development Environments) such as Eclipse and Visual Studio.

Continue reading this article here: http://www.informit.com/articles/article.aspx?p=1856388