This repository has been archived by the owner on Aug 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy patheffective_go.html
7239 lines (6252 loc) · 220 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": "实效Go编程",
"Subtitle": "版本:2013年12月22日",
"Template": true
}-->
<!--{
"Title": "Effective Go",
"Template": true
}-->
<div class="english">
<h2 id="introduction">Introduction</h2>
</div>
<h2 id="引言">引言</h2>
<div class="english">
<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>
</div>
<p>
Go 是一门全新的语言。尽管它从既有的语言中借鉴了许多理念,但其与众不同的特性,
使得使用Go编程在本质上就不同于其它语言。将现有的C++或Java程序直译为Go
程序并不能令人满意——毕竟Java程序是用Java编写的,而不是Go。
另一方面,若从Go的角度去分析问题,你就能编写出同样可行但大不相同的程序。
换句话说,要想将Go程序写得好,就必须理解其特性和风格。了解命名、格式化、
程序结构等既定规则也同样重要,这样你编写的程序才能更容易被其他程序员所理解。
</p>
<div class="english">
<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>
</div>
<p>
本文档就如何编写清晰、地道的Go代码提供了一些技巧。它是对<a href="/ref/spec">语言规范</a>、
<a href="https://go-tour-zh.appspot.com/">Go语言之旅</a>以及
<a href="/doc/code.html">如何使用Go编程</a>的补充说明,因此我们建议您先阅读这些文档。
</p>
<div class="english">
<h3 id="examples">Examples</h3>
</div>
<h3 id="示例">示例</h3>
<div class="english">
<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>
</div>
<p>
<a href="/src/pkg/">Go包的源码</a>不仅是核心库,同时也是学习如何使用Go语言的示例源码。
此外,其中的一些包还包含了可工作的,独立的可执行示例,你可以直接在
<a href="http://golang.org">golang.org</a>网站上运行它们,比如
<a href="http://zh.golanger.com/pkg/strings/#example_Map">这个例子</a>
(单击文字“示例”来展开它)。如果你有任何关于某些问题如何解决,或某些东西如何实现的疑问,
也可以从中获取相关的答案、思路以及后台实现。
</p>
<div class="english">
<h2 id="formatting">Formatting</h2>
</div>
<h2 id="格式化">格式化</h2>
<div class="english">
<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>
</div>
<p>
格式化问题总是充满了争议,但却始终没有形成统一的定论。虽说人们可以适应不同的编码风格,
但抛弃这种适应过程岂不更好?若所有人都遵循相同的编码风格,在这类问题上浪费的时间将会更少。
问题就在于如何实现这种设想,而无需冗长的语言风格规范。
</p>
<div class="english">
<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>
</div>
<p>
在Go中我们另辟蹊径,让机器来处理大部分的格式化问题。<code>gofmt</code>
程序(也可用 <code>go fmt</code>,它以包为处理对象而非源文件)将Go程序按照标准风格缩进、
对齐,保留注释并在需要时重新格式化。若你想知道如何处理一些新的代码布局,请尝试运行
<code>gofmt</code>;若结果仍不尽人意,请重新组织你的程序(或提交有关 <code>gofmt</code>
的Bug),而不必为此纠结。
</p>
<div class="english">
<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>
</div>
<p>
举例来说,你无需花时间将结构体中的字段注释对齐,<code>gofmt</code> 将为你代劳。
假如有以下声明:
</p>
<div class="english">
<pre>
type T struct {
name string // name of the object
value int // its value
}
</pre>
</div>
<pre>
type T struct {
name string // 对象名
value int // 对象值
}
</pre>
<div class="english">
<p>
<code>gofmt</code> will line up the columns:
</p>
</div>
<p>
<code>gofmt</code> 会将它按列对齐为:
</p>
<div class="english">
<pre>
type T struct {
name string // name of the object
value int // its value
}
</pre>
</div>
<pre>
type T struct {
name string // 对象名
value int // 对象值
}
</pre>
<div class="english">
<p>
All Go code in the standard packages has been formatted with <code>gofmt</code>.
</p>
</div>
<p>
标准包中所有的Go代码都已经用 <code>gofmt</code> 格式化过了。
</p>
<div class="english">
<p>
Some formatting details remain. Very briefly:
</p>
</div>
<p>
还有一些关于格式化的细节,它们非常简短:
</p>
<div class="english">
<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>
</div>
<dl>
<dt>缩进</dt>
<dd>
我们使用制表符(tab)缩进,<code>gofmt</code> 默认也使用它。在你认为确实有必要时再使用空格。
</dd>
<dt>行的长度</dt>
<dd>
Go对行的长度没有限制,别担心打孔纸不够长。如果一行实在太长,也可进行折行并插入适当的tab缩进。
</dd>
<dt>括号</dt>
<dd>
比起C和Java,Go所需的括号更少:控制结构(<code>if</code>、<code>for</code> 和
<code>switch</code>)在语法上并不需要圆括号。此外,操作符优先级处理变得更加简洁,因此
<pre>
x<<8 + y<<16
</pre>
正表述了空格符所传达的含义。
</dd>
</dl>
<div class="english">
<h2 id="commentary">Commentary</h2>
</div>
<h2 id="注释">注释</h2>
<div class="english">
<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>
</div>
<p>
Go语言支持C风格的块注释 <code>/* */</code> 和C++风格的行注释 <code>//</code>。
行注释更为常用,而块注释则主要用作包的注释,当然也可在禁用一大段代码时使用。
</p>
<div class="english">
<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>
</div>
<p>
<code>godoc</code> 既是一个程序,又是一个Web服务器,它对Go的源码进行处理,并提取包中的文档内容。
出现在顶级声明之前,且与该声明之间没有空行的注释,将与该声明一起被提取出来,作为该条目的说明文档。
这些注释的类型和风格决定了 <code>godoc</code> 生成的文档质量。
</p>
<div class="english">
<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>
</div>
<p>
每个包都应包含一段<b>包注释</b>,即放置在包子句前的一个块注释。对于包含多个文件的包,
包注释只需出现在其中的任一文件中即可。包注释应在整体上对该包进行介绍,并提供包的相关信息。
它将出现在 <code>godoc</code> 页面中的最上面,并为紧随其后的内容建立详细的文档。
</p>
<div class="english">
<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>
</div>
<pre>
/*
regexp 包为正则表达式实现了一个简单的库。
该库接受的正则表达式语法为:
正则表达式:
串联 { '|' 串联 }
串联:
{ 闭包 }
闭包:
条目 [ '*' | '+' | '?' ]
条目:
'^'
'$'
'.'
字符
'[' [ '^' ] 字符遍历 ']'
'(' 正则表达式 ')'
*/
package regexp
</pre>
<div class="english">
<p>
If the package is simple, the package comment can be brief.
</p>
</div>
<p>
若某个包比较简单,包注释同样可以简洁些。
</p>
<div class="english">
<pre>
// Package path implements utility routines for
// manipulating slash-separated filename paths.
</pre>
</div>
<pre>
// path 包实现了一些常用的工具,以便于操作用反斜杠分隔的路径.
</pre>
<div class="english">
<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>
</div>
<p>
注释无需进行额外的格式化,如用星号来突出等。生成的输出甚至可能无法以等宽字体显示,
因此不要依赖于空格对齐,<code>godoc</code> 会像 <code>gofmt</code> 那样处理好这一切。
注释是不会被解析的纯文本,因此像HTML或其它类似于 <code>_这样_</code> 的东西将按照
<b>原样</b> 输出,因此不应使用它们。<code>godoc</code> 所做的调整,
就是将已缩进的文本以等宽字体显示,来适应对应的程序片段。
<a href="http://golang.org/pkg/fmt/"><code>fmt</code> 包</a>的注释就用了这种不错的效果。
</p>
<div class="english">
<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>
</div>
<p>
<code>godoc</code> 是否会重新格式化注释取决于上下文,因此必须确保它们看起来清晰易辨:
使用正确的拼写、标点和语句结构以及折叠长行等。
</p>
<div class="english">
<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>
</div>
<p>
在包中,任何顶级声明前面的注释都将作为该声明的<b>文档注释</b>。
在程序中,每个可导出(首字母大写)的名称都应该有文档注释。
</p>
<div class="english">
<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>
</div>
<p>
文档注释最好是完整的句子,这样它才能适应各种自动化的展示。
第一句应当以被声明的东西开头,并且是单句的摘要。
</p>
<div class="english">
<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>
</div>
<pre>
// Compile 用于解析正则表达式并返回,如果成功,则 Regexp 对象就可用于匹配所针对的文本。
func Compile(str string) (regexp *Regexp, err error) {
</pre>
<div class="english">
<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>
</div>
<p>
若注释总是以名称开头,<code>godoc</code> 的输出就能通过 <code>grep</code>
变得更加有用。假如你记不住“Compile”这个名称,而又在找正则表达式的解析函数,
那就可以运行
</p>
<pre>
$ godoc regexp | grep parse
</pre>
<div class="english">
<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>
</div>
<p>
若包中的所有文档注释都以“此函数…”开头,<code>grep</code> 就无法帮你记住此名称。
但由于每个包的文档注释都以其名称开头,你就能看到这样的内容,它能显示你正在寻找的词语。
</p>
<div class="english">
<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>
</div>
<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>
<div class="english">
<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>
</div>
<p>
Go的声明语法允许成组声明。单个文档注释应介绍一组相关的常量或变量。
由于是整体声明,这种注释往往较为笼统。
</p>
<div class="english">
<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>
</div>
<pre>
// 表达式解析失败后返回错误代码。
var (
ErrInternal = errors.New("regexp: internal error")
ErrUnmatchedLpar = errors.New("regexp: unmatched '('")
ErrUnmatchedRpar = errors.New("regexp: unmatched ')'")
...
)
</pre>
<div class="english">
<p>
Grouping can also indicate relationships between items,
such as the fact that a set of variables is protected by a mutex.
</p>
</div>
<p>
即便是对于私有名称,也可通过成组声明来表明各项间的关系,例如某一组由互斥体保护的变量。
</p>
<pre>
var (
countLock sync.Mutex
inputCount uint32
outputCount uint32
errorCount uint32
)
</pre>
<div class="english">
<h2 id="names">Names</h2>
</div>
<h2 id="命名">命名</h2>
<div class="english">
<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>
</div>
<p>
正如命名在其它语言中的地位,它在 Go 中同样重要。有时它们甚至会影响语义:
例如,某个名称在包外是否可见,就取决于其首个字符是否为大写字母。
因此有必要花点时间来讨论Go程序中的命名约定。
</p>
<div class="english">
<h3 id="package-names">Package names</h3>
</div>
<h3 id="包名">包名</h3>
<div class="english">
<p>
When a package is imported, the package name becomes an accessor for the
contents. After
</p>
</div>
<p>
当一个包被导入后,包名就会成了内容的访问器。在
</p>
<pre>
import "bytes"
</pre>
<div class="english">
<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>
</div>
<p>
之后,被导入的包就能通过 <code>bytes.Buffer</code> 来引用了。
若所有人都以相同的名称来引用其内容将大有裨益,
这也就意味着包应当有个恰当的名称:其名称应该简洁明了而易于理解。按照惯例,
包应当以小写的单个单词来命名,且不应使用下划线或驼峰记法。<code>err</code>
的命名就是出于简短考虑的,因为任何使用该包的人都会键入该名称。
不必担心<b>引用次序</b>的冲突。包名就是导入时所需的唯一默认名称,
它并不需要在所有源码中保持唯一,即便在少数发生冲突的情况下,
也可为导入的包选择一个别名来局部使用。
无论如何,通过文件名来判定使用的包,都是不会产生混淆的。
</p>
<div class="english">
<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>
</div>
<p>
另一个约定就是包名应为其源码目录的基本名称。在 <code>src/pkg/encoding/base64</code>
中的包应作为 <code>"encoding/base64"</code> 导入,其包名应为 <code>base64</code>,
而非 <code>encoding_base64</code> 或 <code>encodingBase64</code>。
</p>
<div class="english">
<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>
</div>
<p>
包的导入者可通过包名来引用其内容,因此包中的可导出名称可以此来避免冲突。
(请勿使用 <code>import .</code> 记法,它可以简化必须在被测试包外运行的测试,
除此之外应尽量避免使用。)例如,<code>bufio</code> 包中的缓存读取器类型叫做
<code>Reader</code> 而非 <code>BufReader</code>,因为用户将它看做
<code>bufio.Reader</code>,这是个清楚而简洁的名称。
此外,由于被导入的项总是通过它们的包名来确定,因此 <code>bufio.Reader</code>
不会与 <code>io.Reader</code> 发生冲突。同样,用于创建 <code>ring.Ring</code>
的新实例的函数(这就是Go中的<strong>构造函数</strong>)一般会称之为
<code>NewRing</code>,但由于 <code>Ring</code> 是该包所导出的唯一类型,且该包也叫
<code>ring</code>,因此它可以只叫做 <code>New</code>,它跟在包的后面,就像
<code>ring.New</code>。使用包结构可以帮助你选择好的名称。
</p>
<div class="english">
<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>
</div>
<p>
另一个简短的例子是 <code>once.Do</code>,<code>once.Do(setup)</code> 表述足够清晰,
使用 <code>once.DoOrWaitUntilDone(setup)</code> 完全就是画蛇添足。
长命名并不会使其更具可读性。一份有用的说明文档通常比额外的长名更有价值。
</p>
<div class="english">
<h3 id="Getters">Getters</h3>
</div>
<h3 id="获取器">获取器</h3>
<div class="english">
<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>
</div>
<p>
Go并不对获取器(getter)和设置器(setter)提供自动支持。
你应当自己提供获取器和设置器,通常很值得这样做,但若要将 <code>Get</code>
放到获取器的名字中,既不符合习惯,也没有必要。若你有个名为 <code>owner</code>
(小写,未导出)的字段,其获取器应当名为 <code>Owner</code>(大写,可导出)而非
<code>GetOwner</code>。大写字母即为可导出的这种规定为区分方法和字段提供了便利。
若要提供设置器方法,<code>SetOwner</code> 是个不错的选择。两个命名看起来都很合理:
</p>
<pre>
owner := obj.Owner()
if owner != user {
obj.SetOwner(user)
}
</pre>
<div class="english">
<h3 id="interface-names">Interface names</h3>
</div>
<h3 id="接口名">接口名</h3>
<div class="english">
<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>
</div>
<p>
按照约定,只包含一个方法的接口应当以该方法的名称加上-er后缀来命名,如
<code>Reader</code>、<code>Writer</code>、
<code>Formatter</code>、<code>CloseNotifier</code> 等。
</p>
<div class="english">
<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>
</div>
<p>
诸如此类的命名有很多,遵循它们及其代表的函数名会让事情变得简单。
<code>Read</code>、<code>Write</code>、<code>Close</code>、<code>Flush</code>、
<code>String</code> 等都具有典型的签名和意义。为避免冲突,请不要用这些名称为你的方法命名,
除非你明确知道它们的签名和意义相同。反之,若你的类型实现了的方法,
与一个众所周知的类型的方法拥有相同的含义,那就使用相同的命名。
请将字符串转换方法命名为 <code>String</code> 而非 <code>ToString</code>。
</p>
<div class="english">
<h3 id="mixed-caps">MixedCaps</h3>
</div>
<h3 id="驼峰记法">驼峰记法</h3>
<div class="english">
<p>
Finally, the convention in Go is to use <code>MixedCaps</code>
or <code>mixedCaps</code> rather than underscores to write
multiword names.
</p>
</div>
<p>
最后,Go中约定使用驼峰记法 <code>MixedCaps</code> 或 <code>mixedCaps</code>。
</p>
<div class="english">
<h2 id="semicolons">Semicolons</h2>
</div>
<h2 id="分号">分号</h2>
<div class="english">
<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>
</div>
<p>
和C一样,Go的正式语法使用分号来结束语句;和C不同的是,这些分号并不在源码中出现。
取而代之,词法分析器会使用一条简单的规则来自动插入分号,因此因此源码中基本就不用分号了。
</p>
<div class="english">
<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>
</div>
<p>
规则是这样的:若在新行前的最后一个标记为标识符(包括 <code>int</code> 和
<code>float64</code> 这类的单词)、数值或字符串常量之类的基本字面或以下标记之一
</p>
<pre>
break continue fallthrough return ++ -- ) }
</pre>
<div class="english">
<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>
</div>
<p>
则词法分析将始终在该标记后面插入分号。这点可以概括为:
“如果新行前的标记为语句的末尾,则插入分号”。
</p>
<div class="english">
<p>
A semicolon can also be omitted immediately before a closing brace,
so a statement such as
</p>
</div>
<p>
分号也可在闭括号之前直接省略,因此像
</p>
<pre>
go func() { for { dst <- <-src } }()
</pre>
<div class="english">
<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>
</div>
<p>
这样的语句无需分号。通常Go程序只在诸如 <code>for</code> 循环子句这样的地方使用分号,
以此来将初始化器、条件及增量元素分开。如果你在一行中写多个语句,也需要用分号隔开。
</p>
<div class="english">
<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>
</div>
<p>
警告:无论如何,你都不应将一个控制结构(<code>if</code>、<code>for</code>、<code>switch</code>
或 <code>select</code>)的左大括号放在下一行。如果这样做,就会在大括号前面插入一个分号,这可能引起不需要的效果。
你应该这样写
</p>
<div class="english">
<pre>
if i < f() {
g()
}
</pre>
<p>
not like this
</p>
<pre>
if i < f() // wrong!
{ // wrong!
g()
}
</pre>
</div>
<pre>
if i < f() {
g()
}
</pre>
<p>
而不是这样
</p>
<pre>
if i < f() // 错!
{ // 错!
g()
}
</pre>
<div class="english">
<h2 id="control-structures">Control structures</h2>
</div>
<h2 id="控制结构">控制结构</h2>
<div class="english">
<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>
</div>
<p>
Go中的结构控制与C有许多相似之处,但其不同之处才是独到之处。
Go不再使用 <code>do</code> 或 <code>while</code> 循环,只有一个更通用的
<code>for</code>;<code>switch</code> 要更灵活一点;<code>if</code> 和
<code>switch</code> 像 <code>for</code>一样可接受可选的初始化语句;
此外,还有一个包含类型选择和多路通信复用器的新控制结构:<code>select</code>。
其语法也有些许不同:没有圆括号,而其主体必须始终使用大括号括住。
</p>
<h3 id="if">If</h3>