This repository has been archived by the owner on May 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
/
go_faq.html
1552 lines (1325 loc) · 55.6 KB
/
go_faq.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": "FAQ"
}-->
<h2 id="Origins">Origins</h2>
<h3 id="What_is_the_purpose_of_the_project">
What is the purpose of the project?</h3>
<p>
No major systems language has emerged in over a decade, but over that time
the computing landscape has changed tremendously. There are several trends:
</p>
<ul>
<li>
Computers are enormously quicker but software development is not faster.
<li>
Dependency management is a big part of software development today but the
“header files” of languages in the C tradition are antithetical to clean
dependency analysis—and fast compilation.
<li>
There is a growing rebellion against cumbersome type systems like those of
Java and C++, pushing people towards dynamically typed languages such as
Python and JavaScript.
<li>
Some fundamental concepts such as garbage collection and parallel computation
are not well supported by popular systems languages.
<li>
The emergence of multicore computers has generated worry and confusion.
</ul>
<p>
We believe it's worth trying again with a new language, a concurrent,
garbage-collected language with fast compilation. Regarding the points above:
</p>
<ul>
<li>
It is possible to compile a large Go program in a few seconds on a single computer.
<li>
Go provides a model for software construction that makes dependency
analysis easy and avoids much of the overhead of C-style include files and
libraries.
<li>
Go's type system has no hierarchy, so no time is spent defining the
relationships between types. Also, although Go has static types the language
attempts to make types feel lighter weight than in typical OO languages.
<li>
Go is fully garbage-collected and provides fundamental support for
concurrent execution and communication.
<li>
By its design, Go proposes an approach for the construction of system
software on multicore machines.
</ul>
<h3 id="What_is_the_origin_of_the_name">
What is the origin of the name?</h3>
<p>
“Ogle” would be a good name for a Go debugger.
</p>
<h3 id="Whats_the_origin_of_the_mascot">
What's the origin of the mascot?</h3>
<p>
The mascot and logo were designed by
<a href="http://reneefrench.blogspot.com">Renée French</a>, who also designed
<a href="http://plan9.bell-labs.com/plan9/glenda.html">Glenda</a>,
the Plan 9 bunny.
The gopher is derived from one she used for an <a href="http://wfmu.org/">WFMU</a>
T-shirt design some years ago.
The logo and mascot are covered by the
<a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0</a>
license.
</p>
<h3 id="What_kind_of_a_name_is_6g">
What kind of a name is 6g?</h3>
<p>
The <code>6g</code> (and <code>8g</code> and <code>5g</code>) compiler is named in the
tradition of the Plan 9 C compilers, described in
<a href="http://plan9.bell-labs.com/sys/doc/compiler.html">
http://plan9.bell-labs.com/sys/doc/compiler.html</a>
(see the table in section 2).
<code>6</code> is the architecture letter for amd64 (or x86-64, if you prefer), while
<code>g</code> stands for Go.
</p>
<h3 id="history">
What is the history of the project?</h3>
<p>
Robert Griesemer, Rob Pike and Ken Thompson started sketching the
goals for a new language on the white board on September 21, 2007.
Within a few days the goals had settled into a plan to do something
and a fair idea of what it would be. Design continued part-time in
parallel with unrelated work. By January 2008, Ken had started work
on a compiler with which to explore ideas; it generated C code as its
output. By mid-year the language had become a full-time project and
had settled enough to attempt a production compiler. In May 2008,
Ian Taylor independently started on a GCC front end for Go using the
draft specification. Russ Cox joined in late 2008 and helped move the language
and libraries from prototype to reality.
</p>
<p>
Go became a public open source project on November 10, 2009.
Many people from the community have contributed ideas, discussions, and code.
</p>
<h3 id="creating_a_new_language">
Why are you creating a new language?</h3>
<p>
Go was born out of frustration with existing languages and
environments for systems programming. Programming had become too
difficult and the choice of languages was partly to blame. One had to
choose either efficient compilation, efficient execution, or ease of
programming; all three were not available in the same mainstream
language. Programmers who could were choosing ease over
safety and efficiency by moving to dynamically typed languages such as
Python and JavaScript rather than C++ or, to a lesser extent, Java.
</p>
<p>
Go is an attempt to combine the ease of programming of an interpreted,
dynamically typed
language with the efficiency and safety of a statically typed, compiled language.
It also aims to be modern, with support for networked and multicore
computing. Finally, it is intended to be <i>fast</i>: it should take
at most a few seconds to build a large executable on a single computer.
To meet these goals required addressing a number of
linguistic issues: an expressive but lightweight type system;
concurrency and garbage collection; rigid dependency specification;
and so on. These cannot be addressed well by libraries or tools; a new
language was called for.
</p>
<h3 id="ancestors">
What are Go's ancestors?</h3>
<p>
Go is mostly in the C family (basic syntax),
with significant input from the Pascal/Modula/Oberon
family (declarations, packages),
plus some ideas from languages
inspired by Tony Hoare's CSP,
such as Newsqueak and Limbo (concurrency).
However, it is a new language across the board.
In every respect the language was designed by thinking
about what programmers do and how to make programming, at least the
kind of programming we do, more effective, which means more fun.
</p>
<h3 id="principles">
What are the guiding principles in the design?</h3>
<p>
Programming today involves too much bookkeeping, repetition, and
clerical work. As Dick Gabriel says, “Old programs read
like quiet conversations between a well-spoken research worker and a
well-studied mechanical colleague, not as a debate with a compiler.
Who'd have guessed sophistication bought such noise?”
The sophistication is worthwhile—no one wants to go back to
the old languages—but can it be more quietly achieved?
</p>
<p>
Go attempts to reduce the amount of typing in both senses of the word.
Throughout its design, we have tried to reduce clutter and
complexity. There are no forward declarations and no header files;
everything is declared exactly once. Initialization is expressive,
automatic, and easy to use. Syntax is clean and light on keywords.
Stuttering (<code>foo.Foo* myFoo = new(foo.Foo)</code>) is reduced by
simple type derivation using the <code>:=</code>
declare-and-initialize construct. And perhaps most radically, there
is no type hierarchy: types just <i>are</i>, they don't have to
announce their relationships. These simplifications allow Go to be
expressive yet comprehensible without sacrificing, well, sophistication.
</p>
<p>
Another important principle is to keep the concepts orthogonal.
Methods can be implemented for any type; structures represent data while
interfaces represent abstraction; and so on. Orthogonality makes it
easier to understand what happens when things combine.
</p>
<h2 id="Usage">Usage</h2>
<h3 id="Is_Google_using_go_internally"> Is Google using Go internally?</h3>
<p>
Yes. There are now several Go programs deployed in
production inside Google. A public example is the server behind
<a href="http://golang.org">http://golang.org</a>.
It's just the <a href="/cmd/godoc"><code>godoc</code></a>
document server running in a production configuration on
<a href="http://code.google.com/appengine/">Google App Engine</a>.
</p>
<h3 id="Do_Go_programs_link_with_Cpp_programs">
Do Go programs link with C/C++ programs?</h3>
<p>
There are two Go compiler implementations, <code>6g</code> and friends,
generically called <code>gc</code>, and <code>gccgo</code>.
<code>Gc</code> uses a different calling convention and linker and can
therefore only be linked with C programs using the same convention.
There is such a C compiler but no C++ compiler.
<code>Gccgo</code> is a GCC front-end that can, with care, be linked with
GCC-compiled C or C++ programs.
</p>
<p>
The <a href="/cmd/cgo/">cgo</a> program provides the mechanism for a
“foreign function interface” to allow safe calling of
C libraries from Go code. SWIG extends this capability to C++ libraries.
</p>
<h3 id="Does_Go_support_Google_protocol_buffers">
Does Go support Google's protocol buffers?</h3>
<p>
A separate open source project provides the necessary compiler plugin and library.
It is available at
<a href="http://code.google.com/p/goprotobuf/">http://code.google.com/p/goprotobuf/</a>
</p>
<h3 id="Can_I_translate_the_Go_home_page">
Can I translate the Go home page into another language?</h3>
<p>
Absolutely. We encourage developers to make Go Language sites in their own languages.
However, if you choose to add the Google logo or branding to your site
(it does not appear on <a href="http://golang.org/">golang.org</a>),
you will need to abide by the guidelines at
<a href="http://www.google.com/permissions/guidelines.html">http://www.google.com/permissions/guidelines.html</a>
</p>
<h2 id="Design">Design</h2>
<h3 id="unicode_identifiers">
What's up with Unicode identifiers?</h3>
<p>
It was important to us to extend the space of identifiers from the
confines of ASCII. Go's rule—identifier characters must be
letters or digits as defined by Unicode—is simple to understand
and to implement but has restrictions. Combining characters are
excluded by design, for instance.
Until there
is an agreed external definition of what an identifier might be,
plus a definition of canonicalization of identifiers that guarantees
no ambiguity, it seemed better to keep combining characters out of
the mix. Thus we have a simple rule that can be expanded later
without breaking programs, one that avoids bugs that would surely arise
from a rule that admits ambiguous identifiers.
</p>
<p>
On a related note, since an exported identifier must begin with an
upper-case letter, identifiers created from “letters”
in some languages can, by definition, not be exported. For now the
only solution is to use something like <code>X日本語</code>, which
is clearly unsatisfactory; we are considering other options. The
case-for-visibility rule is unlikely to change however; it's one
of our favorite features of Go.
</p>
<h3 id="Why_doesnt_Go_have_feature_X">Why does Go not have feature X?</h3>
<p>
Every language contains novel features and omits someone's favorite
feature. Go was designed with an eye on felicity of programming, speed of
compilation, orthogonality of concepts, and the need to support features
such as concurrency and garbage collection. Your favorite feature may be
missing because it doesn't fit, because it affects compilation speed or
clarity of design, or because it would make the fundamental system model
too difficult.
</p>
<p>
If it bothers you that Go is missing feature <var>X</var>,
please forgive us and investigate the features that Go does have. You might find that
they compensate in interesting ways for the lack of <var>X</var>.
</p>
<h3 id="generics">
Why does Go not have generic types?</h3>
<p>
Generics may well be added at some point. We don't feel an urgency for
them, although we understand some programmers do.
</p>
<p>
Generics are convenient but they come at a cost in
complexity in the type system and run-time. We haven't yet found a
design that gives value proportionate to the complexity, although we
continue to think about it. Meanwhile, Go's built-in maps and slices,
plus the ability to use the empty interface to construct containers
(with explicit unboxing) mean in many cases it is possible to write
code that does what generics would enable, if less smoothly.
</p>
<p>
This remains an open issue.
</p>
<h3 id="exceptions">
Why does Go not have exceptions?</h3>
<p>
We believe that coupling exceptions to a control
structure, as in the <code>try-catch-finally</code> idiom, results in
convoluted code. It also tends to encourage programmers to label
too many ordinary errors, such as failing to open a file, as
exceptional.
</p>
<p>
Go takes a different approach. For plain error handling, Go's multi-value
returns make it easy to report an error without overloading the return value.
<a href="http://blog.golang.org/2011/07/error-handling-and-go.html">A
canonical error type, coupled
with Go's other features</a>, makes error
handling pleasant but quite different from that in other languages.
</p>
<p>
Go also has a couple
of built-in functions to signal and recover from truly exceptional
conditions. The recovery mechanism is executed only as part of a
function's state being torn down after an error, which is sufficient
to handle catastrophe but requires no extra control structures and,
when used well, can result in clean error-handling code.
</p>
<p>
See the <a href="http://blog.golang.org/2010/08/defer-panic-and-recover.html">Defer, Panic, and Recover</a> article for details.
</p>
<h3 id="assertions">
Why does Go not have assertions?</h3>
<p>
Go doesn't provide assertions. They are undeniably convenient, but our
experience has been that programmers use them as a crutch to avoid thinking
about proper error handling and reporting. Proper error handling means that
servers continue operation after non-fatal errors instead of crashing.
Proper error reporting means that errors are direct and to the point,
saving the programmer from interpreting a large crash trace. Precise
errors are particularly important when the programmer seeing the errors is
not familiar with the code.
</p>
<p>
We understand that this is a point of contention. There are many things in
the Go language and libraries that differ from modern practices, simply
because we feel it's sometimes worth trying a different approach.
</p>
<h3 id="csp">
Why build concurrency on the ideas of CSP?</h3>
<p>
Concurrency and multi-threaded programming have a reputation
for difficulty. We believe this is due partly to complex
designs such as pthreads and partly to overemphasis on low-level details
such as mutexes, condition variables, and memory barriers.
Higher-level interfaces enable much simpler code, even if there are still
mutexes and such under the covers.
</p>
<p>
One of the most successful models for providing high-level linguistic support
for concurrency comes from Hoare's Communicating Sequential Processes, or CSP.
Occam and Erlang are two well known languages that stem from CSP.
Go's concurrency primitives derive from a different part of the family tree
whose main contribution is the powerful notion of channels as first class objects.
</p>
<h3 id="goroutines">
Why goroutines instead of threads?</h3>
<p>
Goroutines are part of making concurrency easy to use. The idea, which has
been around for a while, is to multiplex independently executing
functions—coroutines—onto a set of threads.
When a coroutine blocks, such as by calling a blocking system call,
the run-time automatically moves other coroutines on the same operating
system thread to a different, runnable thread so they won't be blocked.
The programmer sees none of this, which is the point.
The result, which we call goroutines, can be very cheap: unless they spend a lot of time
in long-running system calls, they cost little more than the memory
for the stack, which is just a few kilobytes.
</p>
<p>
To make the stacks small, Go's run-time uses segmented stacks. A newly
minted goroutine is given a few kilobytes, which is almost always enough.
When it isn't, the run-time allocates (and frees) extension segments automatically.
The overhead averages about three cheap instructions per function call.
It is practical to create hundreds of thousands of goroutines in the same
address space. If goroutines were just threads, system resources would
run out at a much smaller number.
</p>
<h3 id="atomic_maps">
Why are map operations not defined to be atomic?</h3>
<p>
After long discussion it was decided that the typical use of maps did not require
safe access from multiple threads, and in those cases where it did, the map was
probably part of some larger data structure or computation that was already
synchronized. Therefore requiring that all map operations grab a mutex would slow
down most programs and add safety to few. This was not an easy decision,
however, since it means uncontrolled map access can crash the program.
</p>
<p>
The language does not preclude atomic map updates. When required, such
as when hosting an untrusted program, the implementation could interlock
map access.
</p>
<h2 id="types">Types</h2>
<h3 id="Is_Go_an_object-oriented_language">
Is Go an object-oriented language?</h3>
<p>
Yes and no. Although Go has types and methods and allows an
object-oriented style of programming, there is no type hierarchy.
The concept of “interface” in Go provides a different approach that
we believe is easy to use and in some ways more general. There are
also ways to embed types in other types to provide something
analogous—but not identical—to subclassing.
Moreover, methods in Go are more general than in C++ or Java:
they can be defined for any sort of data, even built-in types such
as plain, “unboxed” integers.
They are not restricted to structs (classes).
</p>
<p>
Also, the lack of type hierarchy makes “objects” in Go feel much more
lightweight than in languages such as C++ or Java.
</p>
<h3 id="How_do_I_get_dynamic_dispatch_of_methods">
How do I get dynamic dispatch of methods?</h3>
<p>
The only way to have dynamically dispatched methods is through an
interface. Methods on a struct or any other concrete type are always resolved statically.
</p>
<h3 id="inheritance">
Why is there no type inheritance?</h3>
<p>
Object-oriented programming, at least in the best-known languages,
involves too much discussion of the relationships between types,
relationships that often could be derived automatically. Go takes a
different approach.
</p>
<p>
Rather than requiring the programmer to declare ahead of time that two
types are related, in Go a type automatically satisfies any interface
that specifies a subset of its methods. Besides reducing the
bookkeeping, this approach has real advantages. Types can satisfy
many interfaces at once, without the complexities of traditional
multiple inheritance.
Interfaces can be very lightweight—an interface with
one or even zero methods can express a useful concept.
Interfaces can be added after the fact if a new idea comes along
or for testing—without annotating the original types.
Because there are no explicit relationships between types
and interfaces, there is no type hierarchy to manage or discuss.
</p>
<p>
It's possible to use these ideas to construct something analogous to
type-safe Unix pipes. For instance, see how <code>fmt.Fprintf</code>
enables formatted printing to any output, not just a file, or how the
<code>bufio</code> package can be completely separate from file I/O,
or how the <code>image</code> packages generate compressed
image files. All these ideas stem from a single interface
(<code>io.Writer</code>) representing a single method
(<code>Write</code>). And that's only scratching the surface.
</p>
<p>
It takes some getting used to but this implicit style of type
dependency is one of the most productive things about Go.
</p>
<h3 id="methods_on_basics">
Why is <code>len</code> a function and not a method?</h3>
<p>
We debated this issue but decided
implementing <code>len</code> and friends as functions was fine in practice and
didn't complicate questions about the interface (in the Go type sense)
of basic types.
</p>
<h3 id="overloading">
Why does Go not support overloading of methods and operators?</h3>
<p>
Method dispatch is simplified if it doesn't need to do type matching as well.
Experience with other languages told us that having a variety of
methods with the same name but different signatures was occasionally useful
but that it could also be confusing and fragile in practice. Matching only by name
and requiring consistency in the types was a major simplifying decision
in Go's type system.
</p>
<p>
Regarding operator overloading, it seems more a convenience than an absolute
requirement. Again, things are simpler without it.
</p>
<h3 id="implements_interface">
Why doesn't Go have "implements" declarations?</h3>
<p>
A Go type satisfies an interface by implementing the methods of that interface,
nothing more. This property allows interfaces to be defined and used without
having to modify existing code. It enables a kind of "duck typing" that
promotes separation of concerns and improves code re-use, and makes it easier
to build on patterns that emerge as the code develops.
The semantics of interfaces is one of the main reasons for Go's nimble,
lightweight feel.
</p>
<p>
See the <a href="#inheritance">question on type inheritance</a> for more detail.
</p>
<h3 id="guarantee_satisfies_interface">
How can I guarantee my type satisfies an interface?</h3>
<p>
You can ask the compiler to check that the type <code>T</code> implements the
interface <code>I</code> by attempting an assignment:
</p>
<pre>
type T struct{}
var _ I = T{} // Verify that T implements I.
</pre>
<p>
If <code>T</code> doesn't implement <code>I</code>, the mistake will be caught
at compile time.
</p>
<p>
If you wish the users of an interface to explicitly declare that they implement
it, you can add a method with a descriptive name to the interface's method set.
For example:
</p>
<pre>
type Fooer interface {
Foo()
ImplementsFooer()
}
</pre>
<p>
A type must then implement the <code>ImplementsFooer</code> method to be a
<code>Fooer</code>, clearly documenting the fact and announcing it in
<a href="/cmd/godoc/">godoc</a>'s output.
</p>
<pre>
type Bar struct{}
func (b Bar) ImplementsFooer() {}
func (b Bar) Foo() {}
</pre>
<p>
Most code doesn't make use of such constraints, since they limit the utility of
the interface idea. Sometimes, though, they're necessary to resolve ambiguities
among similar interfaces.
</p>
<h3 id="t_and_equal_interface">
Why doesn't type T satisfy the Equal interface?</h3>
<p>
Consider this simple interface to represent an object that can compare
itself with another value:
</p>
<pre>
type Equaler interface {
Equal(Equaler) bool
}
</pre>
<p>
and this type, <code>T</code>:
</p>
<pre>
type T int
func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
</pre>
<p>
Unlike the analogous situation in some polymorphic type systems,
<code>T</code> does not implement <code>Equaler</code>.
The argument type of <code>T.Equal</code> is <code>T</code>,
not literally the required type <code>Equaler</code>.
</p>
<p>
In Go, the type system does not promote the argument of
<code>Equal</code>; that is the programmer's responsibility, as
illustrated by the type <code>T2</code>, which does implement
<code>Equaler</code>:
</p>
<pre>
type T2 int
func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler
</pre>
<p>
Even this isn't like other type systems, though, because in Go <em>any</em>
type that satisfies <code>Equaler</code> could be passed as the
argument to <code>T2.Equal</code>, and at run time we must
check that the argument is of type <code>T2</code>.
Some languages arrange to make that guarantee at compile time.
</p>
<p>
A related example goes the other way:
</p>
<pre>
type Opener interface {
Open(name) Reader
}
func (t T3) Open() *os.File
</pre>
<p>
In Go, <code>T3</code> does not satisfy <code>Opener</code>,
although it might in another language.
</p>
<p>
While it is true that Go's type system does less for the programmer
in such cases, the lack of subtyping makes the rules about
interface satisfaction very easy to state: are the function's names
and signatures exactly those of the interface?
Go's rule is also easy to implement efficiently.
We feel these benefits offset the lack of
automatic type promotion. Should Go one day adopt some form of generic
typing, we expect there would be a way to express the idea of these
examples and also have them be statically checked.
</p>
<h3 id="convert_slice_of_interface">
Can I convert a []T to an []interface{}?</h3>
<p>
Not directly, because they do not have the same representation in memory.
It is necessary to copy the elements individually to the destination
slice. This example converts a slice of <code>int</code> to a slice of
<code>interface{}</code>:
</p>
<pre>
t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
s[i] = v
}
</pre>
<h3 id="unions">
Why are there no untagged unions, as in C?</h3>
<p>
Untagged unions would violate Go's memory safety
guarantees.
</p>
<h3 id="variant_types">
Why does Go not have variant types?</h3>
<p>
Variant types, also known as algebraic types, provide a way to specify
that a value might take one of a set of other types, but only those
types. A common example in systems programming would specify that an
error is, say, a network error, a security error or an application
error and allow the caller to discriminate the source of the problem
by examining the type of the error. Another example is a syntax tree
in which each node can be a different type: declaration, statement,
assignment and so on.
</p>
<p>
We considered adding variant types to Go, but after discussion
decided to leave them out because they overlap in confusing ways
with interfaces. What would happen if the elements of a variant type
were themselves interfaces?
</p>
<p>
Also, some of what variant types address is already covered by the
language. The error example is easy to express using an interface
value to hold the error and a type switch to discriminate cases. The
syntax tree example is also doable, although not as elegantly.
</p>
<h2 id="values">Values</h2>
<h3 id="conversions">
Why does Go not provide implicit numeric conversions?</h3>
<p>
The convenience of automatic conversion between numeric types in C is
outweighed by the confusion it causes. When is an expression unsigned?
How big is the value? Does it overflow? Is the result portable, independent
of the machine on which it executes?
It also complicates the compiler; “the usual arithmetic conversions”
are not easy to implement and inconsistent across architectures.
For reasons of portability, we decided to make things clear and straightforward
at the cost of some explicit conversions in the code.
The definition of constants in Go—arbitrary precision values free
of signedness and size annotations—ameliorates matters considerably,
though.
</p>
<p>
A related detail is that, unlike in C, <code>int</code> and <code>int64</code>
are distinct types even if <code>int</code> is a 64-bit type. The <code>int</code>
type is generic; if you care about how many bits an integer holds, Go
encourages you to be explicit.
</p>
<h3 id="builtin_maps">
Why are maps built in?</h3>
<p>
The same reason strings are: they are such a powerful and important data
structure that providing one excellent implementation with syntactic support
makes programming more pleasant. We believe that Go's implementation of maps
is strong enough that it will serve for the vast majority of uses.
If a specific application can benefit from a custom implementation, it's possible
to write one but it will not be as convenient syntactically; this seems a reasonable tradeoff.
</p>
<h3 id="map_keys">
Why don't maps allow slices as keys?</h3>
<p>
Map lookup requires an equality operator, which slices do not implement.
They don't implement equality because equality is not well defined on such types;
there are multiple considerations involving shallow vs. deep comparison, pointer vs.
value comparison, how to deal with recursive types, and so on.
We may revisit this issue—and implementing equality for slices
will not invalidate any existing programs—but without a clear idea of what
equality of structs and arrays should mean, it was simpler to leave it out for now.
</p>
<p>
In Go 1, equality is defined for structs and arrays, so such
types can be used as map keys, but slices still do not have a definition of equality.
</p>
<h3 id="references">
Why are maps, slices, and channels references while arrays are values?</h3>
<p>
There's a lot of history on that topic. Early on, maps and channels
were syntactically pointers and it was impossible to declare or use a
non-pointer instance. Also, we struggled with how arrays should work.
Eventually we decided that the strict separation of pointers and
values made the language harder to use. Introducing reference types,
including slices to handle the reference form of arrays, resolved
these issues. Reference types add some regrettable complexity to the
language but they have a large effect on usability: Go became a more
productive, comfortable language when they were introduced.
</p>
<h2 id="Writing_Code">Writing Code</h2>
<h3 id="How_are_libraries_documented">
How are libraries documented?</h3>
<p>
There is a program, <code>godoc</code>, written in Go, that extracts
package documentation from the source code. It can be used on the
command line or on the web. An instance is running at
<a href="http://golang.org/pkg/">http://golang.org/pkg/</a>.
In fact, <code>godoc</code> implements the full site at
<a href="http://golang.org/">http://golang.org/</a>.
</p>
<h3 id="Is_there_a_Go_programming_style_guide">
Is there a Go programming style guide?</h3>
<p>
Eventually, there may be a small number of rules to guide things
like naming, layout, and file organization.
The document <a href="effective_go.html">Effective Go</a>
contains some style advice.
More directly, the program <code>gofmt</code> is a pretty-printer
whose purpose is to enforce layout rules; it replaces the usual
compendium of do's and don'ts that allows interpretation.
All the Go code in the repository has been run through <code>gofmt</code>.
</p>
<h3 id="How_do_I_submit_patches_to_the_Go_libraries">
How do I submit patches to the Go libraries?</h3>
<p>
The library sources are in <code>go/src/pkg</code>.
If you want to make a significant change, please discuss on the mailing list before embarking.
</p>
<p>
See the document
<a href="contribute.html">Contributing to the Go project</a>
for more information about how to proceed.
</p>
<h2 id="Pointers">Pointers and Allocation</h2>
<h3 id="pass_by_value">
When are function parameters passed by value?</h3>
<p>
As in all languages in the C family, everything in Go is passed by value.
That is, a function always gets a copy of the
thing being passed, as if there were an assignment statement assigning the
value to the parameter. For instance, passing an <code>int</code> value
to a function makes a copy of the <code>int</code>, and passing a pointer
value makes a copy of the pointer, but not the data it points to.
(See the next section for a discussion of how this affects method receivers.)
</p>
<p>
Map and slice values behave like pointers: they are descriptors that
contain pointers to the underlying map or slice data. Copying a map or
slice value doesn't copy the data it points to. Copying an interface value
makes a copy of the thing stored in the interface value. If the interface
value holds a struct, copying the interface value makes a copy of the
struct. If the interface value holds a pointer, copying the interface value
makes a copy of the pointer, but again not the data it points to.
</p>
<h3 id="methods_on_values_or_pointers">
Should I define methods on values or pointers?</h3>
<pre>
func (s *MyStruct) pointerMethod() { } // method on pointer
func (s MyStruct) valueMethod() { } // method on value
</pre>
<p>
For programmers unaccustomed to pointers, the distinction between these
two examples can be confusing, but the situation is actually very simple.
When defining a method on a type, the receiver (<code>s</code> in the above
example) behaves exactly as if it were an argument to the method.
Whether to define the receiver as a value or as a pointer is the same
question, then, as whether a function argument should be a value or
a pointer.
There are several considerations.
</p>
<p>
First, and most important, does the method need to modify the
receiver?
If it does, the receiver <em>must</em> be a pointer.
(Slices and maps are reference types, so their story is a little
more subtle, but for instance to change the length of a slice
in a method the receiver must still be a pointer.)
In the examples above, if <code>pointerMethod</code> modifies
the fields of <code>s</code>,
the caller will see those changes, but <code>valueMethod</code>
is called with a copy of the caller's argument (that's the definition
of passing a value), so changes it makes will be invisible to the caller.
</p>
<p>
By the way, pointer receivers are identical to the situation in Java,
although in Java the pointers are hidden under the covers; it's Go's
value receivers that are unusual.
</p>
<p>
Second is the consideration of efficiency. If the receiver is large,
a big <code>struct</code> for instance, it will be much cheaper to
use a pointer receiver.
</p>
<p>
Next is consistency. If some of the methods of the type must have
pointer receivers, the rest should too, so the method set is
consistent regardless of how the type is used.
See the section on <a href="#different_method_sets">method sets</a>
for details.
</p>
<p>
For types such as basic types, slices, and small <code>structs</code>,
a value receiver is very cheap so unless the semantics of the method
requires a pointer, a value receiver is efficient and clear.
</p>
<h3 id="new_and_make">
What's the difference between new and make?</h3>
<p>
In short: <code>new</code> allocates memory, <code>make</code> initializes
the slice, map, and channel types.
</p>
<p>
See the <a href="/doc/effective_go.html#allocation_new">relevant section
of Effective Go</a> for more details.
</p>
<h3 id="q_int_sizes">
Why is <code>int</code> 32 bits on 64 bit machines?</h3>
<p>
The sizes of <code>int</code> and <code>uint</code> are implementation-specific
but the same as each other on a given platform.
The 64 bit Go compilers (both 6g and gccgo) use a 32 bit representation for
<code>int</code>. Code that relies on a particular
size of value should use an explicitly sized type, like <code>int64</code>.
On the other hand, floating-point scalars and complex
numbers are always sized: <code>float32</code>, <code>complex64</code>,
etc., because programmers should be aware of precision when using
floating-point numbers.
The default size of a floating-point constant is <code>float64</code>.
</p>
<p>
At the moment, all implementations use 32-bit ints, an essentially arbitrary decision.
However, we expect that <code>int</code> will be increased to 64 bits on 64-bit
architectures in a future release of Go.
</p>
<h3 id="stack_or_heap">
How do I know whether a variable is allocated on the heap or the stack?</h3>
<p>
From a correctness standpoint, you don't need to know.
Each variable in Go exists as long as there are references to it.
The storage location chosen by the implementation is irrelevant to the
semantics of the language.
</p>
<p>
The storage location does have an effect on writing efficient programs.
When possible, the Go compilers will allocate variables that are
local to a function in that function's stack frame. However, if the
compiler cannot prove that the variable is not referenced after the
function returns, then the compiler must allocate the variable on the
garbage-collected heap to avoid dangling pointer errors.
Also, if a local variable is very large, it might make more sense
to store it on the heap rather than the stack.
</p>
<p>
In the current compilers, if a variable has its address taken, that variable
is a candidate for allocation on the heap. However, a basic <em>escape
analysis</em> recognizes some cases when such variables will not
live past the return from the function and can reside on the stack.
</p>
<h2 id="Concurrency">Concurrency</h2>
<h3 id="What_operations_are_atomic_What_about_mutexes">
What operations are atomic? What about mutexes?</h3>
<p>
We haven't fully defined it all yet, but some details about atomicity are
available in the <a href="go_mem.html">Go Memory Model specification</a>.
</p>
<p>
Regarding mutexes, the <a href="/pkg/sync">sync</a>
package implements them, but we hope Go programming style will
encourage people to try higher-level techniques. In particular, consider
structuring your program so that only one goroutine at a time is ever
responsible for a particular piece of data.
</p>
<p>
Do not communicate by sharing memory. Instead, share memory by communicating.
</p>
<p>
See the <a href="/doc/codewalk/sharemem/">Share Memory By Communicating</a> code walk and its <a href="http://blog.golang.org/2010/07/share-memory-by-communicating.html">associated article</a> for a detailed discussion of this concept.
</p>