# Using Pointers In Go

- Published: December 16, 2014
- Author: William Kennedy
- URL: https://www.ardanlabs.com/blog/2014/12/using-pointers-in-go.html

<span style="font-size: large;">Introduction</span><br />
I am asked quite a bit about when and when not to use pointers in Go. The problem most people have, is that they try to make this decision based on what they think the performance tradeoff will be. Hence the problem, don’t make coding decisions based on unfounded thoughts you may have about performance. Make coding decisions based on the code being idiomatic, simple, readable and reasonable.

<br />
<br />
My use of pointers is based on discoveries I have made looking at code from the standard library. There are always exceptions to these rules, but what I will show you is common practice. It starts with classifying the type of value that needs to be shared. These type classifications are built-in, struct and reference types. Let’s look at each one individually.<br />
<br />
<span style="font-size: large;">Built-In Types</span><br />
Go’s <a href="http://golang.org/ref/spec#Types" target="_blank">built-in types</a> represent primitive data values that are the building blocks for managing and working with data. I group these types collectively as the set of boolean, numeric and string types. When declaring functions and methods that accept values of these types, the standard library rarely shares them with a pointer.<br />
<br />
Let’s start by looking at the <span style="font-family: Courier New, Courier, monospace;">isShellSpecialVar</span> function from the <span style="font-family: Courier New, Courier, monospace;">env</span> package:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 1</b> &nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/os/env.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/os/env.go</a><br />
<br />
38 func isShellSpecialVar(c uint8) bool {<br />
39 &nbsp; &nbsp; switch c {<br />
40 &nbsp; &nbsp; case '&#42;', '#', '$', '@', '!', '?', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':<br />
41 &nbsp; &nbsp; &nbsp; &nbsp; return true<br />
42 &nbsp; &nbsp; }<br />
43 &nbsp; &nbsp; return false<br />
44 }
</div>
<br />
The <span style="font-family: Courier New, Courier, monospace;">isShellSpecialVar</span> function in listing 1 is declared to accept a value of type <span style="font-family: Courier New, Courier, monospace;">uint8</span> and return a value of type <span style="font-family: Courier New, Courier, monospace;">bool</span>. For the caller to use this function, they must pass a copy of their <span style="font-family: Courier New, Courier, monospace;">uint8</span> type value into the function. This is the same for the return value. A copy of the function’s <span style="font-family: Courier New, Courier, monospace;">bool</span> type value is being returned back to the caller.<br />
<br />
Next, let’s look at the <span style="font-family: Courier New, Courier, monospace;">getShellName</span> function from the same <span style="font-family: Courier New, Courier, monospace;">env</span> package:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 2</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/os/env.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/os/env.go</a><br />
<br />
54 func getShellName(s string) (string, int) {<br />
55 &nbsp; &nbsp; switch {<br />
56 &nbsp; &nbsp; case s[0] == '{':<br />
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;. . .<br />
66 &nbsp; &nbsp; &nbsp; &nbsp; return &quot;&quot;, 1 // Bad syntax; just eat the brace.<br />
67 &nbsp; &nbsp; case isShellSpecialVar(s[0]):<br />
68 &nbsp; &nbsp; &nbsp; &nbsp; return s[0:1], 1<br />
69 &nbsp; &nbsp; }<br />
&nbsp; &nbsp; &nbsp; &nbsp;. . .<br />
74 &nbsp; &nbsp; return s[:i], i<br />
75 }
</div>
<br />
The <span style="font-family: Courier New, Courier, monospace;">getShellName</span> function in listing 2 is declared to accept a value of type <span style="font-family: Courier New, Courier, monospace;">string</span> and return two values, one of type <span style="font-family: Courier New, Courier, monospace;">string</span> and the other of type <span style="font-family: Courier New, Courier, monospace;">int</span>. A <span style="font-family: Courier New, Courier, monospace;">string</span> is a special built-in type in Go that represents an immutable slice of bytes. Since this slice can’t grow, the capacity value is not associated with its <a href="https://www.ardanlabs.com/blog/2013/08/understanding-slices-in-go-programming.html" target="_blank">slice header</a>. It is best to treat values of type <span style="font-family: Courier New, Courier, monospace;">string</span> the same way you treat boolean and numeric type values, as a primitive data value.<br />
<br />
When a call is made to <span style="font-family: Courier New, Courier, monospace;">getShellName</span>, the caller passes a copy of its <span style="font-family: Courier New, Courier, monospace;">string</span> value into the function. The function generates a new <span style="font-family: Courier New, Courier, monospace;">string</span> value and returns a copy of that value back to the caller. All the values being passed in and out of this function are copies of the original values.<br />
<br />
This practice of sharing copies of <span style="font-family: Courier New, Courier, monospace;">string</span> values is very prevalent in the <span style="font-family: Courier New, Courier, monospace;">strings</span> package:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 3</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/strings/strings.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/strings/strings.go</a><br />
<br />
620 func Trim(s string, cutset string) string {<br />
621 &nbsp; &nbsp; if s == &quot;&quot; || cutset == &quot;&quot; {<br />
622 &nbsp; &nbsp; &nbsp; &nbsp; return s<br />
623 &nbsp; &nbsp; }<br />
624 &nbsp; &nbsp; return TrimFunc(s, makeCutsetFunc(cutset))<br />
625 }</div>
<br />
All of the functions in the <span style="font-family: Courier New, Courier, monospace;">strings</span> package accept copies of the caller’s <span style="font-family: Courier New, Courier, monospace;">string</span> values and return copies of the <span style="font-family: Courier New, Courier, monospace;">string</span> values they create. Listing 3 shows the implementation of the <span style="font-family: Courier New, Courier, monospace;">Trim</span> function. The function accepts copies of two <span style="font-family: Courier New, Courier, monospace;">string</span> values, and returns a copy of either the first <span style="font-family: Courier New, Courier, monospace;">string</span> value that is passed in or a copy of a new <span style="font-family: Courier New, Courier, monospace;">string</span> value that has trimmed out the cutset.<br />
<br />
If you review more code from the standard library that share built-in type values, you will see how these values are rarely shared with a pointer. If a function or method needs to change the value of a built-in type, a new value reflecting that change is often returned back to the caller.<br />
<br />
In general, don’t share built-in type values with a pointer.<br />
<br />
<span style="font-size: large;">Struct Types</span><br />
<a href="http://golang.org/ref/spec#Struct_types" target="_blank">Struct</a> types allow for the creation of complex data types by composing different types together. This is accomplished by composing a sequence of fields, each which with a name and a type. They also support <a href="https://www.ardanlabs.com/blog/2014/05/methods-interfaces-and-embedded-types.html" target="_blank">embedding</a>, which adds to the way struct types can be composed.<br />
<br />
Struct types can be implemented to behave like built-in types. When they are, you should treat them as such. To see a struct type that behaves as a primitive data value, we can look at the <span style="font-family: Courier New, Courier, monospace;">time</span> package:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 4</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/time/time.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/time/time.go</a><br />
<br />
39 type Time struct {<br />
40 &nbsp; &nbsp; // sec gives the number of seconds elapsed since<br />
41 &nbsp; &nbsp; // January 1, year 1 00:00:00 UTC.<br />
42 &nbsp; &nbsp; sec int64<br />
43<br />
44 &nbsp; &nbsp; // nsec specifies a non-negative nanosecond<br />
45 &nbsp; &nbsp; // offset within the second named by Seconds.<br />
46 &nbsp; &nbsp; // It must be in the range [0, 999999999].<br />
47 &nbsp; &nbsp; nsec int32<br />
48<br />
49 &nbsp; &nbsp; // loc specifies the Location that should be used to<br />
50 &nbsp; &nbsp; // determine the minute, hour, month, day, and year<br />
51 &nbsp; &nbsp; // that correspond to this Time.<br />
52 &nbsp; &nbsp; // Only the zero Time has a nil Location.<br />
53 &nbsp; &nbsp; // In that case it is interpreted to mean UTC.<br />
54 &nbsp; &nbsp; loc &#42;Location<br />
55 }
</div>
<br />
Listing 4 shows the <span style="font-family: Courier New, Courier, monospace;">Time</span> struct type. This type represents time and has been implemented to behave as a primitive data value. If you look at the factory function <span style="font-family: Courier New, Courier, monospace;">Now</span>, you will see it returns a value of type <span style="font-family: Courier New, Courier, monospace;">Time</span>, not a pointer:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 5</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/time/time.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/time/time.go</a><br />
<br />
781 func Now() Time {<br />
782 &nbsp; &nbsp; sec, nsec := now()<br />
783 &nbsp; &nbsp; return Time{sec + unixToInternal, nsec, Local}<br />
784 }
</div>
<br />
Listing 5 shows how the <span style="font-family: Courier New, Courier, monospace;">Now</span> function returns a value of type <span style="font-family: Courier New, Courier, monospace;">Time</span>. This is an indication that values of type <span style="font-family: Courier New, Courier, monospace;">Time</span> are safe to copy and is the preferred way to share them. Next, let’s look at a method that is used to change the value of a <span style="font-family: Courier New, Courier, monospace;">Time</span> value:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 6</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/time/time.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/time/time.go</a><br />
<br />
610 func (t Time) Add(d Duration) Time {<br />
611 &nbsp; &nbsp; t.sec += int64(d / 1e9)<br />
612 &nbsp; &nbsp; nsec := int32(t.nsec) + int32(d%1e9)<br />
613 &nbsp; &nbsp; if nsec &gt;= 1e9 {<br />
614 &nbsp; &nbsp; &nbsp; &nbsp; t.sec++<br />
615 &nbsp; &nbsp; &nbsp; &nbsp; nsec -= 1e9<br />
616 &nbsp; &nbsp; } else if nsec &lt; 0 {<br />
617 &nbsp; &nbsp; &nbsp; &nbsp; t.sec--<br />
618 &nbsp; &nbsp; &nbsp; &nbsp; nsec += 1e9<br />
619 &nbsp; &nbsp; }<br />
620 &nbsp; &nbsp; t.nsec = nsec<br />
621 &nbsp; &nbsp; return t<br />
622 }
</div>
<br />
Just like we saw when working with built-in types, listing 6 shows how the <span style="font-family: Courier New, Courier, monospace;">Add</span> method is called against a copy of the caller’s <span style="font-family: Courier New, Courier, monospace;">Time</span> value. The method changes the local copy of the receiver value and returns a copy of that change back to the caller.<br />
<br />
Functions that accept <span style="font-family: Courier New, Courier, monospace;">Time</span> values also accept copies of these values:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 7</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/time/time.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/time/time.go</a><br />
<br />
1118 func div(t Time, d Duration) (qmod2 int, r Duration) {
</div>
<br />
Listing 7 shows the declaration of the <span style="font-family: Courier New, Courier, monospace;">div</span> function which accepts a value of type <span style="font-family: Courier New, Courier, monospace;">Time</span> and <span style="font-family: Courier New, Courier, monospace;">Duration</span>. Again, values of type <span style="font-family: Courier New, Courier, monospace;">Time</span> are treated like a primitive data type and are copied when shared.<br />
<br />
Most of the time struct types are not created to behave like a primitive data type. In these cases, sharing the value by using a pointer is a better way to go. Let’s look at an example from the <span style="font-family: Courier New, Courier, monospace;">os</span> package:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 8</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/os/file.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/os/file.go</a><br />
<br />
238 func Open(name string) (file &#42;File, err error) {<br />
239 &nbsp; &nbsp; return OpenFile(name, O_RDONLY, 0)<br />
240 }
</div>
<br />
In listing 8 we see the <span style="font-family: Courier New, Courier, monospace;">Open</span> function from the os package. It opens a file for reading and returns a pointer to a value of type <span style="font-family: Courier New, Courier, monospace;">File</span>. Next, let’s look at the declaration of the <span style="font-family: Courier New, Courier, monospace;">File</span> struct type for the UNIX platform:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 9</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/os/file_unix.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/os/file_unix.go</a><br />
<br />
15 // File represents an open file descriptor.<br />
16 type File struct {<br />
17 &nbsp; &nbsp; &#42;file<br />
18 }<br />
19<br />
20 // file is the real representation of &#42;File.<br />
21 // The extra level of indirection ensures that no clients of os<br />
22 // can overwrite this data, which could cause the finalizer<br />
23 // to close the wrong file descriptor.<br />
24 type file struct {<br />
25 &nbsp; &nbsp; fd      int<br />
26 &nbsp; &nbsp; name    string<br />
27 &nbsp; &nbsp; dirinfo &#42;dirInfo // nil unless directory being read<br />
28 &nbsp; &nbsp; nepipe  int32    // number of consecutive EPIPE in Write<br />
29 }
</div>
<br />
I left the comments for these type declarations in listing 9 because they really bring home the point I want to make. When you have a factory function like <span style="font-family: Courier New, Courier, monospace;">Open</span> that is providing you a pointer, it is a good sign that you should not be making copies of the referenced value being returned. <span style="font-family: Courier New, Courier, monospace;">Open</span> is returning a pointer because it is not safe to make copies of the referenced <span style="font-family: Courier New, Courier, monospace;">File</span> value being returned. The value should always be used and shared through the pointer.<br />
<br />
Even if a function or method is not changing the state of a <span style="font-family: Courier New, Courier, monospace;">File</span> struct type value, it still needs to be shared with a pointer. Let’s look at the <span style="font-family: Courier New, Courier, monospace;">epipecheck</span> function from the <span style="font-family: Courier New, Courier, monospace;">os</span> package for the UNIX platform:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 10</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/os/file_unix.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/os/file_unix.go</a><br />
<br />
58 func epipecheck(file &#42;File, e error) {<br />
59 &nbsp; &nbsp; if e == syscall.EPIPE {<br />
60 &nbsp; &nbsp; &nbsp; &nbsp; if atomic.AddInt32(&amp;file.nepipe, 1) &gt;= 10 {<br />
61 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sigpipe()<br />
62 &nbsp; &nbsp; &nbsp; &nbsp; }<br />
63 &nbsp; &nbsp; } else {<br />
64 &nbsp; &nbsp; &nbsp; &nbsp; atomic.StoreInt32(&amp;file.nepipe, 0)<br />
65 &nbsp; &nbsp; }<br />
66 }
</div>
<br />
Here in listing 10, the <span style="font-family: Courier New, Courier, monospace;">epipecheck</span> function accepts a pointer of type <span style="font-family: Courier New, Courier, monospace;">File</span>. The caller therefore shares its <span style="font-family: Courier New, Courier, monospace;">File</span> type value with the function via a pointer. Notice the <span style="font-family: Courier New, Courier, monospace;">epipecheck</span> function is not changing the state of the <span style="font-family: Courier New, Courier, monospace;">File</span> value but using it to perform its operation.<br />
<br />
This applies as well for the methods declared for the <span style="font-family: Courier New, Courier, monospace;">File</span> type:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 11</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/os/file.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/os/file.go</a><br />
<br />
224 func (f &#42;File) Chdir() error {<br />
225 &nbsp; &nbsp; if f == nil {<br />
226 &nbsp; &nbsp; &nbsp; &nbsp; return ErrInvalid<br />
227 &nbsp; &nbsp; }<br />
228 &nbsp; &nbsp; if e := syscall.Fchdir(f.fd); e != nil {<br />
229 &nbsp; &nbsp; &nbsp; &nbsp; return &amp;PathError{&quot;chdir&quot;, f.name, e}<br />
230 &nbsp; &nbsp; }<br />
231 &nbsp; &nbsp; return nil<br />
232 }
</div>
<br />
The <span style="font-family: Courier New, Courier, monospace;">Chdir</span> method in listing 11 is using a pointer receiver to implement the method and does not change the state of the receiver value. In all these cases, to share a value of type <span style="font-family: Courier New, Courier, monospace;">File</span>, it must be done with a pointer. A <span style="font-family: Courier New, Courier, monospace;">File</span> value is not a primitive data value.<br />
<br />
If you review more code from the standard library, you will see how struct types are either implemented as a primitive data value like the built-in types or implemented as a value that needs to be shared with a pointer and never copied. The factory functions for a given struct type will give you a great clue as to how the type is implemented.<br />
<br />
In general, share struct type values with a pointer unless the struct type has been implemented to behave like a primitive data value.<br />
<br />
<i>If you are still not sure, this is another way to think about. Think of every struct as having a nature. If the nature of the struct is something that should not be changed, like a time, a color or a coordinate, then implement the struct as a primitive data value. If the nature of the struct is something that can be changed, even if it never is in your program, it is not a primitive data value and should be implemented to be shared with a pointer. Don’t create structs that have a duality of nature</i>.<br />
<br />
<span style="font-size: large;">Reference Types</span><br />
Reference types are slices, maps, channels, interface and function values. These are values that contain a header value that references an underlying data structure via a pointer and other meta-data. We rarely share reference type values with a pointer because the header value is designed to be copied. The header value already contains a pointer which is sharing the underlying data structure for us by default.<br />
<br />
Let’s look at an example from the <span style="font-family: Courier New, Courier, monospace;">net</span> package:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 12</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/net/ip.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/net/ip.go</a><br />
<br />
32 type IP []byte</div>
<br />
Listing 12 shows a named type from the <span style="font-family: Courier New, Courier, monospace;">net</span> package called <span style="font-family: Courier New, Courier, monospace;">IP</span> with a base type that is a slice of bytes. There is value in using a named type when you need to declare behavior around a built-in or reference type. Let’s look at the <span style="font-family: Courier New, Courier, monospace;">MarshalText</span> method for the <span style="font-family: Courier New, Courier, monospace;">IP</span> named type:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 13</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/net/ip.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/net/ip.go</a><br />
<br />
329 func (ip IP) MarshalText() ([]byte, error) {<br />
330 &nbsp; &nbsp; if len(ip) == 0 {<br />
331 &nbsp; &nbsp; &nbsp; &nbsp; return []byte(&quot;&quot;), nil<br />
332 &nbsp; &nbsp; }<br />
333 &nbsp; &nbsp; if len(ip) != IPv4len &amp;&amp; len(ip) != IPv6len {<br />
334 &nbsp; &nbsp; &nbsp; &nbsp; return nil, errors.New(&quot;invalid IP address&quot;)<br />
335 &nbsp; &nbsp; }<br />
336 &nbsp; &nbsp; return []byte(ip.String()), nil<br />
337 }
</div>
<br />
Here in listing 13, we can see how the <span style="font-family: Courier New, Courier, monospace;">MarshalText</span> method is using a value receiver. This is exactly what I would expect to see because we don’t share reference types with a pointer. If you look at the rest of the methods declared for the <span style="font-family: Courier New, Courier, monospace;">IP</span> named type in the <span style="font-family: Courier New, Courier, monospace;">net</span> package, you will see the use of more value receivers.<br />
<br />
This applies to sharing reference type values as parameters to functions and methods:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 14</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/net/ip.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/net/ip.go</a><br />
<br />
318 // ipEmptyString is like ip.String except that it returns<br />
319 // an empty string when ip is unset.<br />
320 func ipEmptyString(ip IP) string {<br />
321 &nbsp; &nbsp; if len(ip) == 0 {<br />
322 &nbsp; &nbsp; &nbsp; &nbsp; return &quot;&quot;<br />
323 &nbsp; &nbsp; }<br />
324 &nbsp; &nbsp; return ip.String()<br />
325 }
</div>
<br />
The <span style="font-family: Courier New, Courier, monospace;">ipEmptyString</span> function in listing 14 accepts a value of named type <span style="font-family: Courier New, Courier, monospace;">IP</span>. No pointer is used to share this value since the base type for <span style="font-family: Courier New, Courier, monospace;">IP</span> is a slice of bytes and therefore a reference type.<br />
<br />
There is one common exception to the rule of not sharing a reference type with a pointer:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 15</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
<a href="http://golang.org/src/net/ip.go" target="_blank"><span class="sr-only">External resource on golang.org: </span>http&#58;//golang.org/src/net/ip.go</a><br />
<br />
341 func (ip &#42;IP) UnmarshalText(text []byte) error {<br />
342 &nbsp; &nbsp; if len(text) == 0 {<br />
343 &nbsp; &nbsp; &nbsp; &nbsp; &#42;ip = nil<br />
344 &nbsp; &nbsp; &nbsp; &nbsp; return nil<br />
345 &nbsp; &nbsp; }<br />
346 &nbsp; &nbsp; s := string(text)<br />
347 &nbsp; &nbsp; x := ParseIP(s)<br />
348 &nbsp; &nbsp; if x == nil {<br />
349 &nbsp; &nbsp; &nbsp; &nbsp; return &amp;ParseError{&quot;IP address&quot;, s}<br />
350 &nbsp; &nbsp; }<br />
351 &nbsp; &nbsp; &#42;ip = x<br />
352 &nbsp; &nbsp; return nil<br />
353 }
</div>
<br />
Anytime you are unmarshaling data into a reference type, you will need to share that reference type value with a pointer. Listing 15 shows the <span style="font-family: Courier New, Courier, monospace;">UnmarshalText</span> method that is performing an unmarshal operation and is declared with a pointer receiver. The <span style="font-family: Courier New, Courier, monospace;">Decode</span> and <span style="font-family: Courier New, Courier, monospace;">Unmarshal</span> functions from the <span style="font-family: Courier New, Courier, monospace;">encoding</span> packages would also expect to receive a pointer to a reference type.<br />
<br />
If you review more code from the standard library, you will see how values from reference types in most cases are not shared with a pointer. Since the reference type contains a header value whose purpose is to share an underlying data structure, sharing these values with a pointer is unnecessary. There is already a pointer in use.<br />
<br />
In general, don’t share reference type values with a pointer unless you are implementing an unmarshal type of functionality.<br />
<br />
<span style="font-size: large;">Slices Of Values</span><br />
One thing I avoid when I can is storing data with a slice of pointers. When I retrieve data from a database, the web or even a file, I store that data in a slice of values:<br />
<br />
<span style="background-color: #eeeeee;">&nbsp; <b>Listing 16</b>&nbsp;&nbsp;</span><br />
<div style="background-color: #efefef; font-family: 'Courier New', Courier, monospace; font-size: small; overflow-x: scroll; padding: 10px; white-space: nowrap;">
10 func FindRegion(s &#42;Service, region string) ([]BuoyStation, error) {<br />
11 &nbsp; &nbsp; var bs []BuoyStation<br />
12 &nbsp; &nbsp; f := func(c &#42;mgo.Collection) error {<br />
13 &nbsp; &nbsp; &nbsp; &nbsp; queryMap := bson.M{&quot;region&quot;: region}<br />
14 &nbsp; &nbsp; &nbsp; &nbsp; return c.Find(queryMap).All(&amp;bs)<br />
15 &nbsp; &nbsp; }<br />
16<br />
17 &nbsp; &nbsp; if err := s.DBAction(cfg.Database, &quot;buoy_stations&quot;, f); err != nil {<br />
18 &nbsp; &nbsp; &nbsp; &nbsp; return nil, err<br />
19 &nbsp; &nbsp; }<br />
20<br />
21 &nbsp; &nbsp; return bs, nil<br />
22 }
</div>
<br />
Here is some code in listing 16 from one of my projects that makes a call to a MongoDB database via the <span style="font-family: Courier New, Courier, monospace;">mgo</span> package. On line 14, I pass the address of the <span style="font-family: Courier New, Courier, monospace;">bs</span> slice to the <span style="font-family: Courier New, Courier, monospace;">All</span> method. The <span style="font-family: Courier New, Courier, monospace;">All</span> method performs an unmarshal call underneath to create the values for the slice. Then the slice of data values is returned by passing a copy of the slice header value back to the caller.<br />
<br />
Using a slice of values allows the data for the program to be stored in a contiguous block of memory. This means that more of the core data I am using can be cached by the CPU at once and hopefully stays in the cache longer. If I create a slice of pointers, there is no guarantee the memory for these core data values would be contiguous, only the pointers to those values would be stored contiguously. Though I am thinking about performance in this case, I would argue that it is more idiomatic.<br />
<br />
There are times when this is not possible. Imagine if I needed a slice of <span style="font-family: Courier New, Courier, monospace;">File</span> type values. Since I can’t make copies of <span style="font-family: Courier New, Courier, monospace;">File</span> type values, I would need to create a slice of <span style="font-family: Courier New, Courier, monospace;">File</span> type pointers. This situation occurs often when working with struct types from the standard library and not your own.<br />
<br />
In general, create slices and maps of values when you can.<br />
<br />
<span style="font-size: large;">Conclusion</span><br />
The standard library is fairly consistent in how it shares values based on the type of value it is working with. Don’t use pointers with built-in data types unless you have a special need to do so. Struct types have a duality. If the struct type is implemented as a primitive data type, then don’t use a pointer. If not, then share those values with a pointer. Finally, reference types should not be shared with a pointer with very few exceptions.<br />
<br />
I would like to re-iterate three other thoughts as I close. First, make coding decisions based on the code being idiomatic, simple, readable and reasonable. Second, this is not about right and wrong, think about the code you are writing and there being reason behind the decisions you are making. Lastly, take each situation and scenario as an individual case, and try not to apply a blanket pattern or solution.<br />
<br />
