blob: 7168f1d057d130135d80f70ca0643227f680aa38 [file] [log] [blame]
Robert Griesemer53440da2009-10-01 14:08:00 -07001<!-- Go For C++ Programmers -->
Larry Hosken698c6c02009-09-17 08:05:12 -07002
3<p>
Russ Cox2a63f5d2009-11-08 01:08:26 -08004Go is a systems programming language intended to be a general-purpose
5systems language, like C++.
Larry Hosken698c6c02009-09-17 08:05:12 -07006These are some notes on Go for experienced C++ programmers. This
7document discusses the differences between Go and C++, and says little
8to nothing about the similarities.
9
10<p>
11For a more general introduction to Go, see the
Rob Pike6ac19ec2009-11-01 20:57:13 -080012<a href="go_tutorial.html">Go tutorial</a> and
13<a href="effective_go.html">Effective Go</a>.
Larry Hosken698c6c02009-09-17 08:05:12 -070014
15<p>
16For a detailed description of the Go language, see the
17<a href="go_spec.html">Go spec</a>.
18
Larry Hosken698c6c02009-09-17 08:05:12 -070019<h2 id="Conceptual_Differences">Conceptual Differences</h2>
20
21<ul>
22<li>Go does not have classes with constructors or destructors.
23 Instead of class methods, a class inheritance hierarchy,
24 and virtual functions, Go provides <em>interfaces</em>, which are
25 <a href="#Interfaces">discussed in more detail below</a>.
26 Interfaces are also used where C++ uses templates.
27
Russ Cox2a63f5d2009-11-08 01:08:26 -080028<li>Go uses garbage collection. It is not necessary (or possible)
29 to release memory explicitly. The garbage collection is (intended to be)
Larry Hosken698c6c02009-09-17 08:05:12 -070030 incremental and highly efficient on modern processors.
31
Russ Cox2a63f5d2009-11-08 01:08:26 -080032<li>Go has pointers but not pointer arithmetic. You cannot
Larry Hosken698c6c02009-09-17 08:05:12 -070033 use a pointer variable to walk through the bytes of a string.
34
35<li>Arrays in Go are first class values. When an array is used as a
Ian Lance Taylore2854872009-10-12 15:43:13 -070036 function parameter, the function receives a copy of the array, not
37 a pointer to it. However, in practice functions often use slices
38 for parameters; slices hold pointers to underlying arrays. Slices
39 are <a href="#Slices">discussed further below</a>.
Larry Hosken698c6c02009-09-17 08:05:12 -070040
Ian Lance Taylore2854872009-10-12 15:43:13 -070041<li>Strings are provided by the language. They may not be changed once they
Larry Hosken698c6c02009-09-17 08:05:12 -070042 have been created.
43
44<li>Hash tables are provided by the language. They are called maps.
45
Ian Lance Taylore2854872009-10-12 15:43:13 -070046<li>Separate threads of execution, and communication channels between
47 them, are provided by the language. This
48 is <a href="#Goroutines">discussed further below</a>.
Larry Hosken698c6c02009-09-17 08:05:12 -070049
Ian Lance Taylore2854872009-10-12 15:43:13 -070050<li>Certain types (maps and channels, described further below)
Larry Hosken698c6c02009-09-17 08:05:12 -070051 are passed by reference, not by value. That is, passing a map to a
52 function does not copy the map, and if the function changes the map
Ian Lance Taylore2854872009-10-12 15:43:13 -070053 the change will be seen by the caller. In C++ terms, one can
54 think of these as being reference types.
Larry Hosken698c6c02009-09-17 08:05:12 -070055
56<li>Go does not use header files. Instead, each source file is part of a
57 defined <em>package</em>. When a package defines an object
Rob Pike6ac19ec2009-11-01 20:57:13 -080058 (type, constant, variable, function) with a name starting with an
59 upper case letter, that object is visible to any other file which
Larry Hosken698c6c02009-09-17 08:05:12 -070060 imports that package.
61
62<li>Go does not support implicit type conversion. Operations that mix
63 different types require casts (called conversions in Go).
64
65<li>Go does not support function overloading and does not support user
66 defined operators.
67
68<li>Go does not support <code>const</code> or <code>volatile</code> qualifiers.
69
70<li>Go uses <code>nil</code> for invalid pointers, where C++ uses
71 <code>NULL</code> or simply <code>0</code>.
72</ul>
73
74<h2 id="Syntax">Syntax</h2>
75
76<p>
77The declaration syntax is reversed compared to C++. You write the name
Russ Cox2a63f5d2009-11-08 01:08:26 -080078followed by the type. Unlike in C++, the syntax for a type does not match
Larry Hosken698c6c02009-09-17 08:05:12 -070079the way in which the variable is used. Type declarations may be read
80easily from left to right.
81
82<pre>
83<b>Go C++</b>
Ian Lance Taylorbf575202010-01-29 16:37:50 -080084var v1 int // int v1;
85var v2 string // const std::string v2; (approximately)
86var v3 [10]int // int v3[10];
87var v4 []int // int* v4; (approximately)
88var v5 struct { f int } // struct { int f; } v5;
89var v6 *int // int* v6; (but no pointer arithmetic)
90var v7 map[string]int // unordered_map&lt;string, int&gt;* v7; (approximately)
91var v8 func(a int) int // int (*v8)(int a);
Larry Hosken698c6c02009-09-17 08:05:12 -070092</pre>
93
94<p>
95Declarations generally take the form of a keyword followed by the name
96of the object being declared. The keyword is one of <code>var</code>,
97<code>func</code>,
98<code>const</code>, or <code>type</code>. Method declarations are a minor
99exception in that
Russ Cox2a63f5d2009-11-08 01:08:26 -0800100the receiver appears before the name of the object being declared; see
Ian Lance Taylore2854872009-10-12 15:43:13 -0700101the <a href="#Interfaces">discussion of interfaces</a>.
Larry Hosken698c6c02009-09-17 08:05:12 -0700102
103<p>
104You can also use a keyword followed by a series of declarations in
105parentheses.
106
107<pre>
Russ Cox2a63f5d2009-11-08 01:08:26 -0800108var (
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800109 i int
Rob Pike80e25fc2011-01-19 23:07:38 -0500110 m float64
Russ Cox2a63f5d2009-11-08 01:08:26 -0800111)
Larry Hosken698c6c02009-09-17 08:05:12 -0700112</pre>
113
114<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700115When declaring a function, you must either provide a name for each parameter
Larry Hosken698c6c02009-09-17 08:05:12 -0700116or not provide a name for any parameter; you can't omit some names
117and provide others. You may group several names with the same type:
118
119<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800120func f(i, j, k int, s, t string)
Larry Hosken698c6c02009-09-17 08:05:12 -0700121</pre>
122
123<p>
124A variable may be initialized when it is declared. When this is done,
125specifying the type is permitted but not required. When the type is
126not specified, the type of the variable is the type of the
127initialization expression.
128
129<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800130var v = *p
Larry Hosken698c6c02009-09-17 08:05:12 -0700131</pre>
132
133<p>
134See also the <a href="#Constants">discussion of constants, below</a>.
Russ Cox2a63f5d2009-11-08 01:08:26 -0800135If a variable is not initialized explicitly, the type must be specified.
Larry Hosken698c6c02009-09-17 08:05:12 -0700136In that case it will be
Russ Cox2a63f5d2009-11-08 01:08:26 -0800137implicitly initialized to the type's zero value (0, nil, etc.). There are no
Larry Hosken698c6c02009-09-17 08:05:12 -0700138uninitialized variables in Go.
139
140<p>
Russ Cox2a63f5d2009-11-08 01:08:26 -0800141Within a function, a short declaration syntax is available with
Larry Hosken698c6c02009-09-17 08:05:12 -0700142<code>:=</code> .
143
144<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800145v1 := v2
Larry Hosken698c6c02009-09-17 08:05:12 -0700146</pre>
147
148<p>
149This is equivalent to
150
151<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800152var v1 = v2
Larry Hosken698c6c02009-09-17 08:05:12 -0700153</pre>
154
155<p>
Rob Pike6ac19ec2009-11-01 20:57:13 -0800156Go permits multiple assignments, which are done in parallel.
Larry Hosken698c6c02009-09-17 08:05:12 -0700157
158<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800159i, j = j, i // Swap i and j.
Larry Hosken698c6c02009-09-17 08:05:12 -0700160</pre>
161
162<p>
Rob Pike6ac19ec2009-11-01 20:57:13 -0800163Functions may have multiple return values, indicated by a list in
164parentheses. The returned values can be stored by assignment
165to a list of variables.
Larry Hosken698c6c02009-09-17 08:05:12 -0700166
167<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800168func f() (i int, j int) { ... }
169v1, v2 = f()
Larry Hosken698c6c02009-09-17 08:05:12 -0700170</pre>
171
172<p>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800173Go code uses very few semicolons in practice. Technically, all Go
174statements are terminated by a semicolon. However, Go treats the end
175of a non-blank line as a semicolon unless the line is clearly
176incomplete (the exact rules are
177in <a href="go_spec.html#Semicolons">the language specification</a>).
178A consequence of this is that in some cases Go does not permit you to
179use a line break. For example, you may not write
180<pre>
181func g()
182{ // INVALID
183}
184</pre>
185A semicolon will be inserted after <code>g()</code>, causing it to be
186a function declaration rather than a function definition. Similarly,
187you may not write
188<pre>
189if x {
190}
191else { // INVALID
192}
193</pre>
194A semicolon will be inserted after the <code>}</code> preceding
195the <code>else</code>, causing a syntax error.
196
197<p>
198Since semicolons do end statements, you may continue using them as in
199C++. However, that is not the recommended style. Idiomatic Go code
200omits unnecessary semicolons, which in practice is all of them other
Scott Lawrence76dccbc2010-08-30 09:58:27 +1000201than the initial <code>for</code> loop clause and cases where you want several
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800202short statements on a single line.
203
204<p>
205While we're on the topic, we recommend that rather than worry about
206semicolons and brace placement, you format your code with
207the <code>gofmt</code> program. That will produce a single standard
208Go style, and let you worry about your code rather than your
209formatting. While the style may initially seem odd, it is as good as
210any other style, and familiarity will lead to comfort.
Larry Hosken698c6c02009-09-17 08:05:12 -0700211
212<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700213When using a pointer to a struct, you use <code>.</code> instead
214of <code>-&gt;</code>.
215Thus syntactically speaking a structure and a pointer to a structure
216are used in the same way.
Larry Hosken698c6c02009-09-17 08:05:12 -0700217
218<pre>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700219type myStruct struct { i int }
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800220var v9 myStruct // v9 has structure type
221var p9 *myStruct // p9 is a pointer to a structure
Larry Hosken698c6c02009-09-17 08:05:12 -0700222f(v9.i, p9.i)
223</pre>
224
225<p>
226Go does not require parentheses around the condition of a <code>if</code>
227statement, or the expressions of a <code>for</code> statement, or the value of a
228<code>switch</code> statement. On the other hand, it does require curly braces
229around the body of an <code>if</code> or <code>for</code> statement.
230
231<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800232if a &lt; b { f() } // Valid
233if (a &lt; b) { f() } // Valid (condition is a parenthesized expression)
234if (a &lt; b) f() // INVALID
235for i = 0; i &lt; 10; i++ {} // Valid
236for (i = 0; i &lt; 10; i++) {} // INVALID
Larry Hosken698c6c02009-09-17 08:05:12 -0700237</pre>
238
239<p>
240Go does not have a <code>while</code> statement nor does it have a
241<code>do/while</code>
242statement. The <code>for</code> statement may be used with a single condition,
243which makes it equivalent to a <code>while</code> statement. Omitting the
244condition entirely is an endless loop.
245
246<p>
247Go permits <code>break</code> and <code>continue</code> to specify a label.
248The label must
249refer to a <code>for</code>, <code>switch</code>, or <code>select</code>
250statement.
251
252<p>
253In a <code>switch</code> statement, <code>case</code> labels do not fall
254through. You can
255make them fall through using the <code>fallthrough</code> keyword. This applies
256even to adjacent cases.
257
258<pre>
Russ Cox2a63f5d2009-11-08 01:08:26 -0800259switch i {
260case 0: // empty case body
261case 1:
262 f() // f is not called when i == 0!
263}
Larry Hosken698c6c02009-09-17 08:05:12 -0700264</pre>
265
266<p>
267But a <code>case</code> can have multiple values.
268
269<pre>
Russ Cox2a63f5d2009-11-08 01:08:26 -0800270switch i {
271case 0, 1:
272 f() // f is called if i == 0 || i == 1.
273}
Larry Hosken698c6c02009-09-17 08:05:12 -0700274</pre>
275
276<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700277The values in a <code>case</code> need not be constants&mdash;or even integers;
Larry Hosken698c6c02009-09-17 08:05:12 -0700278any type
279that supports the equality comparison operator, such as strings or
Ian Lance Taylore2854872009-10-12 15:43:13 -0700280pointers, can be used&mdash;and if the <code>switch</code>
Larry Hosken698c6c02009-09-17 08:05:12 -0700281value is omitted it defaults to <code>true</code>.
282
283<pre>
Russ Cox2a63f5d2009-11-08 01:08:26 -0800284switch {
285case i &lt; 0:
286 f1()
287case i == 0:
288 f2()
289case i &gt; 0:
290 f3()
291}
Larry Hosken698c6c02009-09-17 08:05:12 -0700292</pre>
293
294<p>
295The <code>++</code> and <code>--</code> operators may only be used in
296statements, not in expressions.
297You cannot write <code>c = *p++</code>. <code>*p++</code> is parsed as
298<code>(*p)++</code>.
299
Ian Lance Taylore2854872009-10-12 15:43:13 -0700300<p>
301The <code>defer</code> statement may be used to call a function after
302the function containing the <code>defer</code> statement returns.
303
304<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800305fd := open("filename")
306defer close(fd) // fd will be closed when this function returns.
Ian Lance Taylore2854872009-10-12 15:43:13 -0700307</pre>
308
Larry Hosken698c6c02009-09-17 08:05:12 -0700309<h2 id="Constants">Constants </h2>
310
311<p>
Robert Griesemera27f1f72009-10-01 14:12:18 -0700312In Go constants may be <i>untyped</i>. This applies even to constants
Russ Cox2a63f5d2009-11-08 01:08:26 -0800313named with a <code>const</code> declaration, if no
Robert Griesemera27f1f72009-10-01 14:12:18 -0700314type is given in the declaration and the initializer expression uses only
315untyped constants.
Rob Pike6ac19ec2009-11-01 20:57:13 -0800316A value derived from an untyped constant becomes typed when it
317is used within a context that
Robert Griesemera27f1f72009-10-01 14:12:18 -0700318requires a typed value. This permits constants to be used relatively
Larry Hosken698c6c02009-09-17 08:05:12 -0700319freely without requiring general implicit type conversion.
320
321<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800322var a uint
Russ Cox2a63f5d2009-11-08 01:08:26 -0800323f(a + 1) // untyped numeric constant "1" becomes typed as uint
Larry Hosken698c6c02009-09-17 08:05:12 -0700324</pre>
325
326<p>
Robert Griesemera27f1f72009-10-01 14:12:18 -0700327The language does not impose any limits on the size of an untyped
328numeric constant or constant expression. A limit is only applied when
329a constant is used where a type is required.
Larry Hosken698c6c02009-09-17 08:05:12 -0700330
331<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800332const huge = 1 &lt;&lt; 100
Russ Cox2a63f5d2009-11-08 01:08:26 -0800333f(huge &gt;&gt; 98)
Larry Hosken698c6c02009-09-17 08:05:12 -0700334</pre>
335
336<p>
337Go does not support enums. Instead, you can use the special name
338<code>iota</code> in a single <code>const</code> declaration to get a
339series of increasing
340value. When an initialization expression is omitted for a <code>const</code>,
341it reuses the preceding expression.
342
343<pre>
Russ Cox2a63f5d2009-11-08 01:08:26 -0800344const (
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800345 red = iota // red == 0
346 blue // blue == 1
Russ Cox2a63f5d2009-11-08 01:08:26 -0800347 green // green == 2
348)
Larry Hosken698c6c02009-09-17 08:05:12 -0700349</pre>
350
351<h2 id="Slices">Slices</h2>
352
353<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700354A slice is conceptually a struct with three fields: a
355pointer to an array, a length, and a capacity.
356Slices support
357the <code>[]</code> operator to access elements of the underlying array.
358The builtin
Larry Hosken698c6c02009-09-17 08:05:12 -0700359<code>len</code> function returns the
360length of the slice. The builtin <code>cap</code> function returns the
361capacity.
362
363<p>
364Given an array, or another slice, a new slice is created via
365<code>a[I:J]</code>. This
366creates a new slice which refers to <code>a</code>, starts at
Russ Cox2a63f5d2009-11-08 01:08:26 -0800367index <code>I</code>, and ends before index
368<code>J</code>. It has length <code>J - I</code>.
Rob Pike6ac19ec2009-11-01 20:57:13 -0800369The new slice refers to the same array
Larry Hosken698c6c02009-09-17 08:05:12 -0700370to which <code>a</code>
371refers. That is, changes made using the new slice may be seen using
372<code>a</code>. The
373capacity of the new slice is simply the capacity of <code>a</code> minus
374<code>I</code>. The capacity
Russ Cox2a63f5d2009-11-08 01:08:26 -0800375of an array is the length of the array. You may also assign an array pointer
376to a variable of slice type; given <code>var s []int; var a[10] int</code>,
Andrey Mirtchovski9a445782010-03-09 14:21:34 -0800377the assignment <code>s = &amp;a</code> is equivalent to
Russ Cox2a63f5d2009-11-08 01:08:26 -0800378<code>s = a[0:len(a)]</code>.
Larry Hosken698c6c02009-09-17 08:05:12 -0700379
380<p>
381What this means is that Go uses slices for some cases where C++ uses pointers.
382If you create a value of type <code>[100]byte</code> (an array of 100 bytes,
383perhaps a
384buffer) and you want to pass it to a function without copying it, you should
385declare the function parameter to have type <code>[]byte</code>, and pass the
386address
Russ Cox2a63f5d2009-11-08 01:08:26 -0800387of the array. Unlike in C++, it is not
Larry Hosken698c6c02009-09-17 08:05:12 -0700388necessary to pass the length of the buffer; it is efficiently accessible via
389<code>len</code>.
390
391<p>
392The slice syntax may also be used with a string. It returns a new string,
393whose value is a substring of the original string.
Rob Pike6ac19ec2009-11-01 20:57:13 -0800394Because strings are immutable, string slices can be implemented
395without allocating new storage for the slices's contents.
Larry Hosken698c6c02009-09-17 08:05:12 -0700396
397<h2 id="Making_values">Making values</h2>
398
399<p>
400Go has a builtin function <code>new</code> which takes a type and
401allocates space
402on the heap. The allocated space will be zero-initialized for the type.
Rob Pike6ac19ec2009-11-01 20:57:13 -0800403For example, <code>new(int)</code> allocates a new int on the heap,
404initializes it with the value <code>0</code>,
405and returns its address, which has type <code>*int</code>.
406Unlike in C++, <code>new</code> is a function, not an operator;
Larry Hosken698c6c02009-09-17 08:05:12 -0700407<code>new int</code> is a syntax error.
408
409<p>
410Map and channel values must be allocated using the builtin function
411<code>make</code>.
412A variable declared with map or channel type without an initializer will be
413automatically initialized to <code>nil</code>.
414Calling <code>make(map[int]int)</code> returns a newly allocated value of
415type <code>map[int]int</code>.
416Note that <code>make</code> returns a value, not a pointer. This is
417consistent with
418the fact that map and channel values are passed by reference. Calling
419<code>make</code> with
420a map type takes an optional argument which is the expected capacity of the
421map. Calling <code>make</code> with a channel type takes an optional
Rob Pike6ac19ec2009-11-01 20:57:13 -0800422argument which sets the
423buffering capacity of the channel; the default is 0 (unbuffered).
Larry Hosken698c6c02009-09-17 08:05:12 -0700424
425<p>
426The <code>make</code> function may also be used to allocate a slice.
427In this case it
428allocates memory for the underlying array and returns a slice referring to it.
429There is one required argument, which is the number of elements in the slice.
430A second, optional, argument is the capacity of the slice. For example,
431<code>make([]int, 10, 20)</code>. This is identical to
432<code>new([20]int)[0:10]</code>. Since
433Go uses garbage collection, the newly allocated array will be discarded
434sometime after there are no references to the returned slice.
435
436<h2 id="Interfaces">Interfaces</h2>
437
438<p>
Rob Pike6ac19ec2009-11-01 20:57:13 -0800439Where C++ provides classes, subclasses and templates,
440Go provides interfaces. A
Larry Hosken698c6c02009-09-17 08:05:12 -0700441Go interface is similar to a C++ pure abstract class: a class with no
442data members, with methods which are all pure virtual. However, in
443Go, any type which provides the methods named in the interface may be
444treated as an implementation of the interface. No explicitly declared
445inheritance is required. The implementation of the interface is
446entirely separate from the interface itself.
447
448<p>
449A method looks like an ordinary function definition, except that it
Ian Lance Taylore2854872009-10-12 15:43:13 -0700450has a <em>receiver</em>. The receiver is similar to
451the <code>this</code> pointer in a C++ class method.
Larry Hosken698c6c02009-09-17 08:05:12 -0700452
453<pre>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700454type myType struct { i int }
455func (p *myType) get() int { return p.i }
Larry Hosken698c6c02009-09-17 08:05:12 -0700456</pre>
457
458<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700459This declares a method <code>get</code> associated with <code>myType</code>.
Larry Hosken698c6c02009-09-17 08:05:12 -0700460The receiver is named <code>p</code> in the body of the function.
461
462<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700463Methods are defined on named types. If you convert the value
464to a different type, the new value will have the methods of the new type,
465not the old type.
466
467<p>
468You may define methods on a builtin type by declaring a new named type
469derived from it. The new type is distinct from the builtin type.
470
471<pre>
472type myInteger int
473func (p myInteger) get() int { return int(p) } // Conversion required.
474func f(i int) { }
475var v myInteger
476// f(v) is invalid.
477// f(int(v)) is valid; int(v) has no defined methods.
478</pre>
479
480<p>
Larry Hosken698c6c02009-09-17 08:05:12 -0700481Given this interface:
482
483<pre>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700484type myInterface interface {
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800485 get() int
486 set(i int)
Larry Hosken698c6c02009-09-17 08:05:12 -0700487}
488</pre>
489
490<p>
Russ Cox2a63f5d2009-11-08 01:08:26 -0800491we can make <code>myType</code> satisfy the interface by adding
Larry Hosken698c6c02009-09-17 08:05:12 -0700492
493<pre>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700494func (p *myType) set(i int) { p.i = i }
Larry Hosken698c6c02009-09-17 08:05:12 -0700495</pre>
496
497<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700498Now any function which takes <code>myInterface</code> as a parameter
Larry Hosken698c6c02009-09-17 08:05:12 -0700499will accept a
Ian Lance Taylore2854872009-10-12 15:43:13 -0700500variable of type <code>*myType</code>.
Larry Hosken698c6c02009-09-17 08:05:12 -0700501
502<pre>
Rob Pike6ac19ec2009-11-01 20:57:13 -0800503func getAndSet(x myInterface) {}
Larry Hosken698c6c02009-09-17 08:05:12 -0700504func f1() {
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800505 var p myType
506 getAndSet(&amp;p)
Larry Hosken698c6c02009-09-17 08:05:12 -0700507}
508</pre>
509
510<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700511In other words, if we view <code>myInterface</code> as a C++ pure abstract
Larry Hosken698c6c02009-09-17 08:05:12 -0700512base
513class, defining <code>set</code> and <code>get</code> for
Ian Lance Taylore2854872009-10-12 15:43:13 -0700514<code>*myType</code> made <code>*myType</code> automatically
515inherit from <code>myInterface</code>. A type may satisfy multiple interfaces.
Larry Hosken698c6c02009-09-17 08:05:12 -0700516
517<p>
518An anonymous field may be used to implement something much like a C++ child
519class.
520
521<pre>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700522type myChildType struct { myType; j int }
Russ Cox2a63f5d2009-11-08 01:08:26 -0800523func (p *myChildType) get() int { p.j++; return p.myType.get() }
Larry Hosken698c6c02009-09-17 08:05:12 -0700524</pre>
525
526<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700527This effectively implements <code>myChildType</code> as a child of
528<code>myType</code>.
Larry Hosken698c6c02009-09-17 08:05:12 -0700529
530<pre>
531func f2() {
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800532 var p myChildType
Ian Lance Taylore2854872009-10-12 15:43:13 -0700533 getAndSet(&amp;p)
Larry Hosken698c6c02009-09-17 08:05:12 -0700534}
535</pre>
536
537<p>
538The <code>set</code> method is effectively inherited from
Ian Lance Taylore2854872009-10-12 15:43:13 -0700539<code>myChildType</code>, because
Russ Cox2a63f5d2009-11-08 01:08:26 -0800540methods associated with the anonymous field are promoted to become methods
Ian Lance Taylore2854872009-10-12 15:43:13 -0700541of the enclosing type. In this case, because <code>myChildType</code> has an
542anonymous field of type <code>myType</code>, the methods of
543<code>myType</code> also become methods of <code>myChildType</code>.
Larry Hosken698c6c02009-09-17 08:05:12 -0700544In this example, the <code>get</code> method was
545overridden, and the <code>set</code> method was inherited.
546
547<p>
Russ Cox2a63f5d2009-11-08 01:08:26 -0800548This is not precisely the same as a child class in C++.
549When a method of an anonymous field is called,
550its receiver is the field, not the surrounding struct.
551In other words, methods on anonymous fields are not virtual functions.
552When you want the equivalent of a virtual function, use an interface.
Larry Hosken698c6c02009-09-17 08:05:12 -0700553
554<p>
555A variable which has an interface type may be converted to have a
Rob Pike6ac19ec2009-11-01 20:57:13 -0800556different interface type using a special construct called a type assertion.
557This is implemented dynamically
Rob Pike966bf712011-03-01 13:54:22 -0800558at run time, like C++ <code>dynamic_cast</code>. Unlike
Larry Hosken698c6c02009-09-17 08:05:12 -0700559<code>dynamic_cast</code>, there does
560not need to be any declared relationship between the two interfaces.
561
562<pre>
Rob Pike6ac19ec2009-11-01 20:57:13 -0800563type myPrintInterface interface {
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800564 print()
Larry Hosken698c6c02009-09-17 08:05:12 -0700565}
Ian Lance Taylore2854872009-10-12 15:43:13 -0700566func f3(x myInterface) {
Rob Pike6ac19ec2009-11-01 20:57:13 -0800567 x.(myPrintInterface).print() // type assertion to myPrintInterface
Larry Hosken698c6c02009-09-17 08:05:12 -0700568}
569</pre>
570
571<p>
Rob Pike6ac19ec2009-11-01 20:57:13 -0800572The conversion to <code>myPrintInterface</code> is entirely dynamic.
Larry Hosken698c6c02009-09-17 08:05:12 -0700573It will
Ian Lance Taylore2854872009-10-12 15:43:13 -0700574work as long as the underlying type of x (the <em>dynamic type</em>) defines
Larry Hosken698c6c02009-09-17 08:05:12 -0700575a <code>print</code> method.
576
577<p>
578Because the conversion is dynamic, it may be used to implement generic
Ian Lance Taylore2854872009-10-12 15:43:13 -0700579programming similar to templates in C++. This is done by
Larry Hosken698c6c02009-09-17 08:05:12 -0700580manipulating values of the minimal interface.
581
582<pre>
583type Any interface { }
584</pre>
585
586<p>
Rob Pike6ac19ec2009-11-01 20:57:13 -0800587Containers may be written in terms of <code>Any</code>, but the caller
588must unbox using a type assertion to recover
589values of the contained type. As the typing is dynamic rather
Larry Hosken698c6c02009-09-17 08:05:12 -0700590than static, there is no equivalent of the way that a C++ template may
591inline the relevant operations. The operations are fully type-checked
Rob Pike966bf712011-03-01 13:54:22 -0800592at run time, but all operations will involve a function call.
Larry Hosken698c6c02009-09-17 08:05:12 -0700593
594<pre>
595type iterator interface {
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800596 get() Any
597 set(v Any)
598 increment()
599 equal(arg *iterator) bool
Larry Hosken698c6c02009-09-17 08:05:12 -0700600}
601</pre>
602
Ian Lance Taylore2854872009-10-12 15:43:13 -0700603<h2 id="Goroutines">Goroutines</h2>
Larry Hosken698c6c02009-09-17 08:05:12 -0700604
605<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700606Go permits starting a new thread of execution (a <em>goroutine</em>)
607using the <code>go</code>
608statement. The <code>go</code> statement runs a function in a
609different, newly created, goroutine.
610All goroutines in a single program share the same address space.
611
612<p>
613Internally, goroutines act like coroutines that are multiplexed among
614multiple operating system threads. You do not have to worry
615about these details.
Larry Hosken698c6c02009-09-17 08:05:12 -0700616
617<pre>
Russ Cox2a63f5d2009-11-08 01:08:26 -0800618func server(i int) {
619 for {
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800620 print(i)
Russ Cox2a63f5d2009-11-08 01:08:26 -0800621 sys.sleep(10)
622 }
623}
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800624go server(1)
625go server(2)
Larry Hosken698c6c02009-09-17 08:05:12 -0700626</pre>
627
628<p>
629(Note that the <code>for</code> statement in the <code>server</code>
Rob Pike6ac19ec2009-11-01 20:57:13 -0800630function is equivalent to a C++ <code>while (true)</code> loop.)
Larry Hosken698c6c02009-09-17 08:05:12 -0700631
632<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700633Goroutines are (intended to be) cheap.
Larry Hosken698c6c02009-09-17 08:05:12 -0700634
635<p>
Rob Pike6ac19ec2009-11-01 20:57:13 -0800636Function literals (which Go implements as closures)
637can be useful with the <code>go</code> statement.
Larry Hosken698c6c02009-09-17 08:05:12 -0700638
639<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800640var g int
Larry Hosken698c6c02009-09-17 08:05:12 -0700641go func(i int) {
Ian Lance Taylore2854872009-10-12 15:43:13 -0700642 s := 0
643 for j := 0; j &lt; i; j++ { s += j }
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800644 g = s
645}(1000) // Passes argument 1000 to the function literal.
Larry Hosken698c6c02009-09-17 08:05:12 -0700646</pre>
647
648<h2 id="Channels">Channels</h2>
649
650<p>
Ian Lance Taylore2854872009-10-12 15:43:13 -0700651Channels are used to communicate between goroutines. Any value may be
Larry Hosken698c6c02009-09-17 08:05:12 -0700652sent over a channel. Channels are (intended to be) efficient and
653cheap. To send a value on a channel, use <code>&lt;-</code> as a binary
654operator. To
655receive a value on a channel, use <code>&lt;-</code> as a unary operator.
656When calling
657functions, channels are passed by reference.
658
659<p>
660The Go library provides mutexes, but you can also use
Ian Lance Taylore2854872009-10-12 15:43:13 -0700661a single goroutine with a shared channel.
Larry Hosken698c6c02009-09-17 08:05:12 -0700662Here is an example of using a manager function to control access to a
663single value.
664
665<pre>
666type cmd struct { get bool; val int }
667func manager(ch chan cmd) {
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800668 var val int = 0
Ian Lance Taylore2854872009-10-12 15:43:13 -0700669 for {
670 c := &lt;- ch
Andrew Gerrand7757fcc2010-09-17 12:39:01 +1000671 if c.get { c.val = val; ch &lt;- c }
Ian Lance Taylore2854872009-10-12 15:43:13 -0700672 else { val = c.val }
673 }
Larry Hosken698c6c02009-09-17 08:05:12 -0700674}
675</pre>
676
677<p>
Russ Cox2a63f5d2009-11-08 01:08:26 -0800678In that example the same channel is used for input and output.
679This is incorrect if there are multiple goroutines communicating
680with the manager at once: a goroutine waiting for a response
681from the manager might receive a request from another goroutine
682instead.
683A solution is to pass in a channel.
Larry Hosken698c6c02009-09-17 08:05:12 -0700684
685<pre>
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800686type cmd2 struct { get bool; val int; ch &lt;- chan int }
Larry Hosken698c6c02009-09-17 08:05:12 -0700687func manager2(ch chan cmd2) {
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800688 var val int = 0
Ian Lance Taylore2854872009-10-12 15:43:13 -0700689 for {
690 c := &lt;- ch
691 if c.get { c.ch &lt;- val }
692 else { val = c.val }
693 }
Larry Hosken698c6c02009-09-17 08:05:12 -0700694}
695</pre>
696
697<p>
Rob Pike6ac19ec2009-11-01 20:57:13 -0800698To use <code>manager2</code>, given a channel to it:
Larry Hosken698c6c02009-09-17 08:05:12 -0700699
700<pre>
701func f4(ch &lt;- chan cmd2) int {
Ian Lance Taylorbf575202010-01-29 16:37:50 -0800702 myCh := make(chan int)
703 c := cmd2{ true, 0, myCh } // Composite literal syntax.
704 ch &lt;- c
705 return &lt;-myCh
Larry Hosken698c6c02009-09-17 08:05:12 -0700706}
707</pre>