Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼

Web Development

Go Tutorial: Object Orientation and Go's Special Data Types

Although Go supports object-oriented programming, it provides neither classes nor inheritance (is-a relationships). Go does support the creation of custom types, and Go makes aggregation (has-a relationships) extremely easy. Go also allows for the complete separation of a type's data from its behavior, and supports duck typing. Duck typing is a powerful abstraction mechanism that allows values to be handled (for example, passed to functions) based on the methods they provide, regardless of their actual types. The terminology is derived from the phrase, "If it walks like a duck, and quacks like a duck, it's a duck." This produces a flexible and powerful alternative to the traditional classes and inheritance approach — but it requires those of us used to the more traditional approach to make some significant conceptual adjustments to really benefit from Go's object orientation.

Go represents data using fundamental built-in types such as bool, int, and string, or by aggregations of types using structs. (Unlike C++, Go's structs are not classes in disguise. For example, Go's structs support aggregation and delegation, but not inheritance.) Go's custom types are based on the fundamental types, or on structs, or on other custom types.

Go supports both named and unnamed custom types. Unnamed types with the same structure can be used interchangeably; however, they cannot have any methods. Any named custom type can have methods, and these methods together constitute the type's interface. Named custom types — even with the same structure — are not interchangeable. (Throughout this article, any reference to a "custom type" means a named custom type, unless stated otherwise.)

An interface is a type that can be formally defined by specifying a particular set of methods. Interfaces are abstract and cannot be instantiated. A concrete (that is, non-interface) type that has methods specified by an interface fulfills the interface — that is, values of such a concrete type can be used as values of the interface's type as well as of their own actual type. Yet no formal connection need be established between an interface and a concrete type that provides the methods specified by the interface. It is sufficient for a custom type to have the interface's methods for it to satisfy that interface. And, of course, a type can satisfy more than one interface simply by providing all the methods for all the interfaces we want it to satisfy.

An empty interface (one that has no methods) is specified as interface{}. Go's empty interface can serve the same role as a reference to a Java Object or a C/C++ void.) Since the empty interface makes no demands at all (because it doesn't require any methods), it can stand for any value (much like a pointer to any value), whether the value is of a built-in type or is of a custom type. Incidentally, in Go terminology, we talk about types and values rather than classes and objects or instances (because Go has no classes). Function and method parameters can be of any built-in or custom type — or of any interface type. In the latter case, this means that a function can have a parameter that says, for example, "pass a value that can read data," regardless of what that value's type actually is. (This will be shown in practice shortly.) For now, let's just look at a very simple custom type — a stack — starting with how values are created and used, and then look at the implementation of the custom type itself.

We will start with the output produced by a simple test program:

$ ./stacker 
[pin clip needle] 

Each item was popped from the custom stack and printed on its own line.

The simple test program that produced this output is stacker/stacker.go. Here are the imports it uses:

import ( 

The fmt package is part of Go's standard library, but the stack package is a local package specific to the stacker application. A Go program or package's imports are first searched for under the GOPATH path or paths, and then under GOROOT. In this particular case, the program's source code is in $HOME/goeg/src/stacker/stacker.go and the stack package is in $HOME/goeg/src/stacker/stack/stack.go. The go tool will build both of them so long as the GOPATH is (or includes) the path $HOME/goeg/.

Import paths are specified using UNIX-style "/"s, even on Windows. Every local package should be stored in a directory with the same name as the package. Local packages can have their own packages (like path/filepath), in exactly the same way as the standard library.

Here's the simple test program's main() function that produced the output:

func main() { 
    var haystack stack.Stack 
    haystack.Push([]string{"pin", "clip", "needle"}) 
    for  {
         item, err := haystack.Pop() 
         if err != nil {

The function begins by declaring the haystack variable of type stack.Stack. It is conventional in Go to always refer to types, functions, variables, and other items in packages using the syntax pkg.item, where pkg is the last (or only) component of the package's name. This helps prevent name collisions. We then push some items onto the stack, pop them off, and print each one until there are no more left.

One amazingly convenient aspect of our custom stack is that despite Go's strong typing, we are not limited to storing homogeneous items (items all of the same type), but can freely mix heterogeneous items (items of various types). This is because the stack.Stack type simply stores interface{} items (that is, values of any type) and doesn't care what their types actually are. Of course, when those items are used, then their type does matter. Here, though, we only use the fmt.Println() function, which uses Go's introspection facilities (from the reflect package) to discover the types of the items it is asked to print.

Another nice Go feature illustrated by the code is the for loop with no conditions. This is an infinite loop, so in most situations, we will need to provide a means of breaking out of the loop — for example, using a break statement as in our example, or a return statement. We will see an additional for syntax in the next example.

Go functions and methods can return a single value or multiple values. It is conventional in Go to report errors by returning an error value (of type error) as the last (or only) value returned by a function or method. The custom stack.Stack type respects this convention. Now that we have seen the custom stack.Stack type in use, we are ready to review its implementation (in file stacker/stack/stack.go).

package stack
import "errors"
type Stack []interface{}

The file starts conventionally by specifying its package name. Then it imports other packages it needs — in this case, just errors. When we define a named custom type in Go, what we are doing is binding an identifier (the type's name) to a new type that has the same underlying representation as an existing (built-in or custom) type — and which is treated by Go as different from the underlying representation. Here, the Stack type is a new name for a slice (a reference to a variable-length array) of interface{} values — and is considered to be different from a plain []interface{}. Because all Go types satisfy the empty interface, values of any type can be stored in a Stack.

The built-in collection types (maps and slices), communication channels (which can be buffered), and strings can all return their length (or buffer size) using the built-in len() function. Similarly, slices and channels can also report their capacity (which may be greater than the length being used) using the built-in cap() function. It is conventional for custom collection types — our own, and those in the Go standard library — to support corresponding Len() and Cap() methods when these make sense. Since the Stack type uses a slice for its underlying representation, it makes sense to provide Stack.Len() and Stack.Cap() methods for it.

func (stack Stack) Len() int {
     return len(stack)

Both functions and methods are defined using the func keyword. However, in the case of methods, the type of value to which the method applies is written after the func keyword and before the method's name, enclosed in parentheses. After the function or method's name comes a — possibly empty — parenthesized list of comma-separated parameters (each written in the form variableNametype). After the parameters comes the function or method's opening brace (if it has no return value), or a single return value (as a type name such as the int returned by the Stack.Len() method shown here), or a parenthesized list of return values, followed by an opening brace.

In most cases, a variable name for the value on which the method is called is also given — in our example here, we have used the name stack (and with no conflict with the package's name). The value on which the method is called is known in Go terminology as the receiver. (In other languages, the receiver is typically called this or self — using such names works fine in Go, but is not considered to be good Go style.)

In our example, the type of the receiver is Stack, so the receiver is passed by value. This means that any changes made to the receiver would be made on a copy of the original value and, in effect, lost. This is not a problem for methods that don't modify the receiver, such as the Stack.Len() method shown here. The Stack.Cap() method is almost identical to the Stack.Len() method (and so is not shown). The only difference is that the Stack.Cap() method returns the cap() rather than the len() of the receiver stack. The source code also includes a Stack.IsEmpty() method, but this is so similar to Stack.Len() — it just returns a bool indicating whether the stack's len() equals 0 — that again it isn't shown.

func (stack *Stack) Push(x interface{})  {
    *stack = append(*stack, x)

The Stack.Push() method is called on a pointer to a Stack (which will be explained shortly), and is passed a value (x) of any type. The built-in append() function takes a slice and one or more values and returns a (possibly new) slice, which has the original slice's contents, plus the given value or values as its last element or elements. If the stack has previously had items popped from it, the underlying slice's capacity is likely to be greater than its length, so the push could be very cheap: simply a matter of putting the x item into the len(stack) position and increasing the stack's length by one.

The Stack.Push() method always works (unless the computer runs out of memory), so we don't need to return an error value to indicate success or failure. If we want to modify a value, we must make its receiver a pointer. (Go pointers are essentially the same as in C and C++, except that pointer arithmetic isn't supported — or necessary.) A pointer is a variable that holds the memory address of another value. One reason that pointers are used is for efficiency — for example, if we have a value of a large type, it is much cheaper to pass a pointer to the value as a parameter than to pass the value itself. Another use is to make a value modifiable. For example, when a variable is passed into a function the function gets a copy of the value (like the stack passed into the stack.Len() function). This means that if we make any changes to the variable inside the function, they will have no effect on the original value. If we need to modify the original value — as is the case here, where we want to append to the stack — we must pass a pointer to the original value, and then we can modify the value that the pointer points to inside the function.

A pointer is declared by preceding the type name with an asterisk (*). So here, in the Stack.Push() method, the stack variable is of type *Stack; that is, the stack variable holds a pointer to a Stack value and not an actual Stack value. We can access the actual Stack value that the pointer points to by dereferencing the pointer — this simply means that we access the value the pointer points to. Dereferencing is done by preceding the variable name with an asterisk. So when we write stack, we are referring to a pointer to a Stack ( a *Stack); and when we write *stack, we are dereferencing the pointer (that is, referring to the actual Stack that the pointer points to).

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.