-
Notifications
You must be signed in to change notification settings - Fork 1
/
go_spec.html
4633 lines (3870 loc) · 135 KB
/
go_spec.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
<!-- The Go Programming Language Specification -->
<!--
Todo
[ ] clarify: two equal lowercase identifiers from different packages denote different objects
[ ] need language about function/method calls and parameter passing rules
[ ] need to say something about "scope" of selectors?
[ ] clarify what a field name is in struct declarations
(struct{T} vs struct {T T} vs struct {t T})
[ ] need explicit language about the result type of operations
[ ] may want to have some examples for the types of shift operations
[ ] should string(1<<s) and float(1<<s) be valid?
[ ] should probably write something about evaluation order of statements even
though obvious
[ ] specify iteration direction for range clause
[ ] review language on implicit dereferencing
-->
<h2 id="Introduction">Introduction</h2>
<p>
This is a reference manual for the Go programming language. For
more information and other documents, see <a href="http://golang.org/">http://golang.org</a>.
</p>
<p>
Go is a general-purpose language designed with systems programming
in mind. It is strongly typed and garbage-collected and has explicit
support for concurrent programming. Programs are constructed from
<i>packages</i>, whose properties allow efficient management of
dependencies. The existing implementations use a traditional
compile/link model to generate executable binaries.
</p>
<p>
The grammar is compact and regular, allowing for easy analysis by
automatic tools such as integrated development environments.
</p>
<h2 id="Notation">Notation</h2>
<p>
The syntax is specified using Extended Backus-Naur Form (EBNF):
</p>
<pre class="grammar">
Production = production_name "=" Expression "." .
Expression = Alternative { "|" Alternative } .
Alternative = Term { Term } .
Term = production_name | token [ "..." token ] | Group | Option | Repetition .
Group = "(" Expression ")" .
Option = "[" Expression "]" .
Repetition = "{" Expression "}" .
</pre>
<p>
Productions are expressions constructed from terms and the following
operators, in increasing precedence:
</p>
<pre class="grammar">
| alternation
() grouping
[] option (0 or 1 times)
{} repetition (0 to n times)
</pre>
<p>
Lower-case production names are used to identify lexical tokens.
Non-terminals are in CamelCase. Lexical symbols are enclosed in
double quotes <code>""</code> or back quotes <code>``</code>.
</p>
<p>
The form <code>a ... b</code> represents the set of characters from
<code>a</code> through <code>b</code> as alternatives.
</p>
<h2 id="Source_code_representation">Source code representation</h2>
<p>
Source code is Unicode text encoded in UTF-8. The text is not
canonicalized, so a single accented code point is distinct from the
same character constructed from combining an accent and a letter;
those are treated as two code points. For simplicity, this document
will use the term <i>character</i> to refer to a Unicode code point.
</p>
<p>
Each code point is distinct; for instance, upper and lower case letters
are different characters.
</p>
<h3 id="Characters">Characters</h3>
<p>
The following terms are used to denote specific Unicode character classes:
</p>
<pre class="ebnf">
unicode_char = /* an arbitrary Unicode code point */ .
unicode_letter = /* a Unicode code point classified as "Letter" */ .
unicode_digit = /* a Unicode code point classified as "Digit" */ .
</pre>
<p>
In <a href="http://www.unicode.org/versions/Unicode5.1.0/">The Unicode Standard 5.1</a>,
Section 4.5 General Category-Normative
defines a set of character categories. Go treats
those characters in category Lu, Ll, Lt, Lm, or Lo as Unicode letters,
and those in category Nd as Unicode digits.
</p>
<h3 id="Letters_and_digits">Letters and digits</h3>
<p>
The underscore character <code>_</code> (U+005F) is considered a letter.
</p>
<pre class="ebnf">
letter = unicode_letter | "_" .
decimal_digit = "0" ... "9" .
octal_digit = "0" ... "7" .
hex_digit = "0" ... "9" | "A" ... "F" | "a" ... "f" .
</pre>
<h2 id="Lexical_elements">Lexical elements</h2>
<h3 id="Comments">Comments</h3>
<p>
There are two forms of comments. The first starts at the character
sequence <code>//</code> and continues through the next newline. The
second starts at the character sequence <code>/*</code> and continues
through the character sequence <code>*/</code>. Comments do not nest.
</p>
<h3 id="Tokens">Tokens</h3>
<p>
Tokens form the vocabulary of the Go language.
There are four classes: identifiers, keywords, operators
and delimiters, and literals. <i>White space</i>, formed from
spaces (U+0020), horizontal tabs (U+0009),
carriage returns (U+000D), and newlines (U+000A),
is ignored except as it separates tokens
that would otherwise combine into a single token. Comments
behave as white space. While breaking the input into tokens,
the next token is the longest sequence of characters that form a
valid token.
</p>
<h3 id="Identifiers">Identifiers</h3>
<p>
Identifiers name program entities such as variables and types.
An identifier is a sequence of one or more letters and digits.
The first character in an identifier must be a letter.
</p>
<pre class="ebnf">
identifier = letter { letter | unicode_digit } .
</pre>
<pre>
a
_x9
ThisVariableIsExported
αβ
</pre>
Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>.
<h3 id="Keywords">Keywords</h3>
<p>
The following keywords are reserved and may not be used as identifiers.
</p>
<pre class="grammar">
break default func interface select
case defer go map struct
chan else goto package switch
const fallthrough if range type
continue for import return var
</pre>
<h3 id="Operators_and_Delimiters">Operators and Delimiters</h3>
<p>
The following character sequences represent <a href="#Operators">operators</a>, delimiters, and other special tokens:
</p>
<pre class="grammar">
+ & += &= && == != ( )
- | -= |= || < <= [ ]
* ^ *= ^= <- > >= { }
/ << /= <<= ++ = := , ;
% >> %= >>= -- ! ... . :
&^ &^=
</pre>
<h3 id="Integer_literals">Integer literals</h3>
<p>
An integer literal is a sequence of digits representing an
<a href="#Constants">integer constant</a>.
An optional prefix sets a non-decimal base: <code>0</code> for octal, <code>0x</code> or
<code>0X</code> for hexadecimal. In hexadecimal literals, letters
<code>a-f</code> and <code>A-F</code> represent values 10 through 15.
</p>
<pre class="ebnf">
int_lit = decimal_lit | octal_lit | hex_lit .
decimal_lit = ( "1" ... "9" ) { decimal_digit } .
octal_lit = "0" { octal_digit } .
hex_lit = "0" ( "x" | "X" ) hex_digit { hex_digit } .
</pre>
<pre>
42
0600
0xBadFace
170141183460469231731687303715884105727
</pre>
<h3 id="Floating-point_literals">Floating-point literals</h3>
<p>
A floating-point literal is a decimal representation of a
<a href="#Constants">floating-point constant</a>.
It has an integer part, a decimal point, a fractional part,
and an exponent part. The integer and fractional part comprise
decimal digits; the exponent part is an <code>e</code> or <code>E</code>
followed by an optionally signed decimal exponent. One of the
integer part or the fractional part may be elided; one of the decimal
point or the exponent may be elided.
</p>
<pre class="ebnf">
float_lit = decimals "." [ decimals ] [ exponent ] |
decimals exponent |
"." decimals [ exponent ] .
decimals = decimal_digit { decimal_digit } .
exponent = ( "e" | "E" ) [ "+" | "-" ] decimals .
</pre>
<pre>
0.
2.71828
1.e+0
6.67428e-11
1E6
.25
.12345E+5
</pre>
<h3 id="Character_literals">Character literals</h3>
<p>
A character literal represents an <a href="#Constants">integer constant</a>,
typically a Unicode code point, as one or more characters enclosed in single
quotes. Within the quotes, any character may appear except single
quote and newline. A single quoted character represents itself,
while multi-character sequences beginning with a backslash encode
values in various formats.
</p>
<p>
The simplest form represents the single character within the quotes;
since Go source text is Unicode characters encoded in UTF-8, multiple
UTF-8-encoded bytes may represent a single integer value. For
instance, the literal <code>'a'</code> holds a single byte representing
a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while
<code>'ä'</code> holds two bytes (<code>0xc3</code> <code>0xa4</code>) representing
a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>.
</p>
<p>
Several backslash escapes allow arbitrary values to be represented
as ASCII text. There are four ways to represent the integer value
as a numeric constant: <code>\x</code> followed by exactly two hexadecimal
digits; <code>\u</code> followed by exactly four hexadecimal digits;
<code>\U</code> followed by exactly eight hexadecimal digits, and a
plain backslash <code>\</code> followed by exactly three octal digits.
In each case the value of the literal is the value represented by
the digits in the corresponding base.
</p>
<p>
Although these representations all result in an integer, they have
different valid ranges. Octal escapes must represent a value between
0 and 255 inclusive. Hexadecimal escapes satisfy this condition
by construction. The escapes <code>\u</code> and <code>\U</code>
represent Unicode code points so within them some values are illegal,
in particular those above <code>0x10FFFF</code> and surrogate halves.
</p>
<p>
After a backslash, certain single-character escapes represent special values:
</p>
<pre class="grammar">
\a U+0007 alert or bell
\b U+0008 backspace
\f U+000C form feed
\n U+000A line feed or newline
\r U+000D carriage return
\t U+0009 horizontal tab
\v U+000b vertical tab
\\ U+005c backslash
\' U+0027 single quote (valid escape only within character literals)
\" U+0022 double quote (valid escape only within string literals)
</pre>
<p>
All other sequences starting with a backslash are illegal inside character literals.
</p>
<pre class="ebnf">
char_lit = "'" ( unicode_value | byte_value ) "'" .
unicode_value = unicode_char | little_u_value | big_u_value | escaped_char .
byte_value = octal_byte_value | hex_byte_value .
octal_byte_value = `\` octal_digit octal_digit octal_digit .
hex_byte_value = `\` "x" hex_digit hex_digit .
little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit .
big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit
hex_digit hex_digit hex_digit hex_digit .
escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
</pre>
<pre>
'a'
'ä'
'本'
'\t'
'\000'
'\007'
'\377'
'\x07'
'\xff'
'\u12e4'
'\U00101234'
</pre>
<h3 id="String_literals">String literals</h3>
<p>
A string literal represents a <a href="#Constants">string constant</a>
obtained from concatenating a sequence of characters. There are two forms:
raw string literals and interpreted string literals.
</p>
<p>
Raw string literals are character sequences between back quotes
<code>``</code>. Within the quotes, any character is legal except
back quote. The value of a raw string literal is the
string composed of the uninterpreted characters between the quotes;
in particular, backslashes have no special meaning and the string may
span multiple lines.
</p>
<p>
Interpreted string literals are character sequences between double
quotes <code>""</code>. The text between the quotes,
which may not span multiple lines, forms the
value of the literal, with backslash escapes interpreted as they
are in character literals (except that <code>\'</code> is illegal and
<code>\"</code> is legal). The three-digit octal (<code>\000</code>)
and two-digit hexadecimal (<code>\x00</code>) escapes represent individual
<i>bytes</i> of the resulting string; all other escapes represent
the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
Thus inside a string literal <code>\377</code> and <code>\xFF</code> represent
a single byte of value <code>0xFF</code>=255, while <code>ÿ</code>,
<code>\u00FF</code>, <code>\U000000FF</code> and <code>\xc3\xbf</code> represent
the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character
U+00FF.
</p>
<p>
A sequence of string literals is concatenated to form a single string.
</p>
<pre class="ebnf">
StringLit = string_lit { string_lit } .
string_lit = raw_string_lit | interpreted_string_lit .
raw_string_lit = "`" { unicode_char } "`" .
interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
</pre>
<pre>
`abc` // same as "abc"
`\n
\n` // same as "\\n\n\\n"
"\n"
""
"Hello, world!\n"
"日本語"
"\u65e5本\U00008a9e"
"\xff\u00FF"
"Alea iacta est."
"Alea " /* The die */ `iacta est` /* is cast */ "." // same as "Alea iacta est."
</pre>
<p>
These examples all represent the same string:
</p>
<pre>
"日本語" // UTF-8 input text
`日本語` // UTF-8 input text as a raw literal
"\u65e5\u672c\u8a9e" // The explicit Unicode code points
"\U000065e5\U0000672c\U00008a9e" // The explicit Unicode code points
"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // The explicit UTF-8 bytes
</pre>
<p>
If the source code represents a character as two code points, such as
a combining form involving an accent and a letter, the result will be
an error if placed in a character literal (it is not a single code
point), and will appear as two code points if placed in a string
literal.
</p>
<h2 id="Constants">Constants</h2>
<p>There are <i>boolean constants</i>, <i>integer constants</i>, <i>floating-point constants</i>,
and <i>string constants</i>. Integer and floating-point constants are
collectively called <i>numeric constants</i>.
</p>
<p>
A constant value is represented by an
<a href="#Integer_literals">integer</a>,
<a href="#Floating-point_literals">floating-point</a>,
<a href="#Character_literals">character</a>, or
<a href="#String_literals">string</a> literal,
an identifier denoting a constant,
a <a href="#Constant_expressions">constant expression</a>, or
the result value of some built-in functions such as <code>unsafe.Sizeof</code>
and <code>cap</code> or <code>len</code> applied to an array,
or <code>len</code> applied to a string constant.
The boolean truth values are represented by the predeclared constants
<code>true</code> and <code>false</code>. The predeclared identifier
<a href="#Iota">iota</a> denotes an integer constant.
</p>
<p>
Numeric constants represent values of arbitrary precision that
have no size and cannot overflow.
</p>
<p>
Constants may be <a href="#Types">typed</a> or untyped.
Literal constants, <code>true</code>, <code>false</code>, <code>iota</code>,
and certain <a href="#Constant_expressions">constant expressions</a>
containing only untyped constant operands are untyped.
</p>
<p>
A constant may be given a type explicitly by a <a href="#Constant_declarations">constant declaration</a>
or <a href="#Conversions">conversion</a>, or implicitly when used in a
<a href="#Variable_declarations">variable declaration</a> or an
<a href="#Assignments">assignment</a> or as an
operand in an <a href="#Expressions">expression</a>.
It is an error if the constant value
cannot be accurately represented as a value of the respective type.
For instance, <code>3.0</code> can be given any integer type but also any
floating-point type, while <code>2147483648.0</code> (equal to <code>1<<31</code>)
can be given the types <code>float32</code>, <code>float64</code>, or <code>uint32</code> but
not <code>int32</code> or <code>string</code>.
</p>
<p>
Implementation restriction: A compiler may implement numeric constants by choosing
an internal representation with at least twice as many bits as any machine type;
for floating-point values, both the mantissa and exponent must be twice as large.
</p>
<h2 id="Types">Types</h2>
<p>
A type determines the set of values and operations specific to values of that
type. A type may be specified by a (possibly qualified) <i>type name</i>
(§<a href="#Qualified_identifier">Qualified identifier</a>, §<a href="#Type_declarations">Type declarations</a>) or a <i>type literal</i>,
which composes a new type from previously declared types.
</p>
<pre class="ebnf">
Type = TypeName | TypeLit | "(" Type ")" .
TypeName = QualifiedIdent.
TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
SliceType | MapType | ChannelType .
</pre>
<p>
Named instances of the boolean, numeric, and string types are
<a href="#Predeclared_identifiers">predeclared</a>.
<i>Composite types</i>—array, struct, pointer, function,
interface, slice, map, and channel types—may be constructed using
type literals.
</p>
<p>
A type may have a <i>method set</i> associated with it
(§<a href="#Interface_types">Interface types</a>, §<a href="#Method_declarations">Method declarations</a>).
The method set of an <a href="#Interface_types">interface type</a> is its interface.
The method set of any other named type <code>T</code>
consists of all methods with receiver type <code>T</code>.
The method set of the corresponding pointer type <code>*T</code>
is the set of all methods with receiver <code>*T</code> or <code>T</code>
(that is, it also contains the method set of <code>T</code>).
Any other type has an empty method set.
In a method set, each method must have a unique name.
</p>
<p>
The <i>static type</i> (or just <i>type</i>) of a variable is the
type defined by its declaration. Variables of interface type
also have a distinct <i>dynamic type</i>, which
is the actual type of the value stored in the variable at run-time.
The dynamic type may vary during execution but is always assignment compatible
to the static type of the interface variable. For non-interface
types, the dynamic type is always the static type.
</p>
<h3 id="Boolean_types">Boolean types</h3>
A <i>boolean type</i> represents the set of Boolean truth values
denoted by the predeclared constants <code>true</code>
and <code>false</code>. The predeclared boolean type is <code>bool</code>.
<h3 id="Numeric_types">Numeric types</h3>
<p>
A <i>numeric type</i> represents sets of integer or floating-point values.
The predeclared architecture-independent numeric types are:
</p>
<pre class="grammar">
uint8 the set of all unsigned 8-bit integers (0 to 255)
uint16 the set of all unsigned 16-bit integers (0 to 65535)
uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
int8 the set of all signed 8-bit integers (-128 to 127)
int16 the set of all signed 16-bit integers (-32768 to 32767)
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
float32 the set of all IEEE-754 32-bit floating-point numbers
float64 the set of all IEEE-754 64-bit floating-point numbers
byte familiar alias for uint8
</pre>
<p>
Integer types are represented in the usual binary format; the value of
an n-bit integer is n bits wide. A negative signed integer is represented
as the two's complement of its absolute value.
</p>
<p>
There is also a set of predeclared numeric types with implementation-specific sizes:
</p>
<pre class="grammar">
uint either 32 or 64 bits
int either 32 or 64 bits
float either 32 or 64 bits
uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value
</pre>
<p>
To avoid portability issues all numeric types are distinct except
<code>byte</code>, which is an alias for <code>uint8</code>.
Conversions
are required when incompatible numeric types are mixed in an expression
or assignment. For instance, <code>int32</code> and <code>int</code>
are not the same type even though they may have the same size on a
particular architecture.
<h3 id="String_types">String types</h3>
<p>
A <i>string type</i> represents the set of string values.
Strings behave like arrays of bytes but are immutable: once created,
it is impossible to change the contents of a string.
The predeclared string type is <code>string</code>.
<p>
The elements of strings have type <code>byte</code> and may be
accessed using the usual <a href="#Indexes">indexing operations</a>. It is
illegal to take the address of such an element; if
<code>s[i]</code> is the <i>i</i>th byte of a
string, <code>&s[i]</code> is invalid. The length of string
<code>s</code> can be discovered using the built-in function
<code>len</code>. The length is a compile-time constant if <code>s</code>
is a string literal.
</p>
<h3 id="Array_types">Array types</h3>
<p>
An array is a numbered sequence of elements of a single
type, called the element type.
The number of elements is called the length and is never
negative.
</p>
<pre class="ebnf">
ArrayType = "[" ArrayLength "]" ElementType .
ArrayLength = Expression .
ElementType = Type .
</pre>
<p>
The length is part of the array's type and must must be a
<a href="#Constant_expressions">constant expression</a> that evaluates to a non-negative
integer value. The length of array <code>a</code> can be discovered
using the built-in function <code>len(a)</code>, which is a
compile-time constant. The elements can be indexed by integer
indices 0 through the <code>len(a)-1</code> (§<a href="#Indexes">Indexes</a>).
</p>
<pre>
[32]byte
[2*N] struct { x, y int32 }
[1000]*float64
</pre>
<h3 id="Slice_types">Slice types</h3>
<p>
A slice is a reference to a contiguous segment of an array and
contains a numbered sequence of elements from that array. A slice
type denotes the set of all slices of arrays of its element type.
A slice value may be <code>nil</code>.
</p>
<pre class="ebnf">
SliceType = "[" "]" ElementType .
</pre>
<p>
Like arrays, slices are indexable and have a length. The length of a
slice <code>s</code> can be discovered by the built-in function
<code>len(s)</code>; unlike with arrays it may change during
execution. The elements can be addressed by integer indices 0
through <code>len(s)-1</code> (§<a href="#Indexes">Indexes</a>). The slice index of a
given element may be less than the index of the same element in the
underlying array.
</p>
<p>
A slice, once initialized, is always associated with an underlying
array that holds its elements. A slice therfore shares storage
with its array and with other slices of the same array; by contrast,
distinct arrays always represent distinct storage.
</p>
<p>
The array underlying a slice may extend past the end of the slice.
The <i>capacity</i> is a measure of that extent: it is the sum of
the length of the slice and the length of the array beyond the slice;
a slice of length up to that capacity can be created by `slicing' a new
one from the original slice (§<a href="#Slices">Slices</a>).
The capacity of a slice <code>a</code> can be discovered using the
built-in function <code>cap(a)</code> and the relationship between
<code>len()</code> and <code>cap()</code> is:
</p>
<pre>
0 <= len(a) <= cap(a)
</pre>
<p>
The value of an uninitialized slice is <code>nil</code>.
The length and capacity of a <code>nil</code> slice
are 0. A new, initialized slice value for a given element type <code>T</code> is
made using the built-in function <code>make</code>, which takes a slice type
and parameters specifying the length and optionally the capacity:
</p>
<pre>
make([]T, length)
make([]T, length, capacity)
</pre>
<p>
The <code>make()</code> call allocates a new, hidden array to which the returned
slice value refers. That is, executing
</p>
<pre>
make([]T, length, capacity)
</pre>
<p>
produces the same slice as allocating an array and slicing it, so these two examples
result in the same slice:
</p>
<pre>
make([]int, 50, 100)
new([100]int)[0:50]
</pre>
<h3 id="Struct_types">Struct types</h3>
<p>
A struct is a sequence of named elements, called fields, each of which has a
name and a type. Field names may be specified explicitly (IdentifierList) or
implicitly (AnonymousField).
Within a struct, non-<a href="#Blank_identifier">blank</a> field names must
be unique.
</p>
<pre class="ebnf">
StructType = "struct" "{" [ FieldDeclList ] "}" .
FieldDeclList = FieldDecl { ";" FieldDecl } [ ";" ] .
FieldDecl = (IdentifierList Type | AnonymousField) [ Tag ] .
AnonymousField = [ "*" ] TypeName .
Tag = StringLit .
</pre>
<pre>
// An empty struct.
struct {}
// A struct with 6 fields.
struct {
x, y int;
u float;
_ float; // padding
A *[]int;
F func();
}
</pre>
<p>
A field declared with a type but no explicit field name is an <i>anonymous field</i>.
Such a field type must be specified as
a type name <code>T</code> or as a pointer to a type name <code>*T</code>,
and <code>T</code> itself may not be
a pointer type. The unqualified type name acts as the field name.
</p>
<pre>
// A struct with four anonymous fields of type T1, *T2, P.T3 and *P.T4
struct {
T1; // field name is T1
*T2; // field name is T2
P.T3; // field name is T3
*P.T4; // field name is T4
x, y int; // field names are x and y
}
</pre>
<p>
The following declaration is illegal because field names must be unique
in a struct type:
</p>
<pre>
struct {
T; // conflicts with anonymous field *T and *P.T
*T; // conflicts with anonymous field T and *P.T
*P.T; // conflicts with anonymous field T and *T
}
</pre>
<p>
Fields and methods (§<a href="#Method_declarations">Method declarations</a>) of an anonymous field are
promoted to be ordinary fields and methods of the struct (§<a href="#Selectors">Selectors</a>).
The following rules apply for a struct type named <code>S</code> and
a type named <code>T</code>:
</p>
<ul>
<li>If <code>S</code> contains an anonymous field <code>T</code>, the
method set of <code>S</code> includes the method set of <code>T</code>.
</li>
<li>If <code>S</code> contains an anonymous field <code>*T</code>, the
method set of <code>S</code> includes the method set of <code>*T</code>
(which itself includes the method set of <code>T</code>).
</li>
<li>If <code>S</code> contains an anonymous field <code>T</code> or
<code>*T</code>, the method set of <code>*S</code> includes the
method set of <code>*T</code> (which itself includes the method
set of <code>T</code>).
</li>
</ul>
<p>
A field declaration may be followed by an optional string literal <i>tag</i>,
which becomes an attribute for all the fields in the corresponding
field declaration. The tags are made
visible through a <a href="#Package_unsafe">reflection interface</a>
but are otherwise ignored.
</p>
<pre>
// A struct corresponding to the TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers.
struct {
microsec uint64 "field 1";
serverIP6 uint64 "field 2";
process string "field 3";
}
</pre>
<h3 id="Pointer_types">Pointer types</h3>
<p>
A pointer type denotes the set of all pointers to variables of a given
type, called the <i>base type</i> of the pointer.
A pointer value may be <code>nil</code>.
</p>
<pre class="ebnf">
PointerType = "*" BaseType .
BaseType = Type .
</pre>
<pre>
*int
*map[string] *chan int
</pre>
<h3 id="Function_types">Function types</h3>
<p>
A function type denotes the set of all functions with the same parameter
and result types.
A function value may be <code>nil</code>.
</p>
<pre class="ebnf">
FunctionType = "func" Signature .
Signature = Parameters [ Result ] .
Result = Parameters | Type .
Parameters = "(" [ ParameterList ] ")" .
ParameterList = ParameterDecl { "," ParameterDecl } .
ParameterDecl = [ IdentifierList ] ( Type | "..." ) .
</pre>
<p>
Within a list of parameters or results, the names (IdentifierList)
must either all be present or all be absent. If present, each name
stands for one item (parameter or result) of the specified type; if absent, each
type stands for one item of that type. Parameter and result
lists are always parenthesized except that if there is exactly
one unnamed result that is not a function type it may written as an unparenthesized type.
</p>
<p>
For the last parameter only, instead of a type one may write
<code>...</code> to indicate that the function may be invoked with
zero or more additional arguments of any
type.
</p>
<pre>
func ()
func (x int)
func () int
func (string, float, ...)
func (a, b int, z float) bool
func (a, b int, z float) (bool)
func (a, b int, z float, opt ...) (success bool)
func (int, int, float) (float, *[]int)
func (n int) (func (p* T))
</pre>
<h3 id="Interface_types">Interface types</h3>
<p>
An interface type specifies a <a href="#Types">method set</a> called its <i>interface</i>.
A variable of interface type can store a value of any type with a method set
that is any superset of the interface. Such a type is said to
<i>implement the interface</i>. An interface value may be <code>nil</code>.
</p>
<pre class="ebnf">
InterfaceType = "interface" "{" [ MethodSpecList ] "}" .
MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] .
MethodSpec = MethodName Signature | InterfaceTypeName .
MethodName = identifier .
InterfaceTypeName = TypeName .
</pre>
<p>
As with all method sets, in an interface type, each method must have a unique name.
</p>
<pre>
// A simple File interface
interface {
Read(b Buffer) bool;
Write(b Buffer) bool;
Close();
}
</pre>
<p>
More than one type may implement an interface.
For instance, if two types <code>S1</code> and <code>S2</code>
have the method set
</p>
<pre>
func (p T) Read(b Buffer) bool { return ... }
func (p T) Write(b Buffer) bool { return ... }
func (p T) Close() { ... }
</pre>
<p>
(where <code>T</code> stands for either <code>S1</code> or <code>S2</code>)
then the <code>File</code> interface is implemented by both <code>S1</code> and
<code>S2</code>, regardless of what other methods
<code>S1</code> and <code>S2</code> may have or share.
</p>
<p>
A type implements any interface comprising any subset of its methods
and may therefore implement several distinct interfaces. For
instance, all types implement the <i>empty interface</i>:
</p>
<pre>
interface{}
</pre>
<p>
Similarly, consider this interface specification,
which appears within a <a href="#Type_declarations">type declaration</a>
to define an interface called <code>Lock</code>:
</p>
<pre>
type Lock interface {
Lock();
Unlock();
}
</pre>
<p>
If <code>S1</code> and <code>S2</code> also implement
</p>
<pre>
func (p T) Lock() { ... }
func (p T) Unlock() { ... }
</pre>
<p>
they implement the <code>Lock</code> interface as well
as the <code>File</code> interface.
</p>
<p>
An interface may contain an interface type name <code>T</code>
in place of a method specification.
The effect is equivalent to enumerating the methods of <code>T</code> explicitly
in the interface.
</p>
<pre>
type ReadWrite interface {
Read(b Buffer) bool;
Write(b Buffer) bool;
}
type File interface {
ReadWrite; // same as enumerating the methods in ReadWrite
Lock; // same as enumerating the methods in Lock
Close();
}
</pre>
<h3 id="Map_types">Map types</h3>
<p>
A map is an unordered group of elements of one type, called the
element type, indexed by a set of unique <i>keys</i> of another type,
called the key type.
A map value may be <code>nil</code>.
</p>
<pre class="ebnf">
MapType = "map" "[" KeyType "]" ElementType .
KeyType = Type .
</pre>
<p>
The comparison operators <code>==</code> and <code>!=</code>
(§<a href="#Comparison_operators">Comparison operators</a>) must be fully defined for operands of the
key type; thus the key type must be a boolean, numeric, string, pointer, function, interface,
map, or channel type. If the key type is an interface type, these
comparison operators must be defined for the dynamic key values;
failure will cause a run-time error.
</p>
<pre>
map [string] int
map [*T] struct { x, y float }
map [string] interface {}
</pre>
<p>
The number of elements is called the length and is never negative.
The length of a map <code>m</code> can be discovered using the
built-in function <code>len(m)</code> and may change during execution.