forked from golang/go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
effective_go.html
3664 lines (3319 loc) · 114 KB
/
effective_go.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--{
"Title": "Effective Go",
"Template": true
}-->
<h2 id="introduction">Introduction</h2>
<p>
Go is a new language. Although it borrows ideas from
existing languages,
it has unusual properties that make effective Go programs
different in character from programs written in its relatives.
A straightforward translation of a C++ or Java program into Go
is unlikely to produce a satisfactory result—Java programs
are written in Java, not Go.
On the other hand, thinking about the problem from a Go
perspective could produce a successful but quite different
program.
In other words,
to write Go well, it's important to understand its properties
and idioms.
It's also important to know the established conventions for
programming in Go, such as naming, formatting, program
construction, and so on, so that programs you write
will be easy for other Go programmers to understand.
</p>
<p>
This document gives tips for writing clear, idiomatic Go code.
It augments the <a href="/ref/spec">language specification</a>,
the <a href="//tour.golang.org/">Tour of Go</a>,
and <a href="/doc/code.html">How to Write Go Code</a>,
all of which you
should read first.
</p>
<h3 id="examples">Examples</h3>
<p>
The <a href="/src/">Go package sources</a>
are intended to serve not
only as the core library but also as examples of how to
use the language.
Moreover, many of the packages contain working, self-contained
executable examples you can run directly from the
<a href="//golang.org">golang.org</a> web site, such as
<a href="//golang.org/pkg/strings/#example_Map">this one</a> (if
necessary, click on the word "Example" to open it up).
If you have a question about how to approach a problem or how something
might be implemented, the documentation, code and examples in the
library can provide answers, ideas and
background.
</p>
<h2 id="formatting">Formatting</h2>
<p>
Formatting issues are the most contentious
but the least consequential.
People can adapt to different formatting styles
but it's better if they don't have to, and
less time is devoted to the topic
if everyone adheres to the same style.
The problem is how to approach this Utopia without a long
prescriptive style guide.
</p>
<p>
With Go we take an unusual
approach and let the machine
take care of most formatting issues.
The <code>gofmt</code> program
(also available as <code>go fmt</code>, which
operates at the package level rather than source file level)
reads a Go program
and emits the source in a standard style of indentation
and vertical alignment, retaining and if necessary
reformatting comments.
If you want to know how to handle some new layout
situation, run <code>gofmt</code>; if the answer doesn't
seem right, rearrange your program (or file a bug about <code>gofmt</code>),
don't work around it.
</p>
<p>
As an example, there's no need to spend time lining up
the comments on the fields of a structure.
<code>Gofmt</code> will do that for you. Given the
declaration
</p>
<pre>
type T struct {
name string // name of the object
value int // its value
}
</pre>
<p>
<code>gofmt</code> will line up the columns:
</p>
<pre>
type T struct {
name string // name of the object
value int // its value
}
</pre>
<p>
All Go code in the standard packages has been formatted with <code>gofmt</code>.
</p>
<p>
Some formatting details remain. Very briefly:
</p>
<dl>
<dt>Indentation</dt>
<dd>We use tabs for indentation and <code>gofmt</code> emits them by default.
Use spaces only if you must.
</dd>
<dt>Line length</dt>
<dd>
Go has no line length limit. Don't worry about overflowing a punched card.
If a line feels too long, wrap it and indent with an extra tab.
</dd>
<dt>Parentheses</dt>
<dd>
Go needs fewer parentheses than C and Java: control structures (<code>if</code>,
<code>for</code>, <code>switch</code>) do not have parentheses in
their syntax.
Also, the operator precedence hierarchy is shorter and clearer, so
<pre>
x<<8 + y<<16
</pre>
means what the spacing implies, unlike in the other languages.
</dd>
</dl>
<h2 id="commentary">Commentary</h2>
<p>
Go provides C-style <code>/* */</code> block comments
and C++-style <code>//</code> line comments.
Line comments are the norm;
block comments appear mostly as package comments, but
are useful within an expression or to disable large swaths of code.
</p>
<p>
The program—and web server—<code>godoc</code> processes
Go source files to extract documentation about the contents of the
package.
Comments that appear before top-level declarations, with no intervening newlines,
are extracted along with the declaration to serve as explanatory text for the item.
The nature and style of these comments determines the
quality of the documentation <code>godoc</code> produces.
</p>
<p>
Every package should have a <i>package comment</i>, a block
comment preceding the package clause.
For multi-file packages, the package comment only needs to be
present in one file, and any one will do.
The package comment should introduce the package and
provide information relevant to the package as a whole.
It will appear first on the <code>godoc</code> page and
should set up the detailed documentation that follows.
</p>
<pre>
/*
Package regexp implements a simple library for regular expressions.
The syntax of the regular expressions accepted is:
regexp:
concatenation { '|' concatenation }
concatenation:
{ closure }
closure:
term [ '*' | '+' | '?' ]
term:
'^'
'$'
'.'
character
'[' [ '^' ] character-ranges ']'
'(' regexp ')'
*/
package regexp
</pre>
<p>
If the package is simple, the package comment can be brief.
</p>
<pre>
// Package path implements utility routines for
// manipulating slash-separated filename paths.
</pre>
<p>
Comments do not need extra formatting such as banners of stars.
The generated output may not even be presented in a fixed-width font, so don't depend
on spacing for alignment—<code>godoc</code>, like <code>gofmt</code>,
takes care of that.
The comments are uninterpreted plain text, so HTML and other
annotations such as <code>_this_</code> will reproduce <i>verbatim</i> and should
not be used.
One adjustment <code>godoc</code> does do is to display indented
text in a fixed-width font, suitable for program snippets.
The package comment for the
<a href="/pkg/fmt/"><code>fmt</code> package</a> uses this to good effect.
</p>
<p>
Depending on the context, <code>godoc</code> might not even
reformat comments, so make sure they look good straight up:
use correct spelling, punctuation, and sentence structure,
fold long lines, and so on.
</p>
<p>
Inside a package, any comment immediately preceding a top-level declaration
serves as a <i>doc comment</i> for that declaration.
Every exported (capitalized) name in a program should
have a doc comment.
</p>
<p>
Doc comments work best as complete sentences, which allow
a wide variety of automated presentations.
The first sentence should be a one-sentence summary that
starts with the name being declared.
</p>
<pre>
// Compile parses a regular expression and returns, if successful, a Regexp
// object that can be used to match against text.
func Compile(str string) (regexp *Regexp, err error) {
</pre>
<p>
If the name always begins the comment, the output of <code>godoc</code>
can usefully be run through <code>grep</code>.
Imagine you couldn't remember the name "Compile" but were looking for
the parsing function for regular expressions, so you ran
the command,
</p>
<pre>
$ godoc regexp | grep parse
</pre>
<p>
If all the doc comments in the package began, "This function...", <code>grep</code>
wouldn't help you remember the name. But because the package starts each
doc comment with the name, you'd see something like this,
which recalls the word you're looking for.
</p>
<pre>
$ godoc regexp | grep parse
Compile parses a regular expression and returns, if successful, a Regexp
parsed. It simplifies safe initialization of global variables holding
cannot be parsed. It simplifies safe initialization of global variables
$
</pre>
<p>
Go's declaration syntax allows grouping of declarations.
A single doc comment can introduce a group of related constants or variables.
Since the whole declaration is presented, such a comment can often be perfunctory.
</p>
<pre>
// Error codes returned by failures to parse an expression.
var (
ErrInternal = errors.New("regexp: internal error")
ErrUnmatchedLpar = errors.New("regexp: unmatched '('")
ErrUnmatchedRpar = errors.New("regexp: unmatched ')'")
...
)
</pre>
<p>
Grouping can also indicate relationships between items,
such as the fact that a set of variables is protected by a mutex.
</p>
<pre>
var (
countLock sync.Mutex
inputCount uint32
outputCount uint32
errorCount uint32
)
</pre>
<h2 id="names">Names</h2>
<p>
Names are as important in Go as in any other language.
They even have semantic effect:
the visibility of a name outside a package is determined by whether its
first character is upper case.
It's therefore worth spending a little time talking about naming conventions
in Go programs.
</p>
<h3 id="package-names">Package names</h3>
<p>
When a package is imported, the package name becomes an accessor for the
contents. After
</p>
<pre>
import "bytes"
</pre>
<p>
the importing package can talk about <code>bytes.Buffer</code>. It's
helpful if everyone using the package can use the same name to refer to
its contents, which implies that the package name should be good:
short, concise, evocative. By convention, packages are given
lower case, single-word names; there should be no need for underscores
or mixedCaps.
Err on the side of brevity, since everyone using your
package will be typing that name.
And don't worry about collisions <i>a priori</i>.
The package name is only the default name for imports; it need not be unique
across all source code, and in the rare case of a collision the
importing package can choose a different name to use locally.
In any case, confusion is rare because the file name in the import
determines just which package is being used.
</p>
<p>
Another convention is that the package name is the base name of
its source directory;
the package in <code>src/encoding/base64</code>
is imported as <code>"encoding/base64"</code> but has name <code>base64</code>,
not <code>encoding_base64</code> and not <code>encodingBase64</code>.
</p>
<p>
The importer of a package will use the name to refer to its contents,
so exported names in the package can use that fact
to avoid stutter.
(Don't use the <code>import .</code> notation, which can simplify
tests that must run outside the package they are testing, but should otherwise be avoided.)
For instance, the buffered reader type in the <code>bufio</code> package is called <code>Reader</code>,
not <code>BufReader</code>, because users see it as <code>bufio.Reader</code>,
which is a clear, concise name.
Moreover,
because imported entities are always addressed with their package name, <code>bufio.Reader</code>
does not conflict with <code>io.Reader</code>.
Similarly, the function to make new instances of <code>ring.Ring</code>—which
is the definition of a <em>constructor</em> in Go—would
normally be called <code>NewRing</code>, but since
<code>Ring</code> is the only type exported by the package, and since the
package is called <code>ring</code>, it's called just <code>New</code>,
which clients of the package see as <code>ring.New</code>.
Use the package structure to help you choose good names.
</p>
<p>
Another short example is <code>once.Do</code>;
<code>once.Do(setup)</code> reads well and would not be improved by
writing <code>once.DoOrWaitUntilDone(setup)</code>.
Long names don't automatically make things more readable.
A helpful doc comment can often be more valuable than an extra long name.
</p>
<h3 id="Getters">Getters</h3>
<p>
Go doesn't provide automatic support for getters and setters.
There's nothing wrong with providing getters and setters yourself,
and it's often appropriate to do so, but it's neither idiomatic nor necessary
to put <code>Get</code> into the getter's name. If you have a field called
<code>owner</code> (lower case, unexported), the getter method should be
called <code>Owner</code> (upper case, exported), not <code>GetOwner</code>.
The use of upper-case names for export provides the hook to discriminate
the field from the method.
A setter function, if needed, will likely be called <code>SetOwner</code>.
Both names read well in practice:
</p>
<pre>
owner := obj.Owner()
if owner != user {
obj.SetOwner(user)
}
</pre>
<h3 id="interface-names">Interface names</h3>
<p>
By convention, one-method interfaces are named by
the method name plus an -er suffix or similar modification
to construct an agent noun: <code>Reader</code>,
<code>Writer</code>, <code>Formatter</code>,
<code>CloseNotifier</code> etc.
</p>
<p>
There are a number of such names and it's productive to honor them and the function
names they capture.
<code>Read</code>, <code>Write</code>, <code>Close</code>, <code>Flush</code>,
<code>String</code> and so on have
canonical signatures and meanings. To avoid confusion,
don't give your method one of those names unless it
has the same signature and meaning.
Conversely, if your type implements a method with the
same meaning as a method on a well-known type,
give it the same name and signature;
call your string-converter method <code>String</code> not <code>ToString</code>.
</p>
<h3 id="mixed-caps">MixedCaps</h3>
<p>
Finally, the convention in Go is to use <code>MixedCaps</code>
or <code>mixedCaps</code> rather than underscores to write
multiword names.
</p>
<h2 id="semicolons">Semicolons</h2>
<p>
Like C, Go's formal grammar uses semicolons to terminate statements,
but unlike in C, those semicolons do not appear in the source.
Instead the lexer uses a simple rule to insert semicolons automatically
as it scans, so the input text is mostly free of them.
</p>
<p>
The rule is this. If the last token before a newline is an identifier
(which includes words like <code>int</code> and <code>float64</code>),
a basic literal such as a number or string constant, or one of the
tokens
</p>
<pre>
break continue fallthrough return ++ -- ) }
</pre>
<p>
the lexer always inserts a semicolon after the token.
This could be summarized as, “if the newline comes
after a token that could end a statement, insert a semicolon”.
</p>
<p>
A semicolon can also be omitted immediately before a closing brace,
so a statement such as
</p>
<pre>
go func() { for { dst <- <-src } }()
</pre>
<p>
needs no semicolons.
Idiomatic Go programs have semicolons only in places such as
<code>for</code> loop clauses, to separate the initializer, condition, and
continuation elements. They are also necessary to separate multiple
statements on a line, should you write code that way.
</p>
<p>
One consequence of the semicolon insertion rules
is that you cannot put the opening brace of a
control structure (<code>if</code>, <code>for</code>, <code>switch</code>,
or <code>select</code>) on the next line. If you do, a semicolon
will be inserted before the brace, which could cause unwanted
effects. Write them like this
</p>
<pre>
if i < f() {
g()
}
</pre>
<p>
not like this
</p>
<pre>
if i < f() // wrong!
{ // wrong!
g()
}
</pre>
<h2 id="control-structures">Control structures</h2>
<p>
The control structures of Go are related to those of C but differ
in important ways.
There is no <code>do</code> or <code>while</code> loop, only a
slightly generalized
<code>for</code>;
<code>switch</code> is more flexible;
<code>if</code> and <code>switch</code> accept an optional
initialization statement like that of <code>for</code>;
<code>break</code> and <code>continue</code> statements
take an optional label to identify what to break or continue;
and there are new control structures including a type switch and a
multiway communications multiplexer, <code>select</code>.
The syntax is also slightly different:
there are no parentheses
and the bodies must always be brace-delimited.
</p>
<h3 id="if">If</h3>
<p>
In Go a simple <code>if</code> looks like this:
</p>
<pre>
if x > 0 {
return y
}
</pre>
<p>
Mandatory braces encourage writing simple <code>if</code> statements
on multiple lines. It's good style to do so anyway,
especially when the body contains a control statement such as a
<code>return</code> or <code>break</code>.
</p>
<p>
Since <code>if</code> and <code>switch</code> accept an initialization
statement, it's common to see one used to set up a local variable.
</p>
<pre>
if err := file.Chmod(0664); err != nil {
log.Print(err)
return err
}
</pre>
<p id="else">
In the Go libraries, you'll find that
when an <code>if</code> statement doesn't flow into the next statement—that is,
the body ends in <code>break</code>, <code>continue</code>,
<code>goto</code>, or <code>return</code>—the unnecessary
<code>else</code> is omitted.
</p>
<pre>
f, err := os.Open(name)
if err != nil {
return err
}
codeUsing(f)
</pre>
<p>
This is an example of a common situation where code must guard against a
sequence of error conditions. The code reads well if the
successful flow of control runs down the page, eliminating error cases
as they arise. Since error cases tend to end in <code>return</code>
statements, the resulting code needs no <code>else</code> statements.
</p>
<pre>
f, err := os.Open(name)
if err != nil {
return err
}
d, err := f.Stat()
if err != nil {
f.Close()
return err
}
codeUsing(f, d)
</pre>
<h3 id="redeclaration">Redeclaration and reassignment</h3>
<p>
An aside: The last example in the previous section demonstrates a detail of how the
<code>:=</code> short declaration form works.
The declaration that calls <code>os.Open</code> reads,
</p>
<pre>
f, err := os.Open(name)
</pre>
<p>
This statement declares two variables, <code>f</code> and <code>err</code>.
A few lines later, the call to <code>f.Stat</code> reads,
</p>
<pre>
d, err := f.Stat()
</pre>
<p>
which looks as if it declares <code>d</code> and <code>err</code>.
Notice, though, that <code>err</code> appears in both statements.
This duplication is legal: <code>err</code> is declared by the first statement,
but only <em>re-assigned</em> in the second.
This means that the call to <code>f.Stat</code> uses the existing
<code>err</code> variable declared above, and just gives it a new value.
</p>
<p>
In a <code>:=</code> declaration a variable <code>v</code> may appear even
if it has already been declared, provided:
</p>
<ul>
<li>this declaration is in the same scope as the existing declaration of <code>v</code>
(if <code>v</code> is already declared in an outer scope, the declaration will create a new variable §),</li>
<li>the corresponding value in the initialization is assignable to <code>v</code>, and</li>
<li>there is at least one other variable in the declaration that is being declared anew.</li>
</ul>
<p>
This unusual property is pure pragmatism,
making it easy to use a single <code>err</code> value, for example,
in a long <code>if-else</code> chain.
You'll see it used often.
</p>
<p>
§ It's worth noting here that in Go the scope of function parameters and return values
is the same as the function body, even though they appear lexically outside the braces
that enclose the body.
</p>
<h3 id="for">For</h3>
<p>
The Go <code>for</code> loop is similar to—but not the same as—C's.
It unifies <code>for</code>
and <code>while</code> and there is no <code>do-while</code>.
There are three forms, only one of which has semicolons.
</p>
<pre>
// Like a C for
for init; condition; post { }
// Like a C while
for condition { }
// Like a C for(;;)
for { }
</pre>
<p>
Short declarations make it easy to declare the index variable right in the loop.
</p>
<pre>
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
</pre>
<p>
If you're looping over an array, slice, string, or map,
or reading from a channel, a <code>range</code> clause can
manage the loop.
</p>
<pre>
for key, value := range oldMap {
newMap[key] = value
}
</pre>
<p>
If you only need the first item in the range (the key or index), drop the second:
</p>
<pre>
for key := range m {
if key.expired() {
delete(m, key)
}
}
</pre>
<p>
If you only need the second item in the range (the value), use the <em>blank identifier</em>, an underscore, to discard the first:
</p>
<pre>
sum := 0
for _, value := range array {
sum += value
}
</pre>
<p>
The blank identifier has many uses, as described in <a href="#blank">a later section</a>.
</p>
<p>
For strings, the <code>range</code> does more work for you, breaking out individual
Unicode code points by parsing the UTF-8.
Erroneous encodings consume one byte and produce the
replacement rune U+FFFD.
(The name (with associated builtin type) <code>rune</code> is Go terminology for a
single Unicode code point.
See <a href="/ref/spec#Rune_literals">the language specification</a>
for details.)
The loop
</p>
<pre>
for pos, char := range "日本\x80語" { // \x80 is an illegal UTF-8 encoding
fmt.Printf("character %#U starts at byte position %d\n", char, pos)
}
</pre>
<p>
prints
</p>
<pre>
character U+65E5 '日' starts at byte position 0
character U+672C '本' starts at byte position 3
character U+FFFD '�' starts at byte position 6
character U+8A9E '語' starts at byte position 7
</pre>
<p>
Finally, Go has no comma operator and <code>++</code> and <code>--</code>
are statements not expressions.
Thus if you want to run multiple variables in a <code>for</code>
you should use parallel assignment (although that precludes <code>++</code> and <code>--</code>).
</p>
<pre>
// Reverse a
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
</pre>
<h3 id="switch">Switch</h3>
<p>
Go's <code>switch</code> is more general than C's.
The expressions need not be constants or even integers,
the cases are evaluated top to bottom until a match is found,
and if the <code>switch</code> has no expression it switches on
<code>true</code>.
It's therefore possible—and idiomatic—to write an
<code>if</code>-<code>else</code>-<code>if</code>-<code>else</code>
chain as a <code>switch</code>.
</p>
<pre>
func unhex(c byte) byte {
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
</pre>
<p>
There is no automatic fall through, but cases can be presented
in comma-separated lists.
</p>
<pre>
func shouldEscape(c byte) bool {
switch c {
case ' ', '?', '&', '=', '#', '+', '%':
return true
}
return false
}
</pre>
<p>
Although they are not nearly as common in Go as some other C-like
languages, <code>break</code> statements can be used to terminate
a <code>switch</code> early.
Sometimes, though, it's necessary to break out of a surrounding loop,
not the switch, and in Go that can be accomplished by putting a label
on the loop and "breaking" to that label.
This example shows both uses.
</p>
<pre>
Loop:
for n := 0; n < len(src); n += size {
switch {
case src[n] < sizeOne:
if validateOnly {
break
}
size = 1
update(src[n])
case src[n] < sizeTwo:
if n+1 >= len(src) {
err = errShortInput
break Loop
}
if validateOnly {
break
}
size = 2
update(src[n] + src[n+1]<<shift)
}
}
</pre>
<p>
Of course, the <code>continue</code> statement also accepts an optional label
but it applies only to loops.
</p>
<p>
To close this section, here's a comparison routine for byte slices that uses two
<code>switch</code> statements:
</p>
<pre>
// Compare returns an integer comparing the two byte slices,
// lexicographically.
// The result will be 0 if a == b, -1 if a < b, and +1 if a > b
func Compare(a, b []byte) int {
for i := 0; i < len(a) && i < len(b); i++ {
switch {
case a[i] > b[i]:
return 1
case a[i] < b[i]:
return -1
}
}
switch {
case len(a) > len(b):
return 1
case len(a) < len(b):
return -1
}
return 0
}
</pre>
<h3 id="type_switch">Type switch</h3>
<p>
A switch can also be used to discover the dynamic type of an interface
variable. Such a <em>type switch</em> uses the syntax of a type
assertion with the keyword <code>type</code> inside the parentheses.
If the switch declares a variable in the expression, the variable will
have the corresponding type in each clause.
It's also idiomatic to reuse the name in such cases, in effect declaring
a new variable with the same name but a different type in each case.
</p>
<pre>
var t interface{}
t = functionOfSomeType()
switch t := t.(type) {
default:
fmt.Printf("unexpected type %T\n", t) // %T prints whatever type t has
case bool:
fmt.Printf("boolean %t\n", t) // t has type bool
case int:
fmt.Printf("integer %d\n", t) // t has type int
case *bool:
fmt.Printf("pointer to boolean %t\n", *t) // t has type *bool
case *int:
fmt.Printf("pointer to integer %d\n", *t) // t has type *int
}
</pre>
<h2 id="functions">Functions</h2>
<h3 id="multiple-returns">Multiple return values</h3>
<p>
One of Go's unusual features is that functions and methods
can return multiple values. This form can be used to
improve on a couple of clumsy idioms in C programs: in-band
error returns such as <code>-1</code> for <code>EOF</code>
and modifying an argument passed by address.
</p>
<p>
In C, a write error is signaled by a negative count with the
error code secreted away in a volatile location.
In Go, <code>Write</code>
can return a count <i>and</i> an error: “Yes, you wrote some
bytes but not all of them because you filled the device”.
The signature of the <code>Write</code> method on files from
package <code>os</code> is:
</p>
<pre>
func (file *File) Write(b []byte) (n int, err error)
</pre>
<p>
and as the documentation says, it returns the number of bytes
written and a non-nil <code>error</code> when <code>n</code>
<code>!=</code> <code>len(b)</code>.
This is a common style; see the section on error handling for more examples.
</p>
<p>
A similar approach obviates the need to pass a pointer to a return
value to simulate a reference parameter.
Here's a simple-minded function to
grab a number from a position in a byte slice, returning the number
and the next position.
</p>
<pre>
func nextInt(b []byte, i int) (int, int) {
for ; i < len(b) && !isDigit(b[i]); i++ {
}
x := 0
for ; i < len(b) && isDigit(b[i]); i++ {
x = x*10 + int(b[i]) - '0'
}
return x, i
}
</pre>
<p>
You could use it to scan the numbers in an input slice <code>b</code> like this:
</p>
<pre>
for i := 0; i < len(b); {
x, i = nextInt(b, i)
fmt.Println(x)
}
</pre>
<h3 id="named-results">Named result parameters</h3>
<p>
The return or result "parameters" of a Go function can be given names and
used as regular variables, just like the incoming parameters.
When named, they are initialized to the zero values for their types when
the function begins; if the function executes a <code>return</code> statement
with no arguments, the current values of the result parameters are
used as the returned values.
</p>
<p>
The names are not mandatory but they can make code shorter and clearer:
they're documentation.
If we name the results of <code>nextInt</code> it becomes
obvious which returned <code>int</code>
is which.
</p>
<pre>
func nextInt(b []byte, pos int) (value, nextPos int) {
</pre>
<p>
Because named results are initialized and tied to an unadorned return, they can simplify
as well as clarify. Here's a version
of <code>io.ReadFull</code> that uses them well:
</p>
<pre>
func ReadFull(r Reader, buf []byte) (n int, err error) {
for len(buf) > 0 && err == nil {
var nr int
nr, err = r.Read(buf)
n += nr
buf = buf[nr:]
}
return
}
</pre>
<h3 id="defer">Defer</h3>
<p>
Go's <code>defer</code> statement schedules a function call (the
<i>deferred</i> function) to be run immediately before the function
executing the <code>defer</code> returns. It's an unusual but
effective way to deal with situations such as resources that must be
released regardless of which path a function takes to return. The
canonical examples are unlocking a mutex or closing a file.
</p>
<pre>
// Contents returns the file's contents as a string.
func Contents(filename string) (string, error) {
f, err := os.Open(filename)