Learning a New Programming Language: My Experience with Go
Go programmer Siddhartha Singh explains what makes Go different and when you should consider using it. Using examples of successful Go programs, he shows how easily you can set up the Go environment, build programs, and run them. Rather than just focusing on the syntax, learn the important motivating factors for considering Go as your language of choice.
Getting Ready to 'Go'
Invented at Google, Go was created by the makers of UNIX. The first thing you need to know about Go is that it compiles to machine code. What does this mean? It's ready to replace other compiled languages such as C/C++.
To get started using Go, download the Go distribution. To write Go code, you can use command-line tools, or you can download golangide, an open source IDE written in C++. If you know Eclipse, try the Go plug-in GoClipse.
One very nice feature of Go is its documentation. For example, suppose you run a command like this:
godoc -http=:8081
This will run a web server locally on port 8081. Then type this in your browser:
http://localhost:8081
The documentation for the command is displayed in your browser.
To see help on running the go command, for example, run this:
go --h
To be able to build local programs and packages, the go tool has three requirements:
- The Go bin directory ($GOROOT/bin or %GOROOT%\bin) must be in the path.
- There must be a directory tree with a src directory where the source code for the local programs and packages resides. For example, if you create a directory go under HOME, create a file as ~/go/src/HelloWorld.go, and so on.
- The directory above the src directory must be in the GOPATH environment variable. For example, to build the HelloWorld example I just mentioned by using the go tool, do this:
$ export GOPATH=$HOME/go $ cd $GOPATH/src $ go build
$ ./HelloWorld Hello World!
A 'Hello World' Program in Go
It's a tradition to start with a Hello World program, so here it is, probably the shortest working Go program you can have:
file : HelloWorld.go package main import "fmt" func main() { fmt.Println("Hello, World") }
From a command line (terminal in Linux), you run it like this:
$ go run HelloWorld.go
This command both compiles and runs the program.
Now coming back on track. What factors might cause you to switch to writing in a different programming language? Would it be management's decision, or your own? Several factors motivated me, as described in the following section.
What Motivated Me to Learn Go?
Languages are designed keeping a particular domain in mind, which means one particular language won't fit for all needs. For instance, C/C++ are for systems and/or performance-related programs. PHP is good for building web pages. Java provides platform independence. Similarly, Go is designed for maintaining flexibility when programming for the latest technologies, as well as for writing system programs. Let's examine some of the unique features of Go that help programmers to write scalable, distributed, parallel programs easily—without worrying about installing separate libraries.
Factor 1: Pointers
Pointers have always fascinated me while writing performance-oriented programs in C/C++. With pointers, you know exactly about memory layouts. Go gives the programmer control over which data structure is a pointer and which isn't.
Pointers are important for performance and indispensable if you want to do systems programming, close to the operating system and network. Here's a code sample that shows the usage of pointers:
//file pointer.go package main import "fmt" func main() { var i1 = 5 fmt.Printf("An integer: %d, its location in memory: %p\n", i1, &i1) var intP *int intP = &i1 fmt.Printf("The value at memory location %p is %d\n", intP, *intP) }
Like most other low-level (system) languages, such as C, C++, and D, Go has the concept of pointers. But pointer arithmetic (such as pointer + 2 to go through the bytes of a string or the positions in an array) often leads to erroneous memory access in C, and therefore to fatal program crashes. Go doesn't allow pointer arithmetic, which makes the language memory-safe. Go pointers more resemble the references from languages like Java, C#, and Visual Basic.NET. For example, the following is invalid Go code:
c = *p++
A pointed variable also persists in memory for as long as at least one pointer points to it, which means that the pointer's lifetime is independent of the scope in which it was created. Think of a smart pointer class in C++, which is implemented using reference counting methodology.
Factor 2: Object-Oriented Programming (OOP)
Go is an OO language, but not in the traditional sense, because it doesn't have the concept of classes and inheritance. However, it supports the concept of interfaces, with which a lot of aspects of object orientation can be made available.
An interface defines a set of methods that are abstracts (pure virtual in C++), but these methods don't contain code; that is, they're not implemented. Also, an interface cannot contain variables, and therefore has no context.
The prototype of an interface is as follows:
type Namer interface { Method1(param_list) return_type Method2(param_list) return_type ... }
where Namer is an interface type.
Three important aspects of OO languages are encapsulation, inheritance, and polymorphism. How are these aspects envisioned in Go?
- Encapsulation (data hiding): In contrast to other OO languages with four or more access levels, Go simplifies to only two:
- Package scope: "object" is only known in its own package if it starts with a lowercase letter.
- Exported: "object" is visible outside of its package if it starts with an uppercase letter.
- Inheritance: By composition; that is, embedding of one or more types (I discuss types later in this article) with the desired behavior (fields and methods). Multiple inheritance is possible through embedding multiple types.
- Polymorphism: By interfaces; that is, a variable of a type can be assigned to a variable of any interface it implements. Types and interfaces are loosely coupled; again, multiple inheritance is possible through implementing multiple interfaces. Go's interfaces are not a variant of Java or C# interfaces. They're independent; in other words, they don't know anything about their hierarchy.
A type can only have methods defined in its own package.
How does this work? Let's say you want to implement an "object serializer" to write to different kinds of stream (say, to a file and a network). In languages like Java, you declare different interfaces to it and implement them in a class containing data. For example, in Java:
//File streamer interface interface IFileStreamer { void StreamToFile(); } //Network streamer interface interface INetworkStreamer { void StreamToNetwork(); } // A class StreamWriter to implement these interfaces public class StreamWriter implements IFileStreamer, INetworkStreamer { private String[] mBuf; public void StreamToFile() {} public void StreamToNetwork() {} }
In Go, this will be implemented as described below:
//Go Step 1: Define your data structures type ByteStream struct { mBuffer string } //Go Step 2: Define an interface that could use the data structure we have //File streamer interface type IFileStreamer interface { StreamToFile() } //Network streamer interface type INetworkStreamer interface { StreamToNetwork() } //Go Step 3: Implement methods to work on data func (byteStream ByteStream) StreamToFile() { WriteToFile(byteStream.mBuffer); } func (byteStream ByteStream) StreamToNetwork() { WriteToNetwork(byteStream.mBuffer); }
If you look carefully, it appears to be data-centric; that is, define your data first and build your interface abstractions. Here, hierarchy is kind of built "along the way," without explicitly stating it; depending on the method signatures associated with the type, it's understood as implementing specific interfaces.
To this point, it might seem that there isn't much difference. But wait: Consider a case where you get a requirement to add one more stream, called a memory stream. In the case of Java, you would have to declare another interface and implement it in the class. That is, you would have to touch the existing class:
interface IMemoryStreamer { void StreamToMemory(); } public class StreamWriter implements IFileStreamer, INetworkStreamer, IMemoryStreamer { ... //Implement the new function void StreamToMemory() {} }
Here comes the benefit of Go: You don't have to change the data class. Just write one more function with the type ByteStream:
func (byteStream ByteStream) StreamToMemory() { WriteToMemory(byteStream.mBuffer); }
This is a shift in the concept of traditional object orientation.
Factor 3: Built-in Concurrency Support
Go adheres to a paradigm known as Communicating Sequential Processes (CSP, invented by C.A.R. Hoare), also called the message, which is already available in Erlang. To execute tasks in parallel, you have to write "Go routines."
Goroutines
Asynchronous function call. Just prefix the function call with the word go. No prior knowledge is required at the time of function declaration. Return values, if any, will be discarded. No way exists to kill spawned goroutines. However, they are all killed when main() exits.
Channels
Go uses channels to synchronize goroutines. A channel is type-safe duplex FIFO, synchronized across goroutines. The syntax looks like this:
<- chn to read; chn <- to write
It reads/writes blocks until the data (command) is available.
Select Statements
Like a switch, except it's for channel I/O. It picks up one ready channel I/O operation from several ready/blocked operations. Non-blocking I/O is possible using the default: option. For example:
package main import ( "fmt" "math/rand" "time" ) func consumer(c1, c2 chan int) { timeout := time.After(time.Second*5) for { var i int select { case i = <-c1: fmt.Println("Producer 1 yielded", i) case i = <-c2: fmt.Println("Producer 2 yielded", i) case <- timeout: return default: time.Sleep(time.Second) } } } func producer(c chan int) { for i := 0; i < 10; i++ { c <- rand.Int() } } func main() { c1, c2 := make(chan int), make(chan int) go producer(c1) // go routine, prefix 'go' go producer(c2) // go routine, prefix 'go' consumer(c1, c2) }
Factor 4: Garbage Collection
Oh! So no memory leaks! Great!! The Go developer doesn't have to code to release the memory for variables and structures that are not used in the program. A separate process in the Go runtime, the garbage collector, takes care of that problem: It searches for variables that are not listed anymore and frees that memory.
Functionality for this process can be accessed via the runtime package. Garbage collection can be called explicitly by invoking the function runtime.GC(), but this is only useful in rare cases, such as when memory resources are scarce, a large chunk of memory could immediately be freed at that point in the execution, and the program takes only a momentary decrease in performance (for the garbage collection-process).
Factor 5: Error Handling Through Multiple Return Values
Go has no exception mechanism, like the try/catch in Java or .NET; you cannot throw exceptions. Instead it has a defer, panic, and recover mechanism.
There are two primary paradigms today in native languages for handling errors: return codes, as in C, or exceptions, as in OO alternatives. Of the two, return codes are the more frustrating option, because returning error codes often conflicts with returning other data from the function. Go solves this problem by allowing functions to return multiple values. One value returned is of type error and can be checked anytime a function returns. If you don't care about the error value, you don't check it. In either case, the regular return values of the function are available to you.
Factor 6: Web Programming
In today's world, we need help from a language to write web-based programs. The trend is to write APIs that are REST-based.
HTML Templates
Go has extremely good and safe support for HTML templates, which are data-driven and make templates suitable for web programming. The package template (html/template) is used for generating HTML output that's safe against code injection.
Writing a Standalone Web Server
It's easy to write a web server in Go:
package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hurray, how good is : %s!", r.URL.Path[1:]) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8000", nil) }
When you run this program and type the URL in your browser,
http://localhost:8000/Go
you should see this response:
Hurray, how good is : Go!
Conclusion
I think this one article has been sufficient to give you a feeling of how Go works. Many other features are also available—expandable arrays, hash maps, etc., make Go extremely good for writing programs. Enjoy them as you get ready to "go"!