Find file
Fetching contributors…
Cannot retrieve contributors at this time
454 lines (411 sloc) 16.4 KB
\epi{"Go has pointers but not pointer arithmetic. You cannot use a pointer
variable to walk through the bytes of a string."}{\textit{Go For C++
Programmers}\\{\textsc{GO AUTHORS}}}
Go has pointers.
There is however no pointer arithmetic, so they act more like
references than pointers that you may know from C. Pointers
are useful.
Remember that when you call a function in Go, the variables are
\emph{pass-by-value}. So, for efficiency and the possibility to modify a
passed value \emph{in} functions we have pointers.
Just like in C you declare a pointer by prefixing the type with an
\lstinline{var p *int}. Now \var{p} is a pointer to an integer value.
All newly declared variables are assigned their zero value and pointers
are no difference. A newly declared, or just a pointer that points to
nothing has a \first{nil}{nil}-value. In other languages this is often called
a NULL pointer in Go it is just \var{nil}. To make
a pointer point to something you can use the \first{address-of operator}{operator!address-of}
(\func{\&}), which we do on line 5:
\begin{lstlisting}[caption=Use of a pointer,label=src:pointers]
var p *int
fmt.Printf("%v", p) |\coderemark{Prints \var{nil}}|
var i int |\coderemark{Declare integer variable \var{i}}|
p = &i |\coderemark{Make \var{p} point to \var{i}}|
fmt.Printf("%v", p) |\coderemark{Prints something like \var{0x7ff96b81c000a}}|
More general: \var{*X} is a pointer to an \type{X}; \var{[3]X} is an
array of three \type{X}s. The
types are therefore really easy to read just read out the names of the
type modifiers: \type{[]} declares an array slice;
declares a pointer; \type{[size]} declares an array. So
\type{[]*[3]*X} is an array slice of pointers to arrays of three
pointers to \type{X}s (also see figure \ref{fig:pointers}).
\caption[Pointers and types]{Pointers and types, the values \var{v} all have type \type{X}}
Dereferencing a pointer is done by prefixing the pointer variable with
\begin{lstlisting}[caption=Dereferencing a pointer,label=src:deref]
p = &i |\coderemark{Take the address of \var{i}}|
*p = 8 |\coderemark{Change the value of \var{i}}|
fmt.Printf("%v\n", *p) |\coderemark{Prints 8}|
fmt.Printf("%v\n", i) |\coderemark{Idem}|
As said, there is no pointer arithmetic, so if you write:
\lstinline{*p++}, it is interpreted as \lstinline{(*p)++}: first
dereference and then increment the value.\index{operator!increment}
Go also has garbage collection, meaning that you don't have to worry about
memory deallocation. Of course almost every language
since 1980 has this, but it is nice to see garbage collection in a
C-like language.
Go has two allocation primitives, \key{new} and \key{make}. They do different
things and apply to different types, which can be confusing, but the
rules are simple.
The following sections show how to handle allocation
in Go and hopefully clarifies the somewhat artificial distinction between
\first{\key{new}}{built-in!new} and \first{\key{make}}{built-in!make}.
\subsection{Allocation with new}
\label{sec:allocation with new}
The built-in function \key{new} is
essentially the same as its namesakes in other languages: \func{new(T)}
allocates zeroed storage for a new item of type \type{T} and returns its
address, a value of type \type{*T}. In Go terminology, it returns a pointer to
a newly allocated zero value of type \type{T}. This is important to
\key{new} returns \emph{pointers}.
means a user of the data structure can create one with \key{new} and get
right to work. For example, the documentation for \func{bytes.Buffer} states
that "the zero value for Buffer is an empty buffer ready to use."
Similarly, \func{sync.Mutex} does not have an explicit constructor or Init
method. Instead, the zero value for a \func{sync.Mutex} is defined to be an
unlocked mutex.
The zero-value-is-useful property works transitively. Consider this type
declaration. See section "\titleref{sec:defining your own}" on page
\pageref{sec:defining your own}.
type SyncedBuffer struct {
lock sync.Mutex
buffer bytes.Buffer
Values of type \type{SyncedBuffer} are also ready to use immediately upon
allocation or just declaration. In this snippet, both \var{p} and
\var{v} will work
correctly without further arrangement.
p := new(SyncedBuffer) |\coderemark{Type *SyncedBuffer}|
var v SyncedBuffer |\coderemark{Type SyncedBuffer}|
\subsection{Allocation with make}
\label{sec:allocation with make}
Back to allocation. The built-in function \func{make(T, args)} serves a purpose
different from \func{new(T)}. It creates slices, maps, and channels only, and
it returns an initialized (not zero) value of type \type{T}, not
\type{*T}. The reason
for the distinction is that these three types are, under the covers,
references to data structures that must be initialized before use. A
slice, for example, is a three-item descriptor containing a pointer to
the data (inside an array), the length, and the capacity; until those
items are initialized, the slice is \type{nil}. For slices, maps, and channels,
\key{make} initializes the internal data structure and prepares the value for
\key{make} returns initialized (non zero) \emph{values}.
For instance,
\lstinline{make([]int, 10, 100)}
allocates an array of 100 ints and then creates a slice structure with
length 10 and a capacity of 100 pointing at the first 10 elements of the
array. In contrast,
\lstinline{new([]int)} returns
a pointer to a newly allocated, zeroed slice structure, that is, a
pointer to a \type{nil} slice value.
These examples illustrate the difference between \key{new} and
var p *[]int = new([]int) // allocates slice structure; *p == nil
// rarely useful
var v []int = make([]int, 100) // v refers to a new array of 100 ints
// Unnecessarily complex:
var p *[]int = new([]int)
*p = make([]int, 100, 100)
// Idiomatic:
v := make([]int, 100)
Remember that \key{make} applies only to maps, slices and channels and does
not return a pointer. To obtain an explicit pointer allocate with
\begin{lbar}[\lstinline{new} allocates; \lstinline{make} initializes]
The above two paragraphs can be simply summarized:\\
\lstinline{new(T)} returns \var{*T} pointing to a zeroed \var{T}\\
\lstinline{make(T)} returns an initialized \var{T}\\
And of course \lstinline{make} is only used for slices, maps and channels.
\subsection{Constructors and composite literals}
\label{sec:constructors and composite literals}
Sometimes the zero value isn't good enough and an initializing
constructor is necessary, as in this example taken from the package
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
f := new(File)
f.fd = fd = name
f.dirinfo = nil
f.nepipe = 0
return f
There's a lot of boiler plate in there. We can simplify it using a
\first{composite literal}{literal!composite}, which is an expression that
creates a new instance each time it is evaluated.
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
f := File{fd, name, nil, 0} |\coderemark{Create a new \type{File}}|
return &f |\coderemark{Return the address of \var{f}}|
It is OK to return the address of a local variable;
the storage associated with the variable survives after the function
In fact, taking the address of a composite literal allocates a
fresh instance each time it is evaluated, so we can combine these last
two lines.\footnote{Taking the address of a composite literal tells the
compiler to allocate it on the heap, not the stack.}
return &File{fd, name, nil, 0}
The items (called \first{fields}{fields} of a composite
literal are laid out in order and must all be
present. However, by labeling the elements explicitly as field:value
pairs, the initializers can appear in any order, with the missing ones
left as their respective zero values. Thus we could say
return &File{fd: fd, name: name}
As a limiting case, if a composite literal contains no fields at all, it
creates a zero value for the type. The expressions
\lstinline{new(File)} and
\lstinline|&File{}| are equivalent.
Composite literals can also be created for arrays, slices, and maps,
with the field labels being indices or map keys as appropriate. In these
examples, the initializations work regardless of the values of
\var{Eio}, and \var{Einval}, as long as they are distinct.
ar := [...]string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
sl := []string {Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
ma := map[int]string{Enone: "no error", Eio: "Eio", Einval: "invalid argument"}
\section{Defining your own types}
\label{sec:defining your own}
Of course Go allows you to define new types, it does this
with the \first{\key{type}}{keyword!type} keyword:
type foo int
a new type \lstinline{foo} which acts like an \lstinline{int}.
Creating more sophisticated types is done with the
An example would be when we want record somebody's name (\type{string})
and age (\type{int}) in a single structure and make it a new type:
Apropos, the output of \lstinline{fmt.Printf("%v\n", a)} is
&\{Pete 42\}
That is nice!
Go knows how to print your structure. If you
only want to print one, or a few, fields of the structure you'll
need to use \verb|.<field name>|. For example to only print the name:
fmt.Printf("%s", |\coderemark{\%s formats a string}|
\subsection{More on structure fields}
As said each item in a structure is called a \index{field}{field}.
A struct with no fields:
struct {}
Or one with five fields:
struct {
x, y int
_ float64 |\coderemark{Padding}|
A *[]int
F func()
If you omit the name for a field, you create an
\first{anonymous field}{field!anonymous}, for instance:
struct {
T1 |\coderemark{Field name is T1}|
*T2 |\coderemark{Field name is T2}|
P.T3 |\coderemark{Field name is T3}|
x, y int |\coderemark{Field names are x and y}|
Note the field names that start with a capital letter are exported, i.e. can be
set or read from other packages. Field names that start with a lowercase are private
to the current package. The same goes for functions defined in packages, see chapter
If you create functions that works on your newly defined type, you can
take two routes:
\item Create a function that takes the type as an argument.
func doSomething(in1 *NameAge, in2 int) { /* ... */ }
This is (you might have guessed) a \first{\emph{function call}}{function!call}.
\item Create a function that works on the type (see \emph{receiver} in
listing \ref{src:function definition}):
func (in1 *NameAge) doSomething(in2 int) { /* ... */ }
This is a \first{\emph{method call}}{method call}, which can be
used as:
var n *NameAge
But keep the following in mind, this is quoted from \cite{go_spec}:
If \type{x} is
addressable and \lstinline{&x}'s method set contains \func{m},
\lstinline{x.m()} is shorthand for \lstinline{(&x).m()}.
In the above case this means that the following is \emph{not} an
var n NameAge |\coderemark{Not a pointer}|
Here Go will search the method list for \var{n} of type \type{NameAge},
come up empty and will then \emph{also} search the method list for
the type \type{*NameAge} and will translate this call to
Whether to use a function or method is entirely up to the programmer, but
if you want to satisfy an interface (see the next chapter) you must use
There is a subtle but major difference between the following type
declarations. Also see \cite[section~"Type Declarations"]{go_spec}.
Suppose we have:
// A Mutex is a data type with two methods, Lock and Unlock.
type Mutex struct { /* Mutex fields */ }
func (m *Mutex) Lock() { /* Lock implementation */ }
func (m *Mutex) Unlock() { /* Unlock implementation */ }
We now create two type in two different manors:
\item \lstinline|type NewMutex Mutex|;
\item \lstinline|type PrintableMutex struct { Mutex }|.
Now \var{NewMutux} has the same memory layout as \var{Mutex}, but
is doesn't have any of the methods of \var{Mutex}. In other words
its method set is empty.
But \var{PrintableMutex} \emph{has} \first{\emph{inherited}}{methods!inherited} the
method set from \var{Mutex}.
In the words of \cite{go_spec}:
The method set of \var{*PrintableMutex} contains the methods
\func{Lock} and \func{Unlock} bound to its anonymous field \var{Mutex}.
Sometimes you want to convert a type to another type.
This is possible in Go, but
there are some rules. For starters, converting from one value to another
is done by functions and not all conversions are allowed.
\caption[Valid conversions]{Valid conversions,
\lstinline{float64} works the same as \lstinline{float32}}
From a \lstinline{string} to a slice of bytes or ints.
mystring := "hello this is string"
byteslice := []byte(mystring)
Converts to a \type{byte} slice, each \type{byte} contains the integer value
of the corresponding byte in the string. Note that as strings in Go
are encoded in UTF-8 some characters in the string may end up in 1, 2, 3
or 4 bytes.
intslice := []int(mystring)
Converts to an \type{int} slice, each \type{int} contains a Unicode code
point. Every character from the string is corresponds to one integer.
From a slice of bytes or ints to a \lstinline{string}.
b := []byte{'h','e','l','l','o'} |\coderemark{Composite literal}|
s := string(b)
i := []int{257,1024,65}
r := string(i)
For numeric values the following conversion are defined:
\item{Convert to a integer with a specific (bit) length:
\item{From floating point to an integer value:
\lstinline{int(float32)}. This discards the fraction part
from the floating point value;}
\item{The other way around: \lstinline{float32(int)};}
\subsection{User defined types and conversions}
How can you convert between the types you have defined
We create two types here \type{Foo} and \type{Bar}, where
\lstinline{Bar} is an alias for \type{Foo}:
type foo struct { int } |\coderemark{Anonymous struct field}|
type bar foo |\coderemark{bar is an alias for foo}|
Then we:
var b bar = bar{1} |\coderemark{Declare \var{b} to be a \type{bar}}|
var f foo = b |\coderemark{Assign \var{b} to \var{f}}|
Which fails on the last line with:
\noindent\error{cannot use b (type bar) as type foo in assignment}
\noindent{}This can be fixed with a conversion:
var f foo = foo(b)
Note the converting structures that are not identical in their fields
is more difficult. Also note that converting \lstinline{b} to a plain
\type{int} also fails; an integer is not the same as a structure containing
an integer.