go_spec.html 186 KB
Newer Older
1 2
<!--{
	"Title": "The Go Programming Language Specification",
3
	"Subtitle": "Version of August 28, 2014",
4
	"Path": "/ref/spec"
5
}-->
6

7
<!--
8
TODO
9
[ ] need language about function/method calls and parameter passing rules
Rob Pike's avatar
Rob Pike committed
10 11
[ ] last paragraph of #Assignments (constant promotion) should be elsewhere
    and mention assignment to empty interface.
Robert Griesemer's avatar
Robert Griesemer committed
12
[ ] need to say something about "scope" of selectors?
13 14
[ ] clarify what a field name is in struct declarations
    (struct{T} vs struct {T T} vs struct {t T})
15
[ ] need explicit language about the result type of operations
16 17
[ ] should probably write something about evaluation order of statements even
	though obvious
18
[ ] in Selectors section, clarify what receiver value is passed in method invocations
19 20
-->

21

22
<h2 id="Introduction">Introduction</h2>
23

24
<p>
Rob Pike's avatar
Rob Pike committed
25
This is a reference manual for the Go programming language. For
26
more information and other documents, see <a href="/">golang.org</a>.
Rob Pike's avatar
Rob Pike committed
27
</p>
28

29
<p>
Rob Pike's avatar
Rob Pike committed
30
Go is a general-purpose language designed with systems programming
Rob Pike's avatar
Rob Pike committed
31
in mind. It is strongly typed and garbage-collected and has explicit
Rob Pike's avatar
Rob Pike committed
32 33 34 35 36
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>
37

38
<p>
Rob Pike's avatar
Rob Pike committed
39 40 41
The grammar is compact and regular, allowing for easy analysis by
automatic tools such as integrated development environments.
</p>
42

43
<h2 id="Notation">Notation</h2>
Rob Pike's avatar
Rob Pike committed
44
<p>
45
The syntax is specified using Extended Backus-Naur Form (EBNF):
Rob Pike's avatar
Rob Pike committed
46
</p>
47

Rob Pike's avatar
Rob Pike committed
48
<pre class="grammar">
49
Production  = production_name "=" [ Expression ] "." .
Rob Pike's avatar
Rob Pike committed
50
Expression  = Alternative { "|" Alternative } .
51
Alternative = Term { Term } .
52
Term        = production_name | token [ "…" token ] | Group | Option | Repetition .
Rob Pike's avatar
Rob Pike committed
53
Group       = "(" Expression ")" .
54
Option      = "[" Expression "]" .
Rob Pike's avatar
Rob Pike committed
55
Repetition  = "{" Expression "}" .
56
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
57

Rob Pike's avatar
Rob Pike committed
58 59 60 61
<p>
Productions are expressions constructed from terms and the following
operators, in increasing precedence:
</p>
Rob Pike's avatar
Rob Pike committed
62
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
63 64 65 66
|   alternation
()  grouping
[]  option (0 or 1 times)
{}  repetition (0 to n times)
67
</pre>
68

69
<p>
Rob Pike's avatar
Rob Pike committed
70
Lower-case production names are used to identify lexical tokens.
71
Non-terminals are in CamelCase. Lexical tokens are enclosed in
Rob Pike's avatar
Rob Pike committed
72
double quotes <code>""</code> or back quotes <code>``</code>.
Rob Pike's avatar
Rob Pike committed
73 74
</p>

75
<p>
76 77
The form <code>a … b</code> represents the set of characters from
<code>a</code> through <code>b</code> as alternatives. The horizontal
78
ellipsis <code></code> is also used elsewhere in the spec to informally denote various
79
enumerations or code snippets that are not further specified. The character <code></code>
80 81
(as opposed to the three characters <code>...</code>) is not a token of the Go
language.
Rob Pike's avatar
Rob Pike committed
82 83
</p>

84
<h2 id="Source_code_representation">Source code representation</h2>
85

86
<p>
Robert Griesemer's avatar
Robert Griesemer committed
87 88
Source code is Unicode text encoded in
<a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. The text is not
Rob Pike's avatar
Rob Pike committed
89 90 91
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
92 93
will use the unqualified term <i>character</i> to refer to a Unicode code point
in the source text.
Rob Pike's avatar
Rob Pike committed
94
</p>
95
<p>
Rob Pike's avatar
Rob Pike committed
96 97 98
Each code point is distinct; for instance, upper and lower case letters
are different characters.
</p>
Russ Cox's avatar
Russ Cox committed
99
<p>
100 101
Implementation restriction: For compatibility with other tools, a
compiler may disallow the NUL character (U+0000) in the source text.
Russ Cox's avatar
Russ Cox committed
102
</p>
103 104
<p>
Implementation restriction: For compatibility with other tools, a
Rob Pike's avatar
Rob Pike committed
105 106
compiler may ignore a UTF-8-encoded byte order mark
(U+FEFF) if it is the first Unicode code point in the source text.
107
A byte order mark may be disallowed anywhere else in the source.
108
</p>
109

110
<h3 id="Characters">Characters</h3>
111

112
<p>
Rob Pike's avatar
Rob Pike committed
113 114
The following terms are used to denote specific Unicode character classes:
</p>
115
<pre class="ebnf">
116 117
newline        = /* the Unicode code point U+000A */ .
unicode_char   = /* an arbitrary Unicode code point except newline */ .
118
unicode_letter = /* a Unicode code point classified as "Letter" */ .
119
unicode_digit  = /* a Unicode code point classified as "Decimal Digit" */ .
120
</pre>
121

Rob Pike's avatar
Rob Pike committed
122
<p>
123
In <a href="http://www.unicode.org/versions/Unicode6.3.0/">The Unicode Standard 6.3</a>,
124
Section 4.5 "General Category"
Rob Pike's avatar
Rob Pike committed
125 126 127 128
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>
129

130
<h3 id="Letters_and_digits">Letters and digits</h3>
Rob Pike's avatar
Rob Pike committed
131 132

<p>
133
The underscore character <code>_</code> (U+005F) is considered a letter.
134 135
</p>
<pre class="ebnf">
136
letter        = unicode_letter | "_" .
137 138 139
decimal_digit = "0" … "9" .
octal_digit   = "0" … "7" .
hex_digit     = "0" … "9" | "A" … "F" | "a" … "f" .
140
</pre>
Rob Pike's avatar
Rob Pike committed
141

142
<h2 id="Lexical_elements">Lexical elements</h2>
143

144
<h3 id="Comments">Comments</h3>
145

Rob Pike's avatar
Rob Pike committed
146
<p>
147
There are two forms of comments:
Rob Pike's avatar
Rob Pike committed
148 149
</p>

150 151 152
<ol>
<li>
<i>Line comments</i> start with the character sequence <code>//</code>
153
and stop at the end of the line. A line comment acts like a newline.
154 155 156 157
</li>
<li>
<i>General comments</i> start with the character sequence <code>/*</code>
and continue through the character sequence <code>*/</code>. A general
158
comment containing one or more newlines acts like a newline, otherwise it acts
159 160 161 162 163 164 165 166 167
like a space.
</li>
</ol>

<p>
Comments do not nest.
</p>


168
<h3 id="Tokens">Tokens</h3>
169

Rob Pike's avatar
Rob Pike committed
170 171
<p>
Tokens form the vocabulary of the Go language.
Robert Griesemer's avatar
Robert Griesemer committed
172 173
There are four classes: <i>identifiers</i>, <i>keywords</i>, <i>operators
and delimiters</i>, and <i>literals</i>.  <i>White space</i>, formed from
174 175 176
spaces (U+0020), horizontal tabs (U+0009),
carriage returns (U+000D), and newlines (U+000A),
is ignored except as it separates tokens
177
that would otherwise combine into a single token. Also, a newline or end of file
Robert Griesemer's avatar
Robert Griesemer committed
178
may trigger the insertion of a <a href="#Semicolons">semicolon</a>.
179
While breaking the input into tokens,
Rob Pike's avatar
Rob Pike committed
180 181 182
the next token is the longest sequence of characters that form a
valid token.
</p>
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
<h3 id="Semicolons">Semicolons</h3>

<p>
The formal grammar uses semicolons <code>";"</code> as terminators in
a number of productions. Go programs may omit most of these semicolons
using the following two rules:
</p>

<ol>
<li>
<p>
When the input is broken into tokens, a semicolon is automatically inserted
into the token stream at the end of a non-blank line if the line's final
token is
</p>
<ul>
200 201
	<li>an
	    <a href="#Identifiers">identifier</a>
202
	</li>
203

204 205 206 207
	<li>an
	    <a href="#Integer_literals">integer</a>,
	    <a href="#Floating-point_literals">floating-point</a>,
	    <a href="#Imaginary_literals">imaginary</a>,
208
	    <a href="#Rune_literals">rune</a>, or
209 210
	    <a href="#String_literals">string</a> literal
	</li>
211

212 213 214 215 216 217
	<li>one of the <a href="#Keywords">keywords</a>
	    <code>break</code>,
	    <code>continue</code>,
	    <code>fallthrough</code>, or
	    <code>return</code>
	</li>
218

219 220 221 222 223 224
	<li>one of the <a href="#Operators_and_Delimiters">operators and delimiters</a>
	    <code>++</code>,
	    <code>--</code>,
	    <code>)</code>,
	    <code>]</code>, or
	    <code>}</code>
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
	</li>
</ul>
</li>

<li>
To allow complex statements to occupy a single line, a semicolon
may be omitted before a closing <code>")"</code> or <code>"}"</code>.
</li>
</ol>

<p>
To reflect idiomatic use, code examples in this document elide semicolons
using these rules.
</p>


241
<h3 id="Identifiers">Identifiers</h3>
242

Rob Pike's avatar
Rob Pike committed
243 244 245 246 247
<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>
248
<pre class="ebnf">
249
identifier = letter { letter | unicode_digit } .
250 251 252 253 254 255 256
</pre>
<pre>
a
_x9
ThisVariableIsExported
αβ
</pre>
257 258

<p>
Robert Griesemer's avatar
Robert Griesemer committed
259
Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>.
260 261
</p>

262

263
<h3 id="Keywords">Keywords</h3>
264

Rob Pike's avatar
Rob Pike committed
265 266 267 268 269 270 271 272 273 274
<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>
275

276
<h3 id="Operators_and_Delimiters">Operators and Delimiters</h3>
Rob Pike's avatar
Rob Pike committed
277 278

<p>
279
The following character sequences represent <a href="#Operators">operators</a>, delimiters, and other special tokens:
Rob Pike's avatar
Rob Pike committed
280 281 282 283 284
</p>
<pre class="grammar">
+    &amp;     +=    &amp;=     &amp;&amp;    ==    !=    (    )
-    |     -=    |=     ||    &lt;     &lt;=    [    ]
*    ^     *=    ^=     &lt;-    &gt;     &gt;=    {    }
Robert Griesemer's avatar
Robert Griesemer committed
285 286
/    &lt;&lt;    /=    &lt;&lt;=    ++    =     :=    ,    ;
%    &gt;&gt;    %=    &gt;&gt;=    --    !     ...   .    :
Rob Pike's avatar
Rob Pike committed
287
     &amp;^          &amp;^=
Rob Pike's avatar
Rob Pike committed
288 289
</pre>

290
<h3 id="Integer_literals">Integer literals</h3>
Rob Pike's avatar
Rob Pike committed
291 292

<p>
293 294 295
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
296 297
<code>0X</code> for hexadecimal.  In hexadecimal literals, letters
<code>a-f</code> and <code>A-F</code> represent values 10 through 15.
Rob Pike's avatar
Rob Pike committed
298
</p>
299
<pre class="ebnf">
300
int_lit     = decimal_lit | octal_lit | hex_lit .
301
decimal_lit = ( "1" … "9" ) { decimal_digit } .
302 303
octal_lit   = "0" { octal_digit } .
hex_lit     = "0" ( "x" | "X" ) hex_digit { hex_digit } .
304 305 306 307 308 309 310 311
</pre>

<pre>
42
0600
0xBadFace
170141183460469231731687303715884105727
</pre>
312

313
<h3 id="Floating-point_literals">Floating-point literals</h3>
Rob Pike's avatar
Rob Pike committed
314
<p>
315 316 317
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,
Rob Pike's avatar
Rob Pike committed
318
and an exponent part.  The integer and fractional part comprise
319
decimal digits; the exponent part is an <code>e</code> or <code>E</code>
Rob Pike's avatar
Rob Pike committed
320 321 322 323
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>
324
<pre class="ebnf">
325 326 327 328 329
float_lit = decimals "." [ decimals ] [ exponent ] |
            decimals exponent |
            "." decimals [ exponent ] .
decimals  = decimal_digit { decimal_digit } .
exponent  = ( "e" | "E" ) [ "+" | "-" ] decimals .
330 331 332 333
</pre>

<pre>
0.
Rob Pike's avatar
Rob Pike committed
334 335
72.40
072.40  // == 72.40
336 337 338 339 340 341 342
2.71828
1.e+0
6.67428e-11
1E6
.25
.12345E+5
</pre>
343

Rob Pike's avatar
Rob Pike committed
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
<h3 id="Imaginary_literals">Imaginary literals</h3>
<p>
An imaginary literal is a decimal representation of the imaginary part of a
<a href="#Constants">complex constant</a>.
It consists of a
<a href="#Floating-point_literals">floating-point literal</a>
or decimal integer followed
by the lower-case letter <code>i</code>.
</p>
<pre class="ebnf">
imaginary_lit = (decimals | float_lit) "i" .
</pre>

<pre>
0i
011i  // == 11i
0.i
2.71828i
1.e+0i
6.67428e-11i
1E6i
.25i
.12345E+5i
</pre>

369

370
<h3 id="Rune_literals">Rune literals</h3>
371

Rob Pike's avatar
Rob Pike committed
372
<p>
373 374 375 376 377 378
A rune literal represents a <a href="#Constants">rune constant</a>,
an integer value identifying a Unicode code point.
A rune literal is expressed 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 the Unicode value
of the character itself,
Rob Pike's avatar
Rob Pike committed
379 380
while multi-character sequences beginning with a backslash encode
values in various formats.
Rob Pike's avatar
Rob Pike committed
381
</p>
382
<p>
Rob Pike's avatar
Rob Pike committed
383 384 385
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
386 387 388 389
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>.
Rob Pike's avatar
Rob Pike committed
390
</p>
391
<p>
392
Several backslash escapes allow arbitrary values to be encoded as
Oling Cat's avatar
Oling Cat committed
393
ASCII text.  There are four ways to represent the integer value
394 395 396 397
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.
Rob Pike's avatar
Rob Pike committed
398 399 400
In each case the value of the literal is the value represented by
the digits in the corresponding base.
</p>
401
<p>
Rob Pike's avatar
Rob Pike committed
402 403
Although these representations all result in an integer, they have
different valid ranges.  Octal escapes must represent a value between
Rob Pike's avatar
Rob Pike committed
404 405
0 and 255 inclusive.  Hexadecimal escapes satisfy this condition
by construction. The escapes <code>\u</code> and <code>\U</code>
Rob Pike's avatar
Rob Pike committed
406
represent Unicode code points so within them some values are illegal,
407
in particular those above <code>0x10FFFF</code> and surrogate halves.
Rob Pike's avatar
Rob Pike committed
408
</p>
409
<p>
Rob Pike's avatar
Rob Pike committed
410 411 412 413 414 415 416 417 418 419 420
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
421
\'   U+0027 single quote  (valid escape only within rune literals)
Rob Pike's avatar
Rob Pike committed
422 423 424
\"   U+0022 double quote  (valid escape only within string literals)
</pre>
<p>
425
All other sequences starting with a backslash are illegal inside rune literals.
Rob Pike's avatar
Rob Pike committed
426
</p>
427
<pre class="ebnf">
Robert Griesemer's avatar
Robert Griesemer committed
428
rune_lit         = "'" ( unicode_value | byte_value ) "'" .
Rob Pike's avatar
Rob Pike committed
429 430
unicode_value    = unicode_char | little_u_value | big_u_value | escaped_char .
byte_value       = octal_byte_value | hex_byte_value .
431 432 433 434
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
Rob Pike's avatar
Rob Pike committed
435
                           hex_digit hex_digit hex_digit hex_digit .
436
escaped_char     = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
Rob Pike's avatar
Rob Pike committed
437
</pre>
438

439 440 441 442 443 444 445 446 447 448 449 450
<pre>
'a'
'ä'
'本'
'\t'
'\000'
'\007'
'\377'
'\x07'
'\xff'
'\u12e4'
'\U00101234'
451 452 453 454 455
'aa'         // illegal: too many characters
'\xa'        // illegal: too few hexadecimal digits
'\0'         // illegal: too few octal digits
'\uDFFF'     // illegal: surrogate half
'\U00110000' // illegal: invalid Unicode code point
456
</pre>
457 458


459
<h3 id="String_literals">String literals</h3>
Rob Pike's avatar
Rob Pike committed
460 461

<p>
462 463 464
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.
Rob Pike's avatar
Rob Pike committed
465 466 467
</p>
<p>
Raw string literals are character sequences between back quotes
468
<code>``</code>.  Within the quotes, any character is legal except
469
back quote. The value of a raw string literal is the
470 471
string composed of the uninterpreted (implicitly UTF-8-encoded) characters
between the quotes;
472
in particular, backslashes have no special meaning and the string may
473
contain newlines.
474
Carriage return characters ('\r') inside raw string literals
475
are discarded from the raw string value.
Rob Pike's avatar
Rob Pike committed
476 477 478
</p>
<p>
Interpreted string literals are character sequences between double
479
quotes <code>&quot;&quot;</code>. The text between the quotes,
480
which may not contain newlines, forms the
Rob Pike's avatar
Rob Pike committed
481
value of the literal, with backslash escapes interpreted as they
482
are in <a href="#Rune_literals">rune literals</a> (except that <code>\'</code> is illegal and
483 484
<code>\"</code> is legal), with the same restrictions.
The three-digit octal (<code>\</code><i>nnn</i>)
Robert Griesemer's avatar
Robert Griesemer committed
485
and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual
Rob Pike's avatar
Rob Pike committed
486 487
<i>bytes</i> of the resulting string; all other escapes represent
the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
488 489 490
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
491
the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character
Rob Pike's avatar
Rob Pike committed
492 493 494
U+00FF.
</p>

495
<pre class="ebnf">
Rob Pike's avatar
Rob Pike committed
496
string_lit             = raw_string_lit | interpreted_string_lit .
497
raw_string_lit         = "`" { unicode_char | newline } "`" .
498
interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
499
</pre>
500

501
<pre>
502 503 504
`abc`  // same as "abc"
`\n
\n`    // same as "\\n\n\\n"
505 506 507 508 509 510
"\n"
""
"Hello, world!\n"
"日本語"
"\u65e5本\U00008a9e"
"\xff\u00FF"
511 512
"\uD800"       // illegal: surrogate half
"\U00110000"   // illegal: invalid Unicode code point
513
</pre>
514

Rob Pike's avatar
Rob Pike committed
515
<p>
516
These examples all represent the same string:
Rob Pike's avatar
Rob Pike committed
517
</p>
518

519
<pre>
Rob Pike's avatar
Rob Pike committed
520 521
"日本語"                                 // UTF-8 input text
`日本語`                                 // UTF-8 input text as a raw literal
522 523 524
"\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
525
</pre>
526

527
<p>
528 529
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
530
an error if placed in a rune literal (it is not a single code
531 532
point), and will appear as two code points if placed in a string
literal.
Rob Pike's avatar
Rob Pike committed
533
</p>
534

535 536 537

<h2 id="Constants">Constants</h2>

538
<p>There are <i>boolean constants</i>,
539
<i>rune constants</i>,
540
<i>integer constants</i>,
Rob Pike's avatar
Rob Pike committed
541
<i>floating-point constants</i>, <i>complex constants</i>,
542
and <i>string constants</i>. Rune, integer, floating-point,
Rob Pike's avatar
Rob Pike committed
543
and complex constants are
544 545 546 547
collectively called <i>numeric constants</i>.
</p>

<p>
548
A constant value is represented by a
549
<a href="#Rune_literals">rune</a>,
550 551
<a href="#Integer_literals">integer</a>,
<a href="#Floating-point_literals">floating-point</a>,
Rob Pike's avatar
Rob Pike committed
552
<a href="#Imaginary_literals">imaginary</a>,
553
or
554 555
<a href="#String_literals">string</a> literal,
an identifier denoting a constant,
556 557
a <a href="#Constant_expressions">constant expression</a>,
a <a href="#Conversions">conversion</a> with a result that is a constant, or
558 559 560 561
the result value of some built-in functions such as
<code>unsafe.Sizeof</code> applied to any value,
<code>cap</code> or <code>len</code> applied to
<a href="#Length_and_capacity">some expressions</a>,
Rob Pike's avatar
Rob Pike committed
562
<code>real</code> and <code>imag</code> applied to a complex constant
563
and <code>complex</code> applied to numeric constants.
564 565 566 567
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>
Rob Pike's avatar
Rob Pike committed
568

Rob Pike's avatar
Rob Pike committed
569 570 571 572 573 574
<p>
In general, complex constants are a form of
<a href="#Constant_expressions">constant expression</a>
and are discussed in that section.
</p>

Rob Pike's avatar
Rob Pike committed
575
<p>
Robert Griesemer's avatar
Robert Griesemer committed
576
Numeric constants represent values of arbitrary precision and do not overflow.
Rob Pike's avatar
Rob Pike committed
577 578
</p>

579 580 581 582 583 584 585 586 587 588 589 590 591 592
<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
593
cannot be represented as a value of the respective type.
Robert Griesemer's avatar
Robert Griesemer committed
594
For instance, <code>3.0</code> can be given any integer or any
595 596 597
floating-point type, while <code>2147483648.0</code> (equal to <code>1&lt;&lt;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>.
598 599
</p>

600 601 602 603 604 605 606 607 608 609
<p>
There are no constants denoting the IEEE-754 infinity and not-a-number values,
but the <a href="/pkg/math/"><code>math</code> package</a>'s
<a href="/pkg/math/#Inf">Inf</a>,
<a href="/pkg/math/#NaN">NaN</a>,
<a href="/pkg/math/#IsInf">IsInf</a>, and
<a href="/pkg/math/#IsNaN">IsNaN</a>
functions return and test for those values at run time.
</p>

610
<p>
611 612 613 614
Implementation restriction: Although numeric constants have arbitrary
precision in the language, a compiler may implement them using an
internal representation with limited precision.  That said, every
implementation must:
615
</p>
616 617 618 619 620 621 622 623 624
<ul>
	<li>Represent integer constants with at least 256 bits.</li>

	<li>Represent floating-point constants, including the parts of
	    a complex constant, with a mantissa of at least 256 bits
	    and a signed exponent of at least 32 bits.</li>

	<li>Give an error if unable to represent an integer constant
	    precisely.</li>
625

626 627 628 629 630 631 632 633 634 635 636 637
	<li>Give an error if unable to represent a floating-point or
	    complex constant due to overflow.</li>

	<li>Round to the nearest representable constant if unable to
	    represent a floating-point or complex constant due to limits
	    on precision.</li>
</ul>
<p>
These requirements apply both to literal constants and to the result
of evaluating <a href="#Constant_expressions">constant
expressions</a>.
</p>
638

639
<h2 id="Types">Types</h2>
640

641
<p>
Robert Griesemer's avatar
Robert Griesemer committed
642
A type determines the set of values and operations specific to values of that
643 644 645 646
type. Types may be <i>named</i> or <i>unnamed</i>. Named types are specified
by a (possibly <a href="#Qualified_identifiers">qualified</a>)
<a href="#Type_declarations"><i>type name</i></a>; unnamed types are specified
using a <i>type literal</i>, which composes a new type from existing types.
Rob Pike's avatar
Rob Pike committed
647
</p>
648

649
<pre class="ebnf">
Rob Pike's avatar
Rob Pike committed
650
Type      = TypeName | TypeLit | "(" Type ")" .
651
TypeName  = identifier | QualifiedIdent .
Rob Pike's avatar
Rob Pike committed
652 653
TypeLit   = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
	    SliceType | MapType | ChannelType .
654
</pre>
655

656
<p>
657 658 659 660 661
Named instances of the boolean, numeric, and string types are
<a href="#Predeclared_identifiers">predeclared</a>.
<i>Composite types</i>&mdash;array, struct, pointer, function,
interface, slice, map, and channel types&mdash;may be constructed using
type literals.
Rob Pike's avatar
Rob Pike committed
662
</p>
663

664 665 666 667
<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
668
is the actual type of the value stored in the variable at run time.
669 670 671 672 673 674
The dynamic type may vary during execution but is always
<a href="#Assignability">assignable</a>
to the static type of the interface variable.  For non-interface
types, the dynamic type is always the static type.
</p>

675 676
<p>
Each type <code>T</code> has an <i>underlying type</i>: If <code>T</code>
677 678
is one of the predeclared boolean, numeric, or string types, or a type literal,
the corresponding underlying
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
type is <code>T</code> itself. Otherwise, <code>T</code>'s underlying type
is the underlying type of the type to which <code>T</code> refers in its
<a href="#Type_declarations">type declaration</a>.
</p>

<pre>
   type T1 string
   type T2 T1
   type T3 []T1
   type T4 T3
</pre>

<p>
The underlying type of <code>string</code>, <code>T1</code>, and <code>T2</code>
is <code>string</code>. The underlying type of <code>[]T1</code>, <code>T3</code>,
and <code>T4</code> is <code>[]T1</code>.
</p>

697
<h3 id="Method_sets">Method sets</h3>
Rob Pike's avatar
Rob Pike committed
698
<p>
699
A type may have a <i>method set</i> associated with it.
700
The method set of an <a href="#Interface_types">interface type</a> is its interface.
701 702 703 704
The method set of any other type <code>T</code> consists of all
<a href="#Method_declarations">methods</a> declared with receiver type <code>T</code>.
The method set of the corresponding <a href="#Pointer_types">pointer type</a> <code>*T</code>
is the set of all methods declared with receiver <code>*T</code> or <code>T</code>
Robert Griesemer's avatar
Robert Griesemer committed
705
(that is, it also contains the method set of <code>T</code>).
706 707
Further rules apply to structs containing anonymous fields, as described
in the section on <a href="#Struct_types">struct types</a>.
Robert Griesemer's avatar
Robert Griesemer committed
708
Any other type has an empty method set.
709
In a method set, each method must have a
710 711
<a href="#Uniqueness_of_identifiers">unique</a>
non-<a href="#Blank_identifier">blank</a> <a href="#MethodName">method name</a>.
Rob Pike's avatar
Rob Pike committed
712
</p>
Robert Griesemer's avatar
Robert Griesemer committed
713

714 715 716 717 718 719
<p>
The method set of a type determines the interfaces that the
type <a href="#Interface_types">implements</a>
and the methods that can be <a href="#Calls">called</a>
using a receiver of that type.
</p>
720

721 722
<h3 id="Boolean_types">Boolean types</h3>

723
<p>
724 725 726
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>.
727
</p>
728

729
<h3 id="Numeric_types">Numeric types</h3>
730

Rob Pike's avatar
Rob Pike committed
731
<p>
732 733
A <i>numeric type</i> represents sets of integer or floating-point values.
The predeclared architecture-independent numeric types are:
Rob Pike's avatar
Rob Pike committed
734
</p>
735

Rob Pike's avatar
Rob Pike committed
736
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
737 738 739 740 741 742 743 744 745
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)
746

Rob Pike's avatar
Rob Pike committed
747 748
float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers
749

Rob Pike's avatar
Rob Pike committed
750 751
complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts
Rob Pike's avatar
Rob Pike committed
752

753
byte        alias for uint8
754
rune        alias for int32
755
</pre>
756

Rob Pike's avatar
Rob Pike committed
757
<p>
Robert Griesemer's avatar
Robert Griesemer committed
758 759
The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using
<a href="http://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>.
Rob Pike's avatar
Rob Pike committed
760
</p>
761

Rob Pike's avatar
Rob Pike committed
762
<p>
763
There is also a set of predeclared numeric types with implementation-specific sizes:
Rob Pike's avatar
Rob Pike committed
764
</p>
765

766
<pre class="grammar">
767
uint     either 32 or 64 bits
768
int      same size as uint
769
uintptr  an unsigned integer large enough to store the uninterpreted bits of a pointer value
770
</pre>
771

772
<p>
773
To avoid portability issues all numeric types are distinct except
774
<code>byte</code>, which is an alias for <code>uint8</code>, and
775
<code>rune</code>, which is an alias for <code>int32</code>.
776
Conversions
777
are required when different numeric types are mixed in an expression
Rob Pike's avatar
Rob Pike committed
778
or assignment. For instance, <code>int32</code> and <code>int</code>
779
are not the same type even though they may have the same size on a
Rob Pike's avatar
Rob Pike committed
780
particular architecture.
781

782

783
<h3 id="String_types">String types</h3>
784

785
<p>
786
A <i>string type</i> represents the set of string values.
787 788
A string value is a (possibly empty) sequence of bytes.
Strings are immutable: once created,
Rob Pike's avatar
Rob Pike committed
789
it is impossible to change the contents of a string.
790
The predeclared string type is <code>string</code>.
791
</p>
Rob Pike's avatar
Rob Pike committed
792 793

<p>
794 795 796
The length of a string <code>s</code> (its size in bytes) can be discovered using
the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
The length is a compile-time constant if the string is a constant.
797 798
A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>
0 through <code>len(s)-1</code>.
799 800 801
It is illegal to take the address of such an element; if
<code>s[i]</code> is the <code>i</code>'th byte of a
string, <code>&amp;s[i]</code> is invalid.
Rob Pike's avatar
Rob Pike committed
802
</p>
803 804


805
<h3 id="Array_types">Array types</h3>
Russ Cox's avatar
Russ Cox committed
806 807 808

<p>
An array is a numbered sequence of elements of a single
809 810
type, called the element type.
The number of elements is called the length and is never
Russ Cox's avatar
Russ Cox committed
811 812 813
negative.
</p>

814
<pre class="ebnf">
Russ Cox's avatar
Russ Cox committed
815 816
ArrayType   = "[" ArrayLength "]" ElementType .
ArrayLength = Expression .
817
ElementType = Type .
Russ Cox's avatar
Russ Cox committed
818 819 820
</pre>

<p>
821 822
The length is part of the array's type; it must evaluate to a
non-negative <a href="#Constants">constant</a> representable by a value
823 824
of type <code>int</code>.
The length of array <code>a</code> can be discovered
825
using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
826
The elements can be addressed by integer <a href="#Index_expressions">indices</a>
827
0 through <code>len(a)-1</code>.
828 829
Array types are always one-dimensional but may be composed to form
multi-dimensional types.
Russ Cox's avatar
Russ Cox committed
830 831 832 833 834 835
</p>

<pre>
[32]byte
[2*N] struct { x, y int32 }
[1000]*float64
836 837
[3][5]int
[2][2][2]float64  // same as [2]([2]([2]float64))
Russ Cox's avatar
Russ Cox committed
838 839
</pre>

840
<h3 id="Slice_types">Slice types</h3>
Russ Cox's avatar
Russ Cox committed
841 842

<p>
843
A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and
844 845
provides access to a numbered sequence of elements from that array.
A slice type denotes the set of all slices of arrays of its element type.
846
The value of an uninitialized slice is <code>nil</code>.
Russ Cox's avatar
Russ Cox committed
847 848
</p>

849
<pre class="ebnf">
Russ Cox's avatar
Russ Cox committed
850 851 852 853 854 855
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
856
<a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during
857 858
execution.  The elements can be addressed by integer <a href="#Index_expressions">indices</a>
0 through <code>len(s)-1</code>.  The slice index of a
Russ Cox's avatar
Russ Cox committed
859 860 861 862 863
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
Rob Pike's avatar
Rob Pike committed
864
array that holds its elements.  A slice therefore shares storage
Russ Cox's avatar
Russ Cox committed
865 866 867 868 869
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.
870
The <i>capacity</i> is a measure of that extent: it is the sum of
Russ Cox's avatar
Russ Cox committed
871
the length of the slice and the length of the array beyond the slice;
872
a slice of length up to that capacity can be created by
Robert Griesemer's avatar
Robert Griesemer committed
873
<a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice.
Russ Cox's avatar
Russ Cox committed
874
The capacity of a slice <code>a</code> can be discovered using the
875
built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.
Russ Cox's avatar
Russ Cox committed
876 877 878
</p>

<p>
879 880 881 882
A new, initialized slice value for a given element type <code>T</code> is
made using the built-in function
<a href="#Making_slices_maps_and_channels"><code>make</code></a>,
which takes a slice type
883 884 885
and parameters specifying the length and optionally the capacity.
A slice created with <code>make</code> always allocates a new, hidden array
to which the returned slice value refers. That is, executing
Russ Cox's avatar
Russ Cox committed
886 887 888 889 890
</p>

<pre>
make([]T, length, capacity)
</pre>
891

Russ Cox's avatar
Russ Cox committed
892
<p>
893 894
produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a>
it, so these two expressions are equivalent:
Russ Cox's avatar
Russ Cox committed
895 896 897 898 899 900 901
</p>

<pre>
make([]int, 50, 100)
new([100]int)[0:50]
</pre>

902 903 904 905
<p>
Like arrays, slices are always one-dimensional but may be composed to construct
higher-dimensional objects.
With arrays of arrays, the inner arrays are, by construction, always the same length;
906 907
however with slices of slices (or arrays of slices), the inner lengths may vary dynamically.
Moreover, the inner slices must be initialized individually.
908
</p>
Russ Cox's avatar
Russ Cox committed
909

910
<h3 id="Struct_types">Struct types</h3>
911

Rob Pike's avatar
Rob Pike committed
912
<p>
913 914 915 916
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
917
be <a href="#Uniqueness_of_identifiers">unique</a>.
Rob Pike's avatar
Rob Pike committed
918
</p>
919

920
<pre class="ebnf">
921
StructType     = "struct" "{" { FieldDecl ";" } "}" .
922 923
FieldDecl      = (IdentifierList Type | AnonymousField) [ Tag ] .
AnonymousField = [ "*" ] TypeName .
924
Tag            = string_lit .
925
</pre>
926

927
<pre>
928 929
// An empty struct.
struct {}
930

Robert Griesemer's avatar
Robert Griesemer committed
931
// A struct with 6 fields.
932
struct {
933
	x, y int
934 935
	u float32
	_ float32  // padding
936 937
	A *[]int
	F func()
938 939
}
</pre>
940

Rob Pike's avatar
Rob Pike committed
941
<p>
Russ Cox's avatar
Russ Cox committed
942 943 944
A field declared with a type but no explicit field name is an <i>anonymous field</i>,
also called an <i>embedded</i> field or an embedding of the type in the struct.
An embedded type must be specified as
945
a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>,
946
and <code>T</code> itself may not be
947
a pointer type. The unqualified type name acts as the field name.
Rob Pike's avatar
Rob Pike committed
948
</p>
949

950 951 952
<pre>
// A struct with four anonymous fields of type T1, *T2, P.T3 and *P.T4
struct {
953 954 955 956 957
	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
958
}
959 960
</pre>

Rob Pike's avatar
Rob Pike committed
961
<p>
962 963
The following declaration is illegal because field names must be unique
in a struct type:
Rob Pike's avatar
Rob Pike committed
964
</p>
965

966
<pre>
967
struct {
968 969 970
	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
971
}
972
</pre>
973

974
<p>
975 976 977 978
A field or <a href="#Method_declarations">method</a> <code>f</code> of an
anonymous field in a struct <code>x</code> is called <i>promoted</i> if
<code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes
that field or method <code>f</code>.
Rob Pike's avatar
Rob Pike committed
979
</p>
Robert Griesemer's avatar
Robert Griesemer committed
980

981 982 983 984 985
<p>
Promoted fields act like ordinary fields
of a struct except that they cannot be used as field names in
<a href="#Composite_literals">composite literals</a> of the struct.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
986

987 988 989 990 991 992 993 994 995 996 997 998
<p>
Given a struct type <code>S</code> and a type named <code>T</code>,
promoted methods are included in the method set of the struct as follows:
</p>
<ul>
	<li>
	If <code>S</code> contains an anonymous field <code>T</code>,
	the <a href="#Method_sets">method sets</a> of <code>S</code>
	and <code>*S</code> both include promoted methods with receiver
	<code>T</code>. The method set of <code>*S</code> also
	includes promoted methods with receiver <code>*T</code>.
	</li>
999

1000 1001 1002 1003 1004
	<li>
	If <code>S</code> contains an anonymous field <code>*T</code>,
	the method sets of <code>S</code> and <code>*S</code> both
	include promoted methods with receiver <code>T</code> or
	<code>*T</code>.
Robert Griesemer's avatar
Robert Griesemer committed
1005 1006
	</li>
</ul>
1007

Rob Pike's avatar
Rob Pike committed
1008
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1009
A field declaration may be followed by an optional string literal <i>tag</i>,
1010
which becomes an attribute for all the fields in the corresponding
Rob Pike's avatar
Rob Pike committed
1011
field declaration. The tags are made
1012
visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a>
1013
and take part in <a href="#Type_identity">type identity</a> for structs
Rob Pike's avatar
Rob Pike committed
1014 1015
but are otherwise ignored.
</p>
1016

1017
<pre>
Rob Pike's avatar
Rob Pike committed
1018
// A struct corresponding to the TimeStamp protocol buffer.
Rob Pike's avatar
Rob Pike committed
1019
// The tag strings define the protocol buffer field numbers.
1020
struct {
1021 1022 1023
	microsec  uint64 "field 1"
	serverIP6 uint64 "field 2"
	process   string "field 3"
1024
}
1025
</pre>
1026

1027
<h3 id="Pointer_types">Pointer types</h3>
1028

Rob Pike's avatar
Rob Pike committed
1029
<p>
1030
A pointer type denotes the set of all pointers to variables of a given
1031
type, called the <i>base type</i> of the pointer.
Peter Mundy's avatar
Peter Mundy committed
1032
The value of an uninitialized pointer is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
1033
</p>
1034

1035
<pre class="ebnf">
1036
PointerType = "*" BaseType .
1037
BaseType    = Type .
1038
</pre>
1039

1040
<pre>
Robert Griesemer's avatar
Robert Griesemer committed
1041 1042
*Point
*[4]int
1043
</pre>
1044

1045
<h3 id="Function_types">Function types</h3>
1046

Rob Pike's avatar
Rob Pike committed
1047
<p>
1048
A function type denotes the set of all functions with the same parameter
Peter Mundy's avatar
Peter Mundy committed
1049
and result types. The value of an uninitialized variable of function type
1050
is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
1051
</p>
1052

1053
<pre class="ebnf">
Rob Pike's avatar
Rob Pike committed
1054 1055
FunctionType   = "func" Signature .
Signature      = Parameters [ Result ] .
1056
Result         = Parameters | Type .
1057
Parameters     = "(" [ ParameterList [ "," ] ] ")" .
Rob Pike's avatar
Rob Pike committed
1058
ParameterList  = ParameterDecl { "," ParameterDecl } .
Russ Cox's avatar
Russ Cox committed
1059
ParameterDecl  = [ IdentifierList ] [ "..." ] Type .
1060 1061 1062
</pre>

<p>
Rob Pike's avatar
Rob Pike committed
1063 1064
Within a list of parameters or results, the names (IdentifierList)
must either all be present or all be absent. If present, each name
1065 1066 1067 1068 1069
stands for one item (parameter or result) of the specified type and
all non-<a href="#Blank_identifier">blank</a> names in the signature
must be <a href="#Uniqueness_of_identifiers">unique</a>.
If absent, each type stands for one item of that type.
Parameter and result
Rob Pike's avatar
Rob Pike committed
1070
lists are always parenthesized except that if there is exactly
Robert Griesemer's avatar
Robert Griesemer committed
1071
one unnamed result it may be written as an unparenthesized type.
Rob Pike's avatar
Rob Pike committed
1072
</p>
Russ Cox's avatar
Russ Cox committed
1073

Robert Griesemer's avatar
Robert Griesemer committed
1074 1075 1076 1077 1078
<p>
The final parameter in a function signature may have
a type prefixed with <code>...</code>.
A function with such a parameter is called <i>variadic</i> and
may be invoked with zero or more arguments for that parameter.
Rob Pike's avatar
Rob Pike committed
1079
</p>
1080 1081

<pre>
Russ Cox's avatar
Russ Cox committed
1082
func()
Robert Griesemer's avatar
Robert Griesemer committed
1083 1084
func(x int) int
func(a, _ int, z float32) bool
1085
func(a, b int, z float32) (bool)
Robert Griesemer's avatar
Robert Griesemer committed
1086
func(prefix string, values ...int)
1087 1088
func(a, b int, z float64, opt ...interface{}) (success bool)
func(int, int, float64) (float64, *[]int)
Russ Cox's avatar
Russ Cox committed
1089
func(n int) func(p *T)
1090 1091 1092
</pre>


1093
<h3 id="Interface_types">Interface types</h3>
1094

Rob Pike's avatar
Rob Pike committed
1095
<p>
1096
An interface type specifies a <a href="#Method_sets">method set</a> called its <i>interface</i>.
Robert Griesemer's avatar
Robert Griesemer committed
1097 1098
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
1099
<i>implement the interface</i>.
Peter Mundy's avatar
Peter Mundy committed
1100
The value of an uninitialized variable of interface type is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
1101
</p>
1102

1103
<pre class="ebnf">
1104
InterfaceType      = "interface" "{" { MethodSpec ";" } "}" .
1105 1106
MethodSpec         = MethodName Signature | InterfaceTypeName .
MethodName         = identifier .
Rob Pike's avatar
Rob Pike committed
1107
InterfaceTypeName  = TypeName .
1108
</pre>
1109

1110
<p>
1111
As with all method sets, in an interface type, each method must have a
1112 1113
<a href="#Uniqueness_of_identifiers">unique</a>
non-<a href="#Blank_identifier">blank</a> name.
1114 1115
</p>

1116
<pre>
Rob Pike's avatar
Rob Pike committed
1117
// A simple File interface
1118
interface {
1119 1120 1121
	Read(b Buffer) bool
	Write(b Buffer) bool
	Close()
1122 1123
}
</pre>
1124

Rob Pike's avatar
Rob Pike committed
1125
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1126
More than one type may implement an interface.
Rob Pike's avatar
Rob Pike committed
1127
For instance, if two types <code>S1</code> and <code>S2</code>
Robert Griesemer's avatar
Robert Griesemer committed
1128
have the method set
Rob Pike's avatar
Rob Pike committed
1129
</p>
1130

1131
<pre>
1132 1133 1134
func (p T) Read(b Buffer) bool { return … }
func (p T) Write(b Buffer) bool { return … }
func (p T) Close() { … }
1135
</pre>
1136

Rob Pike's avatar
Rob Pike committed
1137 1138 1139 1140 1141 1142
<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>
1143

Rob Pike's avatar
Rob Pike committed
1144 1145 1146 1147 1148
<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>
1149

1150
<pre>
1151
interface{}
1152
</pre>
1153

Rob Pike's avatar
Rob Pike committed
1154 1155
<p>
Similarly, consider this interface specification,
Robert Griesemer's avatar
Robert Griesemer committed
1156
which appears within a <a href="#Type_declarations">type declaration</a>
Rob Pike's avatar
Rob Pike committed
1157 1158
to define an interface called <code>Lock</code>:
</p>
1159 1160 1161

<pre>
type Lock interface {
1162 1163
	Lock()
	Unlock()
1164
}
1165
</pre>
1166

Rob Pike's avatar
Rob Pike committed
1167 1168 1169
<p>
If <code>S1</code> and <code>S2</code> also implement
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1170

1171
<pre>
1172 1173
func (p T) Lock() { … }
func (p T) Unlock() { … }
1174 1175
</pre>

1176
<p>
Rob Pike's avatar
Rob Pike committed
1177 1178 1179 1180
they implement the <code>Lock</code> interface as well
as the <code>File</code> interface.
</p>
<p>
1181
An interface may use an interface type name <code>T</code>
Rob Pike's avatar
Rob Pike committed
1182
in place of a method specification.
1183 1184
The effect, called embedding an interface,
is equivalent to enumerating the methods of <code>T</code> explicitly
Rob Pike's avatar
Rob Pike committed
1185 1186
in the interface.
</p>
1187

1188 1189
<pre>
type ReadWrite interface {
1190 1191
	Read(b Buffer) bool
	Write(b Buffer) bool
1192
}
1193

1194
type File interface {
1195 1196 1197
	ReadWrite  // same as enumerating the methods in ReadWrite
	Lock       // same as enumerating the methods in Lock
	Close()
1198 1199
}
</pre>
1200

1201
<p>
Russ Cox's avatar
Russ Cox committed
1202 1203
An interface type <code>T</code> may not embed itself
or any interface type that embeds <code>T</code>, recursively.
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
</p>

<pre>
// illegal: Bad cannot embed itself
type Bad interface {
	Bad
}

// illegal: Bad1 cannot embed itself using Bad2
type Bad1 interface {
	Bad2
}
type Bad2 interface {
	Bad1
}
</pre>

1221
<h3 id="Map_types">Map types</h3>
1222

Rob Pike's avatar
Rob Pike committed
1223 1224
<p>
A map is an unordered group of elements of one type, called the
1225
element type, indexed by a set of unique <i>keys</i> of another type,
1226
called the key type.
1227
The value of an uninitialized map is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
1228
</p>
1229

1230
<pre class="ebnf">
1231
MapType     = "map" "[" KeyType "]" ElementType .
1232
KeyType     = Type .
1233
</pre>
1234

1235
<p>
1236 1237
The <a href="#Comparison_operators">comparison operators</a>
<code>==</code> and <code>!=</code> must be fully defined
1238 1239
for operands of the key type; thus the key type must not be a function, map, or
slice.
1240
If the key type is an interface type, these
Rob Pike's avatar
Rob Pike committed
1241
comparison operators must be defined for the dynamic key values;
Rob Pike's avatar
Rob Pike committed
1242
failure will cause a <a href="#Run_time_panics">run-time panic</a>.
Rob Pike's avatar
Rob Pike committed
1243 1244

</p>
1245

1246
<pre>
1247 1248 1249
map[string]int
map[*T]struct{ x, y float64 }
map[string]interface{}
1250
</pre>
1251

Rob Pike's avatar
Rob Pike committed
1252
<p>
1253 1254
The number of map elements is called its length.
For a map <code>m</code>, it can be discovered using the
1255
built-in function <a href="#Length_and_capacity"><code>len</code></a>
1256 1257
and may change during execution. Elements may be added during execution
using <a href="#Assignments">assignments</a> and retrieved with
1258
<a href="#Index_expressions">index expressions</a>; they may be removed with the
1259
<a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function.
Rob Pike's avatar
Rob Pike committed
1260 1261 1262
</p>
<p>
A new, empty map value is made using the built-in
1263 1264
function <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
which takes the map type and an optional capacity hint as arguments:
Rob Pike's avatar
Rob Pike committed
1265
</p>
1266

1267
<pre>
1268 1269
make(map[string]int)
make(map[string]int, 100)
1270
</pre>
1271

1272 1273 1274
<p>
The initial capacity does not bound its size:
maps grow to accommodate the number of items
1275 1276 1277
stored in them, with the exception of <code>nil</code> maps.
A <code>nil</code> map is equivalent to an empty map except that no elements
may be added.
1278

1279
<h3 id="Channel_types">Channel types</h3>
1280

Rob Pike's avatar
Rob Pike committed
1281
<p>
1282 1283 1284 1285 1286 1287
A channel provides a mechanism for
<a href="#Go_statements">concurrently executing functions</a>
to communicate by
<a href="#Send_statements">sending</a> and
<a href="#Receive_operator">receiving</a>
values of a specified element type.
1288
The value of an uninitialized channel is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
1289
</p>
1290

1291
<pre class="ebnf">
1292
ChannelType = ( "chan" | "chan" "&lt;-" | "&lt;-" "chan" ) ElementType .
1293
</pre>
1294

1295
<p>
1296
The optional <code>&lt;-</code> operator specifies the channel <i>direction</i>,
1297
<i>send</i> or <i>receive</i>. If no direction is given, the channel is
1298
<i>bidirectional</i>.
1299 1300
A channel may be constrained only to send or only to receive by
<a href="#Conversions">conversion</a> or <a href="#Assignments">assignment</a>.
1301 1302 1303
</p>

<pre>
1304 1305 1306
chan T          // can be used to send and receive values of type T
chan&lt;- float64  // can only be used to send float64s
&lt;-chan int      // can only be used to receive ints
1307 1308
</pre>

Rob Pike's avatar
Rob Pike committed
1309
<p>
1310 1311
The <code>&lt;-</code> operator associates with the leftmost <code>chan</code>
possible:
Rob Pike's avatar
Rob Pike committed
1312
</p>
1313

1314
<pre>
1315 1316 1317
chan&lt;- chan int    // same as chan&lt;- (chan int)
chan&lt;- &lt;-chan int  // same as chan&lt;- (&lt;-chan int)
&lt;-chan &lt;-chan int  // same as &lt;-chan (&lt;-chan int)
1318
chan (&lt;-chan int)
1319
</pre>
1320

Rob Pike's avatar
Rob Pike committed
1321
<p>
1322
A new, initialized channel
1323 1324
value can be made using the built-in function
<a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1325
which takes the channel type and an optional <i>capacity</i> as arguments:
Rob Pike's avatar
Rob Pike committed
1326
</p>
1327

1328
<pre>
1329
make(chan int, 100)
1330
</pre>
1331

Rob Pike's avatar
Rob Pike committed
1332
<p>
1333 1334
The capacity, in number of elements, sets the size of the buffer in the channel.
If the capacity is zero or absent, the channel is unbuffered and communication
1335 1336
succeeds only when both a sender and receiver are ready. Otherwise, the channel
is buffered and communication succeeds without blocking if the buffer
1337
is not full (sends) or not empty (receives).
1338
A <code>nil</code> channel is never ready for communication.
Rob Pike's avatar
Rob Pike committed
1339
</p>
1340

1341
<p>
1342
A channel may be closed with the built-in function
1343 1344
<a href="#Close"><code>close</code></a>.
The multi-valued assignment form of the
1345
<a href="#Receive_operator">receive operator</a>
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
reports whether a received value was sent before
the channel was closed.
</p>

<p>
A single channel may be used in
<a href="#Send_statements">send statements</a>,
<a href="#Receive_operator">receive operations</a>,
and calls to the built-in functions
<a href="#Length_and_capacity"><code>cap</code></a> and
<a href="#Length_and_capacity"><code>len</code></a>
by any number of goroutines without further synchronization.
Channels act as first-in-first-out queues.
For example, if one goroutine sends values on a channel
and a second goroutine receives them, the values are
received in the order sent.
1362 1363
</p>

1364
<h2 id="Properties_of_types_and_values">Properties of types and values</h2>
1365

1366 1367
<h3 id="Type_identity">Type identity</h3>

1368
<p>
1369
Two types are either <i>identical</i> or <i>different</i>.
1370
</p>
1371

1372
<p>
1373
Two <a href="#Types">named types</a> are identical if their type names originate in the same
1374
<a href="#Type_declarations">TypeSpec</a>.
1375
A named and an <a href="#Types">unnamed type</a> are always different. Two unnamed types are identical
1376
if the corresponding type literals are identical, that is, if they have the same
1377
literal structure and corresponding components have identical types. In detail:
1378
</p>
Rob Pike's avatar
Rob Pike committed
1379

1380
<ul>
1381 1382
	<li>Two array types are identical if they have identical element types and
	    the same array length.</li>
1383

1384
	<li>Two slice types are identical if they have identical element types.</li>
1385

1386
	<li>Two struct types are identical if they have the same sequence of fields,
1387 1388
	    and if corresponding fields have the same names, and identical types,
	    and identical tags.
1389 1390
	    Two anonymous fields are considered to have the same name. Lower-case field
	    names from different packages are always different.</li>
1391

1392
	<li>Two pointer types are identical if they have identical base types.</li>
1393

1394
	<li>Two function types are identical if they have the same number of parameters
Russ Cox's avatar
Russ Cox committed
1395 1396
	    and result values, corresponding parameter and result types are
	    identical, and either both functions are variadic or neither is.
1397
	    Parameter and result names are not required to match.</li>
1398

1399
	<li>Two interface types are identical if they have the same set of methods
1400 1401
	    with the same names and identical function types. Lower-case method names from
	    different packages are always different. The order of the methods is irrelevant.</li>
1402

1403
	<li>Two map types are identical if they have identical key and value types.</li>
1404

1405 1406
	<li>Two channel types are identical if they have identical value types and
	    the same direction.</li>
1407 1408 1409
</ul>

<p>
Rob Pike's avatar
Rob Pike committed
1410 1411
Given the declarations
</p>
1412 1413 1414

<pre>
type (
1415 1416
	T0 []string
	T1 []string
1417 1418
	T2 struct{ a, b int }
	T3 struct{ a, c int }
1419 1420
	T4 func(int, float64) *T0
	T5 func(x int, y float64) *[]string
1421
)
1422
</pre>
1423

Rob Pike's avatar
Rob Pike committed
1424
<p>
1425
these types are identical:
Rob Pike's avatar
Rob Pike committed
1426
</p>
1427

1428
<pre>
1429
T0 and T0
1430
[]int and []int
1431
struct{ a, b *T5 } and struct{ a, b *T5 }
1432
func(x int, y float64) *[]string and func(int, float64) (result *[]string)
1433
</pre>
1434

Rob Pike's avatar
Rob Pike committed
1435
<p>
1436
<code>T0</code> and <code>T1</code> are different because they are named types
1437 1438
with distinct declarations; <code>func(int, float64) *T0</code> and
<code>func(x int, y float64) *[]string</code> are different because <code>T0</code>
1439
is different from <code>[]string</code>.
Rob Pike's avatar
Rob Pike committed
1440
</p>
1441 1442


1443
<h3 id="Assignability">Assignability</h3>
Rob Pike's avatar
Rob Pike committed
1444 1445

<p>
1446 1447
A value <code>x</code> is <i>assignable</i> to a variable of type <code>T</code>
("<code>x</code> is assignable to <code>T</code>") in any of these cases:
Rob Pike's avatar
Rob Pike committed
1448
</p>
1449

Rob Pike's avatar
Rob Pike committed
1450 1451
<ul>
<li>
1452 1453 1454
<code>x</code>'s type is identical to <code>T</code>.
</li>
<li>
Rob Pike's avatar
Rob Pike committed
1455 1456
<code>x</code>'s type <code>V</code> and <code>T</code> have identical
<a href="#Types">underlying types</a> and at least one of <code>V</code>
1457
or <code>T</code> is not a <a href="#Types">named type</a>.
Robert Griesemer's avatar
Robert Griesemer committed
1458 1459
</li>
<li>
1460
<code>T</code> is an interface type and
1461 1462 1463 1464 1465
<code>x</code> <a href="#Interface_types">implements</a> <code>T</code>.
</li>
<li>
<code>x</code> is a bidirectional channel value, <code>T</code> is a channel type,
<code>x</code>'s type <code>V</code> and <code>T</code> have identical element types,
Rob Pike's avatar
Rob Pike committed
1466
and at least one of <code>V</code> or <code>T</code> is not a named type.
Rob Pike's avatar
Rob Pike committed
1467 1468
</li>
<li>
1469 1470 1471 1472 1473 1474
<code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code>
is a pointer, function, slice, map, channel, or interface type.
</li>
<li>
<code>x</code> is an untyped <a href="#Constants">constant</a> representable
by a value of type <code>T</code>.
Robert Griesemer's avatar
Robert Griesemer committed
1475
</li>
Rob Pike's avatar
Rob Pike committed
1476 1477
</ul>

1478

1479
<h2 id="Blocks">Blocks</h2>
Robert Griesemer's avatar
Robert Griesemer committed
1480 1481

<p>
1482 1483
A <i>block</i> is a possibly empty sequence of declarations and statements
within matching brace brackets.
Robert Griesemer's avatar
Robert Griesemer committed
1484 1485 1486
</p>

<pre class="ebnf">
1487 1488
Block = "{" StatementList "}" .
StatementList = { Statement ";" } .
Robert Griesemer's avatar
Robert Griesemer committed
1489 1490 1491 1492 1493 1494 1495 1496 1497
</pre>

<p>
In addition to explicit blocks in the source code, there are implicit blocks:
</p>

<ol>
	<li>The <i>universe block</i> encompasses all Go source text.</li>

Robert Griesemer's avatar
Robert Griesemer committed
1498
	<li>Each <a href="#Packages">package</a> has a <i>package block</i> containing all
Robert Griesemer's avatar
Robert Griesemer committed
1499 1500 1501 1502 1503
	    Go source text for that package.</li>

	<li>Each file has a <i>file block</i> containing all Go source text
	    in that file.</li>

1504 1505 1506
	<li>Each <a href="#If_statements">"if"</a>,
	    <a href="#For_statements">"for"</a>, and
	    <a href="#Switch_statements">"switch"</a>
Robert Griesemer's avatar
Robert Griesemer committed
1507 1508
	    statement is considered to be in its own implicit block.</li>

1509 1510
	<li>Each clause in a <a href="#Switch_statements">"switch"</a>
	    or <a href="#Select_statements">"select"</a> statement
Robert Griesemer's avatar
Robert Griesemer committed
1511 1512 1513 1514
	    acts as an implicit block.</li>
</ol>

<p>
Robert Griesemer's avatar
Robert Griesemer committed
1515
Blocks nest and influence <a href="#Declarations_and_scope">scoping</a>.
Robert Griesemer's avatar
Robert Griesemer committed
1516 1517 1518
</p>


1519
<h2 id="Declarations_and_scope">Declarations and scope</h2>
1520 1521

<p>
1522 1523 1524 1525 1526 1527 1528
A <i>declaration</i> binds a non-<a href="#Blank_identifier">blank</a> identifier to a
<a href="#Constant_declarations">constant</a>,
<a href="#Type_declarations">type</a>,
<a href="#Variable_declarations">variable</a>,
<a href="#Function_declarations">function</a>,
<a href="#Labeled_statements">label</a>, or
<a href="#Import_declarations">package</a>.
1529
Every identifier in a program must be declared.
Robert Griesemer's avatar
Robert Griesemer committed
1530 1531
No identifier may be declared twice in the same block, and
no identifier may be declared in both the file and package block.
1532
</p>
1533

1534 1535 1536
<p>
The <a href="#Blank_identifier">blank identifier</a> may be used like any other identifier
in a declaration, but it does not introduce a binding and thus is not declared.
1537 1538 1539
In the package block, the identifier <code>init</code> may only be used for
<a href="#Package_initialization"><code>init</code> function</a> declarations,
and like the blank identifier it does not introduce a new binding.
1540 1541
</p>

1542
<pre class="ebnf">
Robert Griesemer's avatar
Robert Griesemer committed
1543 1544
Declaration   = ConstDecl | TypeDecl | VarDecl .
TopLevelDecl  = Declaration | FunctionDecl | MethodDecl .
1545
</pre>
1546

1547
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1548
The <i>scope</i> of a declared identifier is the extent of source text in which
1549
the identifier denotes the specified constant, type, variable, function, label, or package.
1550
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1551

1552
<p>
1553
Go is lexically scoped using <a href="#Blocks">blocks</a>:
1554
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1555

1556
<ol>
1557
	<li>The scope of a <a href="#Predeclared_identifiers">predeclared identifier</a> is the universe block.</li>
Robert Griesemer's avatar
Robert Griesemer committed
1558 1559

	<li>The scope of an identifier denoting a constant, type, variable,
1560 1561
	    or function (but not method) declared at top level (outside any
	    function) is the package block.</li>
Robert Griesemer's avatar
Robert Griesemer committed
1562

1563
	<li>The scope of the package name of an imported package is the file block
Robert Griesemer's avatar
Robert Griesemer committed
1564 1565
	    of the file containing the import declaration.</li>

1566 1567
	<li>The scope of an identifier denoting a method receiver, function parameter,
	    or result variable is the function body.</li>
Robert Griesemer's avatar
Robert Griesemer committed
1568 1569 1570

	<li>The scope of a constant or variable identifier declared
	    inside a function begins at the end of the ConstSpec or VarSpec
1571
	    (ShortVarDecl for short variable declarations)
Robert Griesemer's avatar
Robert Griesemer committed
1572 1573 1574
	    and ends at the end of the innermost containing block.</li>

	<li>The scope of a type identifier declared inside a function
Russ Cox's avatar
Russ Cox committed
1575
	    begins at the identifier in the TypeSpec
Robert Griesemer's avatar
Robert Griesemer committed
1576
	    and ends at the end of the innermost containing block.</li>
1577
</ol>
1578

1579
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1580 1581 1582
An identifier declared in a block may be redeclared in an inner block.
While the identifier of the inner declaration is in scope, it denotes
the entity declared by the inner declaration.
1583
</p>
1584

Robert Griesemer's avatar
Robert Griesemer committed
1585
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1586
The <a href="#Package_clause">package clause</a> is not a declaration; the package name
Robert Griesemer's avatar
Robert Griesemer committed
1587
does not appear in any scope. Its purpose is to identify the files belonging
1588
to the same <a href="#Packages">package</a> and to specify the default package name for import
Robert Griesemer's avatar
Robert Griesemer committed
1589 1590
declarations.
</p>
1591 1592


1593
<h3 id="Label_scopes">Label scopes</h3>
1594

Robert Griesemer's avatar
Robert Griesemer committed
1595
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1596
Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are
1597 1598 1599
used in the <a href="#Break_statements">"break"</a>,
<a href="#Continue_statements">"continue"</a>, and
<a href="#Goto_statements">"goto"</a> statements.
Russ Cox's avatar
Russ Cox committed
1600
It is illegal to define a label that is never used.
Robert Griesemer's avatar
Robert Griesemer committed
1601 1602 1603 1604 1605
In contrast to other identifiers, labels are not block scoped and do
not conflict with identifiers that are not labels. The scope of a label
is the body of the function in which it is declared and excludes
the body of any nested function.
</p>
1606 1607


1608 1609 1610
<h3 id="Blank_identifier">Blank identifier</h3>

<p>
1611 1612 1613 1614
The <i>blank identifier</i> is represented by the underscore character <code>_</code>.
It serves as an anonymous placeholder instead of a regular (non-blank)
identifier and has special meaning in <a href="#Declarations_and_scope">declarations</a>,
as an <a href="#Operands">operand</a>, and in <a href="#Assignments">assignments</a>.
1615 1616 1617
</p>


1618
<h3 id="Predeclared_identifiers">Predeclared identifiers</h3>
1619

1620
<p>
1621 1622
The following identifiers are implicitly declared in the
<a href="#Blocks">universe block</a>:
1623 1624
</p>
<pre class="grammar">
Russ Cox's avatar
Russ Cox committed
1625 1626 1627 1628
Types:
	bool byte complex64 complex128 error float32 float64
	int int8 int16 int32 int64 rune string
	uint uint8 uint16 uint32 uint64 uintptr
1629

1630
Constants:
1631 1632 1633 1634
	true false iota

Zero value:
	nil
1635

1636
Functions:
1637
	append cap close complex copy delete imag len
Robert Griesemer's avatar
Robert Griesemer committed
1638
	make new panic print println real recover
1639
</pre>
1640

1641

1642
<h3 id="Exported_identifiers">Exported identifiers</h3>
Robert Griesemer's avatar
Robert Griesemer committed
1643

1644
<p>
1645 1646
An identifier may be <i>exported</i> to permit access to it from another package.
An identifier is exported if both:
1647 1648
</p>
<ol>
1649 1650 1651 1652 1653
	<li>the first character of the identifier's name is a Unicode upper case
	letter (Unicode class "Lu"); and</li>
	<li>the identifier is declared in the <a href="#Blocks">package block</a>
	or it is a <a href="#Struct_types">field name</a> or
	<a href="#MethodName">method name</a>.</li>
1654
</ol>
1655
<p>
1656
All other identifiers are not exported.
1657
</p>
1658

1659

1660
<h3 id="Uniqueness_of_identifiers">Uniqueness of identifiers</h3>
Robert Griesemer's avatar
Robert Griesemer committed
1661 1662

<p>
1663 1664 1665 1666
Given a set of identifiers, an identifier is called <i>unique</i> if it is
<i>different</i> from every other in the set.
Two identifiers are different if they are spelled differently, or if they
appear in different <a href="#Packages">packages</a> and are not
Shenghou Ma's avatar
Shenghou Ma committed
1667
<a href="#Exported_identifiers">exported</a>. Otherwise, they are the same.
Robert Griesemer's avatar
Robert Griesemer committed
1668 1669
</p>

1670
<h3 id="Constant_declarations">Constant declarations</h3>
1671

1672 1673
<p>
A constant declaration binds a list of identifiers (the names of
Robert Griesemer's avatar
Robert Griesemer committed
1674 1675 1676 1677
the constants) to the values of a list of <a href="#Constant_expressions">constant expressions</a>.
The number of identifiers must be equal
to the number of expressions, and the <i>n</i>th identifier on
the left is bound to the value of the <i>n</i>th expression on the
1678 1679
right.
</p>
1680

1681
<pre class="ebnf">
1682
ConstDecl      = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1683
ConstSpec      = IdentifierList [ [ Type ] "=" ExpressionList ] .
1684

1685 1686
IdentifierList = identifier { "," identifier } .
ExpressionList = Expression { "," Expression } .
1687
</pre>
1688

1689
<p>
1690
If the type is present, all constants take the type specified, and
1691
the expressions must be <a href="#Assignability">assignable</a> to that type.
1692
If the type is omitted, the constants take the
1693 1694 1695 1696 1697 1698
individual types of the corresponding expressions.
If the expression values are untyped <a href="#Constants">constants</a>,
the declared constants remain untyped and the constant identifiers
denote the constant values. For instance, if the expression is a
floating-point literal, the constant identifier denotes a floating-point
constant, even if the literal's fractional part is zero.
1699
</p>
1700

1701
<pre>
1702
const Pi float64 = 3.14159265358979323846
1703
const zero = 0.0         // untyped floating-point constant
1704
const (
1705
	size int64 = 1024
1706
	eof        = -1  // untyped integer constant
1707
)
1708
const a, b, c = 3, 4, "foo"  // a = 3, b = 4, c = "foo", untyped integer and string constants
1709
const u, v float32 = 0, 3    // u = 0.0, v = 3.0
1710
</pre>
1711

1712 1713 1714 1715
<p>
Within a parenthesized <code>const</code> declaration list the
expression list may be omitted from any but the first declaration.
Such an empty list is equivalent to the textual substitution of the
Rob Pike's avatar
Rob Pike committed
1716
first preceding non-empty expression list and its type if any.
1717 1718 1719
Omitting the list of expressions is therefore equivalent to
repeating the previous list.  The number of identifiers must be equal
to the number of expressions in the previous list.
Robert Griesemer's avatar
Robert Griesemer committed
1720 1721
Together with the <a href="#Iota"><code>iota</code> constant generator</a>
this mechanism permits light-weight declaration of sequential values:
1722
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1723

1724
<pre>
1725
const (
1726 1727 1728 1729 1730 1731 1732 1733
	Sunday = iota
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Partyday
	numberOfDays  // this constant is not exported
1734
)
1735
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
1736 1737


1738
<h3 id="Iota">Iota</h3>
1739

1740
<p>
1741
Within a <a href="#Constant_declarations">constant declaration</a>, the predeclared identifier
1742 1743
<code>iota</code> represents successive untyped integer <a href="#Constants">
constants</a>. It is reset to 0 whenever the reserved word <code>const</code>
1744 1745
appears in the source and increments after each <a href="#ConstSpec">ConstSpec</a>.
It can be used to construct a set of related constants:
1746
</p>
1747

1748
<pre>
Robert Griesemer's avatar
Robert Griesemer committed
1749
const (  // iota is reset to 0
1750 1751 1752
	c0 = iota  // c0 == 0
	c1 = iota  // c1 == 1
	c2 = iota  // c2 == 2
1753 1754 1755
)

const (
1756 1757 1758
	a = 1 &lt;&lt; iota  // a == 1 (iota has been reset)
	b = 1 &lt;&lt; iota  // b == 2
	c = 1 &lt;&lt; iota  // c == 4
1759 1760 1761
)

const (
1762 1763 1764
	u         = iota * 42  // u == 0     (untyped integer constant)
	v float64 = iota * 42  // v == 42.0  (float64 constant)
	w         = iota * 42  // w == 84    (untyped integer constant)
1765 1766
)

1767 1768
const x = iota  // x == 0 (iota has been reset)
const y = iota  // y == 0 (iota has been reset)
1769
</pre>
1770

1771
<p>
1772
Within an ExpressionList, the value of each <code>iota</code> is the same because
1773
it is only incremented after each ConstSpec:
1774
</p>
1775

1776
<pre>
1777
const (
1778 1779 1780 1781
	bit0, mask0 = 1 &lt;&lt; iota, 1&lt;&lt;iota - 1  // bit0 == 1, mask0 == 0
	bit1, mask1                           // bit1 == 2, mask1 == 1
	_, _                                  // skips iota == 2
	bit3, mask3                           // bit3 == 8, mask3 == 7
1782
)
1783
</pre>
1784

1785
<p>
1786 1787 1788
This last example exploits the implicit repetition of the
last non-empty expression list.
</p>
1789 1790


1791
<h3 id="Type_declarations">Type declarations</h3>
1792

1793
<p>
1794
A type declaration binds an identifier, the <i>type name</i>, to a new type
1795 1796 1797
that has the same <a href="#Types">underlying type</a> as an existing type,
and operations defined for the existing type are also defined for the new type.
The new type is <a href="#Type_identity">different</a> from the existing type.
1798
</p>
1799

1800
<pre class="ebnf">
1801
TypeDecl     = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
1802
TypeSpec     = identifier Type .
1803
</pre>
1804

1805
<pre>
1806
type IntArray [16]int
1807

1808
type (
1809
	Point struct{ x, y float64 }
1810 1811
	Polar Point
)
1812

1813
type TreeNode struct {
1814 1815
	left, right *TreeNode
	value *Comparable
1816 1817
}

1818
type Block interface {
1819 1820 1821
	BlockSize() int
	Encrypt(src, dst []byte)
	Decrypt(src, dst []byte)
1822
}
1823
</pre>
1824

1825 1826
<p>
The declared type does not inherit any <a href="#Method_declarations">methods</a>
1827
bound to the existing type, but the <a href="#Method_sets">method set</a>
1828
of an interface type or of elements of a composite type remains unchanged:
1829 1830 1831
</p>

<pre>
Rob Pike's avatar
Rob Pike committed
1832
// A Mutex is a data type with two methods, Lock and Unlock.
1833 1834 1835 1836 1837 1838 1839
type Mutex struct         { /* Mutex fields */ }
func (m *Mutex) Lock()    { /* Lock implementation */ }
func (m *Mutex) Unlock()  { /* Unlock implementation */ }

// NewMutex has the same composition as Mutex but its method set is empty.
type NewMutex Mutex

1840 1841 1842 1843
// The method set of the <a href="#Pointer_types">base type</a> of PtrMutex remains unchanged,
// but the method set of PtrMutex is empty.
type PtrMutex *Mutex

Robert Griesemer's avatar
Robert Griesemer committed
1844
// The method set of *PrintableMutex contains the methods
1845
// Lock and Unlock bound to its anonymous field Mutex.
1846
type PrintableMutex struct {
1847
	Mutex
1848
}
1849

1850 1851
// MyBlock is an interface type that has the same method set as Block.
type MyBlock Block
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
</pre>

<p>
A type declaration may be used to define a different boolean, numeric, or string
type and attach methods to it:
</p>

<pre>
type TimeZone int

const (
1863 1864 1865 1866
	EST TimeZone = -(5 + iota)
	CST
	MST
	PST
1867 1868 1869
)

func (tz TimeZone) String() string {
1870
	return fmt.Sprintf("GMT+%dh", tz)
1871 1872 1873 1874
}
</pre>


1875
<h3 id="Variable_declarations">Variable declarations</h3>
1876 1877 1878 1879 1880

<p>
A variable declaration creates a variable, binds an identifier to it and
gives it a type and optionally an initial value.
</p>
1881
<pre class="ebnf">
1882
VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
1883
VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
1884
</pre>
1885

1886
<pre>
1887
var i int
1888
var U, V, W float64
1889
var k = 0
1890
var x, y float32 = -1, -2
1891
var (
1892
	i       int
1893 1894
	u, v, s = 2.0, 3.0, "bar"
)
Robert Griesemer's avatar
Robert Griesemer committed
1895
var re, im = complexSqrt(-1)
1896
var _, found = entries[name]  // map lookup; only interested in "found"
1897
</pre>
1898

1899
<p>
1900
If a list of expressions is given, the variables are initialized
1901
by <a href="#Assignments">assigning</a> the expressions to the variables
Rob Pike's avatar
Rob Pike committed
1902
in order; all expressions must be consumed and all variables initialized from them.
1903
Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>.
1904
</p>
1905

1906
<p>
1907 1908 1909
If the type is present, each variable is given that type.
Otherwise, the types are deduced from the assignment
of the expression list.
1910
</p>
1911

1912
<p>
1913 1914
If the type is absent and the corresponding expression evaluates to an
untyped <a href="#Constants">constant</a>, the type of the declared variable
1915
is as described in §<a href="#Assignments">Assignments</a>.
1916 1917 1918 1919 1920 1921 1922
</p>

<p>
Implementation restriction: A compiler may make it illegal to declare a variable
inside a <a href="#Function_declarations">function body</a> if the variable is
never used.
</p>
1923

1924
<h3 id="Short_variable_declarations">Short variable declarations</h3>
1925

1926
<p>
1927
A <i>short variable declaration</i> uses the syntax:
1928
</p>
1929

1930
<pre class="ebnf">
1931
ShortVarDecl = IdentifierList ":=" ExpressionList .
1932
</pre>
1933

1934
<p>
1935
It is shorthand for a regular <a href="#Variable_declarations">variable declaration</a>
1936
with initializer expressions but no types:
1937
</p>
1938

1939 1940
<pre class="grammar">
"var" IdentifierList = ExpressionList .
1941
</pre>
1942

1943
<pre>
1944 1945 1946 1947 1948
i, j := 0, 10
f := func() int { return 7 }
ch := make(chan int)
r, w := os.Pipe(fd)  // os.Pipe() returns two values
_, y, _ := coord(p)  // coord() returns three values; only interested in y coordinate
1949
</pre>
1950

Rob Pike's avatar
Rob Pike committed
1951
<p>
1952
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they
1953
were originally declared earlier in the same block with the same type, and at
Robert Griesemer's avatar
Robert Griesemer committed
1954
least one of the non-<a href="#Blank_identifier">blank</a> variables is new.  As a consequence, redeclaration
Rob Pike's avatar
Rob Pike committed
1955 1956 1957 1958 1959 1960
can only appear in a multi-variable short declaration.
Redeclaration does not introduce a new
variable; it just assigns a new value to the original.
</p>

<pre>
1961 1962
field1, offset := nextField(str, 0)
field2, offset := nextField(str, offset)  // redeclares offset
1963
a, a := 1, 2                              // illegal: double declaration of a or no new variable if a was declared elsewhere
Rob Pike's avatar
Rob Pike committed
1964 1965
</pre>

Rob Pike's avatar
Rob Pike committed
1966
<p>
1967
Short variable declarations may appear only inside functions.
1968 1969 1970 1971 1972
In some contexts such as the initializers for
<a href="#If_statements">"if"</a>,
<a href="#For_statements">"for"</a>, or
<a href="#Switch_statements">"switch"</a> statements,
they can be used to declare local temporary variables.
Rob Pike's avatar
Rob Pike committed
1973
</p>
1974

1975
<h3 id="Function_declarations">Function declarations</h3>
1976

1977
<p>
1978 1979
A function declaration binds an identifier, the <i>function name</i>,
to a function.
1980
</p>
1981

1982
<pre class="ebnf">
1983
FunctionDecl = "func" FunctionName ( Function | Signature ) .
1984
FunctionName = identifier .
1985 1986
Function     = Signature FunctionBody .
FunctionBody = Block .
1987
</pre>
1988

1989 1990 1991 1992 1993 1994
<p>
If the function's <a href="#Function_types">signature</a> declares
result parameters, the function body's statement list must end in
a <a href="#Terminating_statements">terminating statement</a>.
</p>

1995
<pre>
Shenghou Ma's avatar
Shenghou Ma committed
1996
func findMarker(c &lt;-chan int) int {
1997
	for i := range c {
Shenghou Ma's avatar
Shenghou Ma committed
1998
		if x := &lt;-c; isMarker(x) {
1999 2000 2001 2002 2003 2004 2005
			return x
		}
	}
	// invalid: missing return statement.
}
</pre>

2006 2007 2008 2009 2010
<p>
A function declaration may omit the body. Such a declaration provides the
signature for a function implemented outside Go, such as an assembly routine.
</p>

2011 2012 2013
<pre>
func min(x int, y int) int {
	if x &lt; y {
2014
		return x
2015
	}
2016
	return y
2017
}
2018 2019

func flushICache(begin, end uintptr)  // implemented externally
2020
</pre>
2021

2022
<h3 id="Method_declarations">Method declarations</h3>
2023

2024
<p>
2025 2026 2027
A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>.
A method declaration binds an identifier, the <i>method name</i>, to a method,
and associates the method with the receiver's <i>base type</i>.
Rob Pike's avatar
Rob Pike committed
2028
</p>
2029

2030
<pre class="ebnf">
2031
MethodDecl   = "func" Receiver MethodName ( Function | Signature ) .
2032
Receiver     = Parameters .
2033 2034
</pre>

2035
<p>
2036 2037 2038 2039
The receiver is specified via an extra parameter section preceeding the method
name. That parameter section must declare a single parameter, the receiver.
Its type must be of the form <code>T</code> or <code>*T</code> (possibly using
parentheses) where <code>T</code> is a type name. The type denoted by <code>T</code> is called
2040 2041 2042 2043 2044 2045 2046
the receiver <i>base type</i>; it must not be a pointer or interface type and
it must be declared in the same package as the method.
The method is said to be <i>bound</i> to the base type and the method name
is visible only within selectors for that type.
</p>

<p>
2047 2048 2049 2050 2051 2052 2053 2054 2055
A non-<a href="#Blank_identifier">blank</a> receiver identifier must be
<a href="#Uniqueness_of_identifiers">unique</a> in the method signature.
If the receiver's value is not referenced inside the body of the method,
its identifier may be omitted in the declaration. The same applies in
general to parameters of functions and methods.
</p>

<p>
For a base type, the non-blank names of methods bound to it must be unique.
2056 2057
If the base type is a <a href="#Struct_types">struct type</a>,
the non-blank method and field names must be distinct.
Rob Pike's avatar
Rob Pike committed
2058
</p>
2059

2060 2061 2062
<p>
Given type <code>Point</code>, the declarations
</p>
2063

2064
<pre>
2065 2066
func (p *Point) Length() float64 {
	return math.Sqrt(p.x * p.x + p.y * p.y)
2067
}
2068

2069 2070 2071
func (p *Point) Scale(factor float64) {
	p.x *= factor
	p.y *= factor
2072 2073
}
</pre>
2074

2075
<p>
Rob Pike's avatar
Rob Pike committed
2076 2077
bind the methods <code>Length</code> and <code>Scale</code>,
with receiver type <code>*Point</code>,
2078 2079
to the base type <code>Point</code>.
</p>
2080

Rob Pike's avatar
Rob Pike committed
2081 2082 2083 2084 2085 2086
<p>
The type of a method is the type of a function with the receiver as first
argument.  For instance, the method <code>Scale</code> has type
</p>

<pre>
2087
func(p *Point, factor float64)
Rob Pike's avatar
Rob Pike committed
2088 2089 2090 2091 2092 2093
</pre>

<p>
However, a function declared this way is not a method.
</p>

2094

2095
<h2 id="Expressions">Expressions</h2>
2096

2097
<p>
Rob Pike's avatar
Rob Pike committed
2098
An expression specifies the computation of a value by applying
2099
operators and functions to operands.
Rob Pike's avatar
Rob Pike committed
2100
</p>
2101

2102
<h3 id="Operands">Operands</h3>
2103

2104
<p>
2105
Operands denote the elementary values in an expression. An operand may be a
2106 2107
literal, a (possibly <a href="#Qualified_identifiers">qualified</a>)
non-<a href="#Blank_identifier">blank</a> identifier denoting a
2108 2109 2110 2111 2112
<a href="#Constant_declarations">constant</a>,
<a href="#Variable_declarations">variable</a>, or
<a href="#Function_declarations">function</a>,
a <a href="#Method_expressions">method expression</a> yielding a function,
or a parenthesized expression.
2113
</p>
2114

2115 2116 2117 2118 2119
<p>
The <a href="#Blank_identifier">blank identifier</a> may appear as an
operand only on the left-hand side of an <a href="#Assignments">assignment</a>.
</p>

2120
<pre class="ebnf">
2121 2122 2123
Operand     = Literal | OperandName | MethodExpr | "(" Expression ")" .
Literal     = BasicLit | CompositeLit | FunctionLit .
BasicLit    = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
2124
OperandName = identifier | QualifiedIdent.
2125
</pre>
2126

2127
<h3 id="Qualified_identifiers">Qualified identifiers</h3>
2128

2129
<p>
2130 2131 2132
A qualified identifier is an identifier qualified with a package name prefix.
Both the package name and the identifier must not be
<a href="#Blank_identifier">blank</a>.
Rob Pike's avatar
Rob Pike committed
2133
</p>
2134

2135
<pre class="ebnf">
2136
QualifiedIdent = PackageName "." identifier .
2137
</pre>
2138

Rob Pike's avatar
Rob Pike committed
2139
<p>
Robert Griesemer's avatar
Robert Griesemer committed
2140 2141
A qualified identifier accesses an identifier in a different package, which
must be <a href="#Import_declarations">imported</a>.
2142 2143
The identifier must be <a href="#Exported_identifiers">exported</a> and
declared in the <a href="#Blocks">package block</a> of that package.
Rob Pike's avatar
Rob Pike committed
2144 2145 2146
</p>

<pre>
2147
math.Sin	// denotes the Sin function in package math
Rob Pike's avatar
Rob Pike committed
2148
</pre>
2149

2150
<h3 id="Composite_literals">Composite literals</h3>
2151

Rob Pike's avatar
Rob Pike committed
2152 2153 2154 2155
<p>
Composite literals construct values for structs, arrays, slices, and maps
and create a new value each time they are evaluated.
They consist of the type of the value
2156 2157
followed by a brace-bound list of composite elements. An element may be
a single expression or a key-value pair.
Rob Pike's avatar
Rob Pike committed
2158
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2159

2160
<pre class="ebnf">
2161
CompositeLit  = LiteralType LiteralValue .
Rob Pike's avatar
Rob Pike committed
2162
LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
2163
                SliceType | MapType | TypeName .
2164
LiteralValue  = "{" [ ElementList [ "," ] ] "}" .
2165
ElementList   = Element { "," Element } .
2166
Element       = [ Key ":" ] Value .
2167
Key           = FieldName | ElementIndex .
Rob Pike's avatar
Rob Pike committed
2168
FieldName     = identifier .
2169
ElementIndex  = Expression .
2170
Value         = Expression | LiteralValue .
2171
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2172

Rob Pike's avatar
Rob Pike committed
2173
<p>
2174 2175 2176
The LiteralType must be a struct, array, slice, or map type
(the grammar enforces this constraint except when the type is given
as a TypeName).
2177 2178
The types of the expressions must be <a href="#Assignability">assignable</a>
to the respective field, element, and key types of the LiteralType;
2179
there is no additional conversion.
2180
The key is interpreted as a field name for struct literals,
2181
an index for array and slice literals, and a key for map literals.
2182 2183 2184
For map literals, all elements must have a key. It is an error
to specify multiple elements with the same field name or
constant key value.
Rob Pike's avatar
Rob Pike committed
2185
</p>
2186

2187 2188
<p>
For struct literals the following rules apply:
2189
</p>
2190
<ul>
2191 2192
	<li>A key must be a field name declared in the LiteralType.
	</li>
2193
	<li>An element list that does not contain any keys must
2194 2195 2196 2197 2198
	    list an element for each struct field in the
	    order in which the fields are declared.
	</li>
	<li>If any element has a key, every element must have a key.
	</li>
2199
	<li>An element list that contains keys does not need to
2200 2201 2202 2203
	    have an element for each struct field. Omitted fields
	    get the zero value for that field.
	</li>
	<li>A literal may omit the element list; such a literal evaluates
2204
	    to the zero value for its type.
2205 2206 2207 2208 2209 2210 2211 2212 2213
	</li>
	<li>It is an error to specify an element for a non-exported
	    field of a struct belonging to a different package.
	</li>
</ul>

<p>
Given the declarations
</p>
2214
<pre>
2215 2216
type Point3D struct { x, y, z float64 }
type Line struct { p, q Point3D }
2217
</pre>
2218

Rob Pike's avatar
Rob Pike committed
2219 2220 2221
<p>
one may write
</p>
2222

2223
<pre>
2224 2225
origin := Point3D{}                            // zero value for Point3D
line := Line{origin, Point3D{y: -4, z: 12.3}}  // zero value for line.q.x
2226 2227
</pre>

2228 2229 2230
<p>
For array and slice literals the following rules apply:
</p>
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
<ul>
	<li>Each element has an associated integer index marking
	    its position in the array.
	</li>
	<li>An element with a key uses the key as its index; the
	    key must be a constant integer expression.
	</li>
	<li>An element without a key uses the previous element's index plus one.
	    If the first element has no key, its index is zero.
	</li>
</ul>

2243
<p>
2244
<a href="#Address_operators">Taking the address</a> of a composite literal
2245
generates a pointer to a unique instance of the literal's value.
2246 2247
</p>
<pre>
2248
var pointer *Point3D = &amp;Point3D{y: 1000}
2249
</pre>
2250

Rob Pike's avatar
Rob Pike committed
2251
<p>
2252 2253
The length of an array literal is the length specified in the LiteralType.
If fewer elements than the length are provided in the literal, the missing
Rob Pike's avatar
Rob Pike committed
2254
elements are set to the zero value for the array element type.
2255 2256 2257
It is an error to provide elements with index values outside the index range
of the array. The notation <code>...</code> specifies an array length equal
to the maximum element index plus one.
Rob Pike's avatar
Rob Pike committed
2258
</p>
2259

2260
<pre>
2261 2262 2263
buffer := [10]string{}             // len(buffer) == 10
intSet := [6]int{1, 2, 3, 5}       // len(intSet) == 6
days := [...]string{"Sat", "Sun"}  // len(days) == 2
2264
</pre>
2265

Rob Pike's avatar
Rob Pike committed
2266 2267
<p>
A slice literal describes the entire underlying array literal.
Rob Pike's avatar
Rob Pike committed
2268
Thus, the length and capacity of a slice literal are the maximum
2269
element index plus one. A slice literal has the form
Rob Pike's avatar
Rob Pike committed
2270
</p>
2271

2272
<pre>
2273
[]T{x1, x2, … xn}
2274
</pre>
2275

Rob Pike's avatar
Rob Pike committed
2276
<p>
2277
and is shorthand for a slice operation applied to an array:
Rob Pike's avatar
Rob Pike committed
2278
</p>
2279

2280
<pre>
Russ Cox's avatar
Russ Cox committed
2281 2282
tmp := [n]T{x1, x2, … xn}
tmp[0 : n]
2283
</pre>
2284

2285 2286 2287 2288
<p>
Within a composite literal of array, slice, or map type <code>T</code>,
elements that are themselves composite literals may elide the respective
literal type if it is identical to the element type of <code>T</code>.
2289
Similarly, elements that are addresses of composite literals may elide
2290
the <code>&amp;T</code> when the element type is <code>*T</code>.
2291 2292 2293
</p>

<pre>
2294 2295 2296
[...]Point{{1.5, -3.5}, {0, 0}}   // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}}
[][]int{{1, 2, 3}, {4, 5}}        // same as [][]int{[]int{1, 2, 3}, []int{4, 5}}

2297
[...]*Point{{1.5, -3.5}, {0, 0}}  // same as [...]*Point{&amp;Point{1.5, -3.5}, &amp;Point{0, 0}}
2298 2299
</pre>

2300 2301
<p>
A parsing ambiguity arises when a composite literal using the
2302 2303 2304 2305 2306 2307 2308
TypeName form of the LiteralType appears as an operand between the
<a href="#Keywords">keyword</a> and the opening brace of the block
of an "if", "for", or "switch" statement, and the composite literal
is not enclosed in parentheses, square brackets, or curly braces.
In this rare case, the opening brace of the literal is erroneously parsed
as the one introducing the block of statements. To resolve the ambiguity,
the composite literal must appear within parentheses.
2309 2310 2311
</p>

<pre>
2312 2313
if x == (T{a,b,c}[i]) { … }
if (x == T{a,b,c}[i]) { … }
2314 2315
</pre>

2316 2317 2318 2319 2320 2321
<p>
Examples of valid array, slice, and map literals:
</p>

<pre>
// list of prime numbers
Rob Pike's avatar
Rob Pike committed
2322
primes := []int{2, 3, 5, 7, 9, 2147483647}
2323 2324

// vowels[ch] is true if ch is a vowel
2325
vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}
2326

2327 2328
// the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1}
filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1}
2329 2330

// frequencies in Hz for equal-tempered scale (A4 = 440Hz)
2331
noteFrequency := map[string]float32{
2332 2333 2334 2335 2336 2337
	"C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83,
	"G0": 24.50, "A0": 27.50, "B0": 30.87,
}
</pre>


2338
<h3 id="Function_literals">Function literals</h3>
2339

Rob Pike's avatar
Rob Pike committed
2340
<p>
2341
A function literal represents an anonymous <a href="#Function_declarations">function</a>.
Rob Pike's avatar
Rob Pike committed
2342
</p>
2343

2344
<pre class="ebnf">
2345
FunctionLit = "func" Function .
2346
</pre>
2347

2348
<pre>
2349
func(a, b int, z float64) bool { return a*b &lt; int(z) }
2350
</pre>
2351

Rob Pike's avatar
Rob Pike committed
2352 2353 2354
<p>
A function literal can be assigned to a variable or invoked directly.
</p>
2355

2356
<pre>
Rob Pike's avatar
Rob Pike committed
2357
f := func(x, y int) int { return x + y }
2358
func(ch chan int) { ch &lt;- ACK }(replyChan)
2359
</pre>
2360

Rob Pike's avatar
Rob Pike committed
2361 2362
<p>
Function literals are <i>closures</i>: they may refer to variables
2363 2364
defined in a surrounding function. Those variables are then shared between
the surrounding function and the function literal, and they survive as long
Rob Pike's avatar
Rob Pike committed
2365 2366
as they are accessible.
</p>
2367

2368

2369
<h3 id="Primary_expressions">Primary expressions</h3>
2370

2371 2372 2373 2374
<p>
Primary expressions are the operands for unary and binary expressions.
</p>

2375
<pre class="ebnf">
2376 2377
PrimaryExpr =
	Operand |
2378
	Conversion |
2379
	BuiltinCall |
2380 2381 2382
	PrimaryExpr Selector |
	PrimaryExpr Index |
	PrimaryExpr Slice |
2383
	PrimaryExpr TypeAssertion |
2384 2385
	PrimaryExpr Call .

2386 2387
Selector       = "." identifier .
Index          = "[" Expression "]" .
Robert Griesemer's avatar
Robert Griesemer committed
2388 2389 2390
Slice          = "[" ( [ Expression ] ":" [ Expression ] ) |
                     ( [ Expression ] ":" Expression ":" Expression )
                 "]" .
2391
TypeAssertion  = "." "(" Type ")" .
Robert Griesemer's avatar
Robert Griesemer committed
2392 2393
Call           = "(" [ ArgumentList [ "," ] ] ")" .
ArgumentList   = ExpressionList [ "..." ] .
2394 2395 2396 2397 2398 2399 2400 2401
</pre>


<pre>
x
2
(s + ".txt")
f(3.1415, true)
2402
Point{1, 2}
2403 2404 2405 2406 2407 2408 2409
m["foo"]
s[i : j + 1]
obj.color
f.p[i].x()
</pre>


2410
<h3 id="Selectors">Selectors</h3>
2411

Rob Pike's avatar
Rob Pike committed
2412
<p>
2413 2414 2415
For a <a href="#Primary_expressions">primary expression</a> <code>x</code>
that is not a <a href="#Package_clause">package name</a>, the
<i>selector expression</i>
Rob Pike's avatar
Rob Pike committed
2416
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2417

2418 2419 2420
<pre>
x.f
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2421

2422
<p>
2423 2424 2425 2426 2427 2428 2429
denotes the field or method <code>f</code> of the value <code>x</code>
(or sometimes <code>*x</code>; see below).
The identifier <code>f</code> is called the (field or method) <i>selector</i>;
it must not be the <a href="#Blank_identifier">blank identifier</a>.
The type of the selector expression is the type of <code>f</code>.
If <code>x</code> is a package name, see the section on
<a href="#Qualified_identifiers">qualified identifiers</a>.
Rob Pike's avatar
Rob Pike committed
2430
</p>
2431

2432
<p>
Rob Pike's avatar
Rob Pike committed
2433 2434
A selector <code>f</code> may denote a field or method <code>f</code> of
a type <code>T</code>, or it may refer
2435 2436
to a field or method <code>f</code> of a nested
<a href="#Struct_types">anonymous field</a> of <code>T</code>.
Rob Pike's avatar
Rob Pike committed
2437 2438 2439 2440 2441 2442 2443 2444
The number of anonymous fields traversed
to reach <code>f</code> is called its <i>depth</i> in <code>T</code>.
The depth of a field or method <code>f</code>
declared in <code>T</code> is zero.
The depth of a field or method <code>f</code> declared in
an anonymous field <code>A</code> in <code>T</code> is the
depth of <code>f</code> in <code>A</code> plus one.
</p>
2445

2446
<p>
2447
The following rules apply to selectors:
Rob Pike's avatar
Rob Pike committed
2448
</p>
2449

Rob Pike's avatar
Rob Pike committed
2450 2451 2452 2453 2454 2455 2456
<ol>
<li>
For a value <code>x</code> of type <code>T</code> or <code>*T</code>
where <code>T</code> is not an interface type,
<code>x.f</code> denotes the field or method at the shallowest depth
in <code>T</code> where there
is such an <code>f</code>.
2457 2458
If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a>
with shallowest depth, the selector expression is illegal.
Rob Pike's avatar
Rob Pike committed
2459 2460
</li>
<li>
2461 2462 2463 2464 2465 2466
For a variable <code>x</code> of type <code>I</code> where <code>I</code>
is an interface type, <code>x.f</code> denotes the actual method with name
<code>f</code> of the value assigned to <code>x</code>.
If there is no method with name <code>f</code> in the
<a href="#Method_sets">method set</a> of <code>I</code>, the selector
expression is illegal.
Rob Pike's avatar
Rob Pike committed
2467 2468 2469
</li>
<li>
In all other cases, <code>x.f</code> is illegal.
2470
</li>
2471
<li>
Russ Cox's avatar
Russ Cox committed
2472 2473 2474 2475 2476 2477 2478 2479 2480
If <code>x</code> is of pointer type and has the value
<code>nil</code> and <code>x.f</code> denotes a struct field,
assigning to or evaluating <code>x.f</code>
causes a <a href="#Run_time_panics">run-time panic</a>.
</li>
<li>
If <code>x</code> is of interface type and has the value
<code>nil</code>, <a href="#Calls">calling</a> or
<a href="#Method_values">evaluating</a> the method <code>x.f</code>
2481
causes a <a href="#Run_time_panics">run-time panic</a>.
2482
</li>
Rob Pike's avatar
Rob Pike committed
2483
</ol>
2484

2485
<p>
2486 2487
Selectors automatically <a href="#Address_operators">dereference</a>
pointers to structs.
2488 2489 2490
If <code>x</code> is a pointer to a struct, <code>x.y</code>
is shorthand for <code>(*x).y</code>; if the field <code>y</code>
is also a pointer to a struct, <code>x.y.z</code> is shorthand
Rob Pike's avatar
Rob Pike committed
2491
for <code>(*(*x).y).z</code>, and so on.
2492 2493
If <code>x</code> contains an anonymous field of type <code>*A</code>,
where <code>A</code> is also a struct type,
2494
<code>x.f</code> is shorthand for <code>(*x.A).f</code>.
Rob Pike's avatar
Rob Pike committed
2495
</p>
2496

2497
<p>
Rob Pike's avatar
Rob Pike committed
2498 2499
For example, given the declarations:
</p>
2500

2501 2502
<pre>
type T0 struct {
2503
	x int
2504
}
2505

2506
func (recv *T0) M0()
2507

2508
type T1 struct {
2509
	y int
2510
}
2511

2512
func (recv T1) M1()
2513

2514
type T2 struct {
2515 2516 2517
	z int
	T1
	*T0
2518
}
Robert Griesemer's avatar
Robert Griesemer committed
2519

2520
func (recv *T2) M2()
Robert Griesemer's avatar
Robert Griesemer committed
2521

Shenghou Ma's avatar
Shenghou Ma committed
2522
var p *T2  // with p != nil and p.T0 != nil
2523
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2524

Rob Pike's avatar
Rob Pike committed
2525 2526 2527
<p>
one may write:
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2528

2529
<pre>
2530 2531 2532
p.z   // (*p).z
p.y   // ((*p).T1).y
p.x   // (*(*p).T0).x
Robert Griesemer's avatar
Robert Griesemer committed
2533

2534 2535 2536
p.M2()  // (*p).M2()
p.M1()  // ((*p).T1).M1()
p.M0()  // ((*p).T0).M0()
2537
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2538 2539


2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766
<h3 id="Method_expressions">Method expressions</h3>

<p>
If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
<code>T.M</code> is a function that is callable as a regular function
with the same arguments as <code>M</code> prefixed by an additional
argument that is the receiver of the method.
</p>

<pre class="ebnf">
MethodExpr    = ReceiverType "." MethodName .
ReceiverType  = TypeName | "(" "*" TypeName ")" | "(" ReceiverType ")" .
</pre>

<p>
Consider a struct type <code>T</code> with two methods,
<code>Mv</code>, whose receiver is of type <code>T</code>, and
<code>Mp</code>, whose receiver is of type <code>*T</code>.
</p>

<pre>
type T struct {
	a int
}
func (tv  T) Mv(a int) int         { return 0 }  // value receiver
func (tp *T) Mp(f float32) float32 { return 1 }  // pointer receiver

var t T
</pre>

<p>
The expression
</p>

<pre>
T.Mv
</pre>

<p>
yields a function equivalent to <code>Mv</code> but
with an explicit receiver as its first argument; it has signature
</p>

<pre>
func(tv T, a int) int
</pre>

<p>
That function may be called normally with an explicit receiver, so
these five invocations are equivalent:
</p>

<pre>
t.Mv(7)
T.Mv(t, 7)
(T).Mv(t, 7)
f1 := T.Mv; f1(t, 7)
f2 := (T).Mv; f2(t, 7)
</pre>

<p>
Similarly, the expression
</p>

<pre>
(*T).Mp
</pre>

<p>
yields a function value representing <code>Mp</code> with signature
</p>

<pre>
func(tp *T, f float32) float32
</pre>

<p>
For a method with a value receiver, one can derive a function
with an explicit pointer receiver, so
</p>

<pre>
(*T).Mv
</pre>

<p>
yields a function value representing <code>Mv</code> with signature
</p>

<pre>
func(tv *T, a int) int
</pre>

<p>
Such a function indirects through the receiver to create a value
to pass as the receiver to the underlying method;
the method does not overwrite the value whose address is passed in
the function call.
</p>

<p>
The final case, a value-receiver function for a pointer-receiver method,
is illegal because pointer-receiver methods are not in the method set
of the value type.
</p>

<p>
Function values derived from methods are called with function call syntax;
the receiver is provided as the first argument to the call.
That is, given <code>f := T.Mv</code>, <code>f</code> is invoked
as <code>f(t, 7)</code> not <code>t.f(7)</code>.
To construct a function that binds the receiver, use a
<a href="#Function_literals">function literal</a> or
<a href="#Method_values">method value</a>.
</p>

<p>
It is legal to derive a function value from a method of an interface type.
The resulting function takes an explicit receiver of that interface type.
</p>

<h3 id="Method_values">Method values</h3>

<p>
If the expression <code>x</code> has static type <code>T</code> and
<code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
<code>x.M</code> is called a <i>method value</i>.
The method value <code>x.M</code> is a function value that is callable
with the same arguments as a method call of <code>x.M</code>.
The expression <code>x</code> is evaluated and saved during the evaluation of the
method value; the saved copy is then used as the receiver in any calls,
which may be executed later.
</p>

<p>
The type <code>T</code> may be an interface or non-interface type.
</p>

<p>
As in the discussion of <a href="#Method_expressions">method expressions</a> above,
consider a struct type <code>T</code> with two methods,
<code>Mv</code>, whose receiver is of type <code>T</code>, and
<code>Mp</code>, whose receiver is of type <code>*T</code>.
</p>

<pre>
type T struct {
	a int
}
func (tv  T) Mv(a int) int         { return 0 }  // value receiver
func (tp *T) Mp(f float32) float32 { return 1 }  // pointer receiver

var t T
var pt *T
func makeT() T
</pre>

<p>
The expression
</p>

<pre>
t.Mv
</pre>

<p>
yields a function value of type
</p>

<pre>
func(int) int
</pre>

<p>
These two invocations are equivalent:
</p>

<pre>
t.Mv(7)
f := t.Mv; f(7)
</pre>

<p>
Similarly, the expression
</p>

<pre>
pt.Mp
</pre>

<p>
yields a function value of type
</p>

<pre>
func(float32) float32
</pre>

<p>
As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver
using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>.
</p>

<p>
As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver
using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&amp;t).Mp</code>.
</p>

<pre>
f := t.Mv; f(7)   // like t.Mv(7)
f := pt.Mp; f(7)  // like pt.Mp(7)
f := pt.Mv; f(7)  // like (*pt).Mv(7)
f := t.Mp; f(7)   // like (&amp;t).Mp(7)
f := makeT().Mp   // invalid: result of makeT() is not addressable
</pre>

<p>
Although the examples above use non-interface types, it is also legal to create a method value
from a value of interface type.
</p>

<pre>
var i interface { M(int) } = myVal
f := i.M; f(7)  // like i.M(7)
</pre>


2767
<h3 id="Index_expressions">Index expressions</h3>
2768

Rob Pike's avatar
Rob Pike committed
2769
<p>
Robert Griesemer's avatar
Robert Griesemer committed
2770
A primary expression of the form
Rob Pike's avatar
Rob Pike committed
2771
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2772

2773 2774 2775
<pre>
a[x]
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2776

Rob Pike's avatar
Rob Pike committed
2777
<p>
2778 2779 2780
denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>.
The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively.
The following rules apply:
Rob Pike's avatar
Rob Pike committed
2781
</p>
2782

2783 2784 2785 2786
<p>
If <code>a</code> is not a map:
</p>
<ul>
2787 2788
	<li>the index <code>x</code> must be of integer type or untyped;
	    it is <i>in range</i> if <code>0 &lt;= x &lt; len(a)</code>,
2789 2790
	    otherwise it is <i>out of range</i></li>
	<li>a <a href="#Constants">constant</a> index must be non-negative
2791
	    and representable by a value of type <code>int</code>
2792 2793
</ul>

2794
<p>
2795
For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>:
Rob Pike's avatar
Rob Pike committed
2796
</p>
2797
<ul>
2798
	<li>a <a href="#Constants">constant</a> index must be in range</li>
2799
	<li>if <code>x</code> is out of range at run time,
2800
	    a <a href="#Run_time_panics">run-time panic</a> occurs</li>
Rob Pike's avatar
Rob Pike committed
2801
	<li><code>a[x]</code> is the array element at index <code>x</code> and the type of
2802
	    <code>a[x]</code> is the element type of <code>A</code></li>
2803 2804 2805
</ul>

<p>
2806 2807 2808 2809 2810 2811 2812 2813
For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type:
</p>
<ul>
	<li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li>
</ul>

<p>
For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>:
2814 2815
</p>
<ul>
2816
	<li>if <code>x</code> is out of range at run time,
2817 2818
	    a <a href="#Run_time_panics">run-time panic</a> occurs</li>
	<li><code>a[x]</code> is the slice element at index <code>x</code> and the type of
2819
	    <code>a[x]</code> is the element type of <code>S</code></li>
2820
</ul>
2821 2822

<p>
2823
For <code>a</code> of <a href="#String_types">string type</a>:
2824 2825
</p>
<ul>
2826
	<li>a <a href="#Constants">constant</a> index must be in range
2827 2828 2829
	    if the string <code>a</code> is also constant</li>
	<li>if <code>x</code> is out of range at run time,
	    a <a href="#Run_time_panics">run-time panic</a> occurs</li>
2830
	<li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of
2831
	    <code>a[x]</code> is <code>byte</code></li>
2832
	<li><code>a[x]</code> may not be assigned to</li>
2833 2834
</ul>

2835
<p>
2836
For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>:
Rob Pike's avatar
Rob Pike committed
2837
</p>
2838
<ul>
2839
	<li><code>x</code>'s type must be
2840 2841
	    <a href="#Assignability">assignable</a>
	    to the key type of <code>M</code></li>
2842
	<li>if the map contains an entry with key <code>x</code>,
2843 2844
	    <code>a[x]</code> is the map value with key <code>x</code>
	    and the type of <code>a[x]</code> is the value type of <code>M</code></li>
2845
	<li>if the map is <code>nil</code> or does not contain such an entry,
2846 2847
	    <code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
	    for the value type of <code>M</code></li>
2848
</ul>
Robert Griesemer's avatar
Robert Griesemer committed
2849

2850
<p>
2851
Otherwise <code>a[x]</code> is illegal.
Rob Pike's avatar
Rob Pike committed
2852 2853 2854
</p>

<p>
2855
An index expression on a map <code>a</code> of type <code>map[K]V</code>
2856
used in an <a href="#Assignments">assignment</a> or initialization of the special form
Rob Pike's avatar
Rob Pike committed
2857 2858 2859
</p>

<pre>
2860 2861 2862
v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
Rob Pike's avatar
Rob Pike committed
2863 2864 2865
</pre>

<p>
2866
yields an additional untyped boolean value. The value of <code>ok</code> is
2867
<code>true</code> if the key <code>x</code> is present in the map, and
2868
<code>false</code> otherwise.
Rob Pike's avatar
Rob Pike committed
2869 2870
</p>

2871 2872 2873 2874 2875
<p>
Assigning to an element of a <code>nil</code> map causes a
<a href="#Run_time_panics">run-time panic</a>.
</p>

2876

Robert Griesemer's avatar
Robert Griesemer committed
2877 2878 2879 2880 2881 2882 2883 2884 2885
<h3 id="Slice_expressions">Slice expressions</h3>

<p>
Slice expressions construct a substring or slice from a string, array, pointer
to array, or slice. There are two variants: a simple form that specifies a low
and high bound, and a full form that also specifies a bound on the capacity.
</p>

<h4>Simple slice expressions</h4>
2886

Rob Pike's avatar
Rob Pike committed
2887
<p>
2888
For a string, array, pointer to array, or slice <code>a</code>, the primary expression
Rob Pike's avatar
Rob Pike committed
2889
</p>
2890

2891
<pre>
2892
a[low : high]
2893
</pre>
2894

Rob Pike's avatar
Rob Pike committed
2895
<p>
2896 2897 2898
constructs a substring or slice. The <i>indices</i> <code>low</code> and
<code>high</code> select which elements of operand <code>a</code> appear
in the result. The result has indices starting at 0 and length equal to
2899
<code>high</code>&nbsp;-&nbsp;<code>low</code>.
2900 2901 2902 2903
After slicing the array <code>a</code>
</p>

<pre>
2904 2905
a := [5]int{1, 2, 3, 4, 5}
s := a[1:4]
2906 2907 2908 2909
</pre>

<p>
the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements
Rob Pike's avatar
Rob Pike committed
2910
</p>
2911

2912 2913 2914
<pre>
s[0] == 2
s[1] == 3
2915
s[2] == 4
2916
</pre>
2917

Rob Pike's avatar
Rob Pike committed
2918
<p>
2919
For convenience, any of the indices may be omitted. A missing <code>low</code>
2920 2921
index defaults to zero; a missing <code>high</code> index defaults to the length of the
sliced operand:
2922 2923
</p>

2924
<pre>
2925
a[2:]  // same as a[2 : len(a)]
2926 2927
a[:3]  // same as a[0 : 3]
a[:]   // same as a[0 : len(a)]
2928 2929
</pre>

2930
<p>
2931 2932 2933 2934 2935 2936 2937
If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for
<code>(*a)[low : high]</code>.
</p>

<p>
For arrays or strings, the indices are <i>in range</i> if
<code>0</code> &lt;= <code>low</code> &lt;= <code>high</code> &lt;= <code>len(a)</code>,
2938 2939
otherwise they are <i>out of range</i>.
For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length.
2940
A <a href="#Constants">constant</a> index must be non-negative and representable by a value of type
2941
<code>int</code>; for arrays or constant strings, constant indices must also be in range.
2942 2943
If both indices are constant, they must satisfy <code>low &lt;= high</code>.
If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
2944 2945
</p>

2946
<p>
2947 2948 2949
Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice,
the result of the slice operation is a non-constant value of the same type as the operand.
For untyped string operands the result is a non-constant value of type <code>string</code>.
2950 2951
If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>
and the result of the slice operation is a slice with the same element type as the array.
Rob Pike's avatar
Rob Pike committed
2952
</p>
2953

2954 2955
<p>
If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result
2956 2957
is a <code>nil</code> slice. Otherwise, the result shares its underlying array with the
operand.
2958
</p>
2959

Robert Griesemer's avatar
Robert Griesemer committed
2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000
<h4>Full slice expressions</h4>

<p>
For an array, pointer to array, or slice <code>a</code> (but not a string), the primary expression
</p>

<pre>
a[low : high : max]
</pre>

<p>
constructs a slice of the same type, and with the same length and elements as the simple slice
expression <code>a[low : high]</code>. Additionally, it controls the resulting slice's capacity
by setting it to <code>max - low</code>. Only the first index may be omitted; it defaults to 0.
After slicing the array <code>a</code>
</p>

<pre>
a := [5]int{1, 2, 3, 4, 5}
t := a[1:3:5]
</pre>

<p>
the slice <code>t</code> has type <code>[]int</code>, length 2, capacity 4, and elements
</p>

<pre>
t[0] == 2
t[1] == 3
</pre>

<p>
As for simple slice expressions, if <code>a</code> is a pointer to an array,
<code>a[low : high : max]</code> is shorthand for <code>(*a)[low : high : max]</code>.
If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>.
</p>

<p>
The indices are <i>in range</i> if <code>0 &lt;= low &lt;= high &lt;= max &lt;= cap(a)</code>,
otherwise they are <i>out of range</i>.
A <a href="#Constants">constant</a> index must be non-negative and representable by a value of type
3001
<code>int</code>; for arrays, constant indices must also be in range.
Robert Griesemer's avatar
Robert Griesemer committed
3002 3003 3004 3005 3006
If multiple indices are constant, the constants that are present must be in range relative to each
other.
If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
</p>

3007
<h3 id="Type_assertions">Type assertions</h3>
3008

Rob Pike's avatar
Rob Pike committed
3009
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3010 3011
For an expression <code>x</code> of <a href="#Interface_types">interface type</a>
and a type <code>T</code>, the primary expression
Rob Pike's avatar
Rob Pike committed
3012
</p>
3013

3014 3015 3016
<pre>
x.(T)
</pre>
3017

3018
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3019
asserts that <code>x</code> is not <code>nil</code>
Russ Cox's avatar
Russ Cox committed
3020
and that the value stored in <code>x</code> is of type <code>T</code>.
3021
The notation <code>x.(T)</code> is called a <i>type assertion</i>.
Rob Pike's avatar
Rob Pike committed
3022 3023
</p>
<p>
3024
More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
3025 3026
that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a>
to the type <code>T</code>.
3027 3028 3029
In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>;
otherwise the type assertion is invalid since it is not possible for <code>x</code>
to store a value of type <code>T</code>.
3030
If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
3031
of <code>x</code> implements the interface <code>T</code>.
Rob Pike's avatar
Rob Pike committed
3032
</p>
3033
<p>
3034
If the type assertion holds, the value of the expression is the value
Rob Pike's avatar
Rob Pike committed
3035 3036 3037
stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false,
a <a href="#Run_time_panics">run-time panic</a> occurs.
In other words, even though the dynamic type of <code>x</code>
3038
is known only at run time, the type of <code>x.(T)</code> is
Rob Pike's avatar
Rob Pike committed
3039 3040
known to be <code>T</code> in a correct program.
</p>
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051

<pre>
var x interface{} = 7  // x has dynamic type int and value 7
i := x.(int)           // i has type int and value 7

type I interface { m() }
var y I
s := y.(string)        // illegal: string does not implement I (missing method m)
r := y.(io.Reader)     // r has type io.Reader and y must implement both I and io.Reader
</pre>

3052
<p>
3053
A type assertion used in an <a href="#Assignments">assignment</a> or initialization of the special form
Rob Pike's avatar
Rob Pike committed
3054
</p>
3055

3056 3057 3058
<pre>
v, ok = x.(T)
v, ok := x.(T)
Rob Pike's avatar
Rob Pike committed
3059
var v, ok = x.(T)
3060
</pre>
3061

3062
<p>
3063 3064 3065
yields an additional untyped boolean value. The value of <code>ok</code> is <code>true</code>
if the assertion holds. Otherwise it is <code>false</code> and the value of <code>v</code> is
the <a href="#The_zero_value">zero value</a> for type <code>T</code>.
Rob Pike's avatar
Rob Pike committed
3066
No run-time panic occurs in this case.
Rob Pike's avatar
Rob Pike committed
3067
</p>
3068

3069

3070
<h3 id="Calls">Calls</h3>
3071

3072
<p>
Rob Pike's avatar
Rob Pike committed
3073 3074
Given an expression <code>f</code> of function type
<code>F</code>,
Rob Pike's avatar
Rob Pike committed
3075
</p>
3076

3077
<pre>
3078
f(a1, a2, … an)
3079
</pre>
3080

3081
<p>
3082
calls <code>f</code> with arguments <code>a1, a2, … an</code>.
3083
Except for one special case, arguments must be single-valued expressions
3084
<a href="#Assignability">assignable</a> to the parameter types of
Rob Pike's avatar
Rob Pike committed
3085 3086 3087 3088 3089 3090 3091
<code>F</code> and are evaluated before the function is called.
The type of the expression is the result type
of <code>F</code>.
A method invocation is similar but the method itself
is specified as a selector upon a value of the receiver type for
the method.
</p>
3092

3093
<pre>
3094
math.Atan2(x, y)  // function call
3095
var pt *Point
Rob Pike's avatar
Rob Pike committed
3096
pt.Scale(3.5)  // method call with receiver pt
3097
</pre>
3098

3099 3100 3101 3102 3103 3104 3105 3106 3107 3108
<p>
In a function call, the function value and arguments are evaluated in
<a href="#Order_of_evaluation">the usual order</a>.
After they are evaluated, the parameters of the call are passed by value to the function
and the called function begins execution.
The return parameters of the function are passed by value
back to the calling function when the function returns.
</p>

<p>
Hong Ruiqi's avatar
Hong Ruiqi committed
3109
Calling a <code>nil</code> function value
3110 3111 3112
causes a <a href="#Run_time_panics">run-time panic</a>.
</p>

3113
<p>
3114
As a special case, if the return values of a function or method
3115 3116
<code>g</code> are equal in number and individually
assignable to the parameters of another function or method
3117 3118 3119
<code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code>
will invoke <code>f</code> after binding the return values of
<code>g</code> to the parameters of <code>f</code> in order.  The call
3120 3121
of <code>f</code> must contain no parameters other than the call of <code>g</code>,
and <code>g</code> must have at least one return value.
3122 3123 3124 3125 3126 3127 3128
If <code>f</code> has a final <code>...</code> parameter, it is
assigned the return values of <code>g</code> that remain after
assignment of regular parameters.
</p>

<pre>
func Split(s string, pos int) (string, string) {
3129
	return s[0:pos], s[pos:]
3130 3131 3132 3133 3134 3135 3136
}

func Join(s, t string) string {
	return s + t
}

if Join(Split(value, len(value)/2)) != value {
3137
	log.Panic("test fails")
3138 3139 3140
}
</pre>

Rob Pike's avatar
Rob Pike committed
3141
<p>
3142 3143
A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a>
of (the type of) <code>x</code> contains <code>m</code> and the
3144
argument list can be assigned to the parameter list of <code>m</code>.
Rob Pike's avatar
Rob Pike committed
3145
If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&amp;x</code>'s method
Robert Griesemer's avatar
Robert Griesemer committed
3146 3147
set contains <code>m</code>, <code>x.m()</code> is shorthand
for <code>(&amp;x).m()</code>:
Rob Pike's avatar
Rob Pike committed
3148
</p>
3149

3150
<pre>
3151
var p Point
Rob Pike's avatar
Rob Pike committed
3152
p.Scale(3.5)
3153
</pre>
3154

3155
<p>
3156
There is no distinct method type and there are no method literals.
Rob Pike's avatar
Rob Pike committed
3157
</p>
3158

3159
<h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3>
3160

Rob Pike's avatar
Rob Pike committed
3161
<p>
3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172
If <code>f</code> is <a href="#Function_types">variadic</a> with a final
parameter <code>p</code> of type <code>...T</code>, then within <code>f</code>
the type of <code>p</code> is equivalent to type <code>[]T</code>.
If <code>f</code> is invoked with no actual arguments for <code>p</code>,
the value passed to <code>p</code> is <code>nil</code>.
Otherwise, the value passed is a new slice
of type <code>[]T</code> with a new underlying array whose successive elements
are the actual arguments, which all must be <a href="#Assignability">assignable</a>
to <code>T</code>. The length and capacity of the slice is therefore
the number of arguments bound to <code>p</code> and may differ for each
call site.
3173
</p>
3174

Rob Pike's avatar
Rob Pike committed
3175
<p>
3176
Given the function and calls
3177 3178
</p>
<pre>
3179
func Greeting(prefix string, who ...string)
3180
Greeting("nobody")
3181 3182 3183 3184
Greeting("hello:", "Joe", "Anna", "Eileen")
</pre>

<p>
Robert Griesemer's avatar
Robert Griesemer committed
3185
within <code>Greeting</code>, <code>who</code> will have the value
3186 3187
<code>nil</code> in the first call, and
<code>[]string{"Joe", "Anna", "Eileen"}</code> in the second.
3188 3189
</p>

Robert Griesemer's avatar
Robert Griesemer committed
3190
<p>
3191 3192 3193
If the final argument is assignable to a slice type <code>[]T</code>, it may be
passed unchanged as the value for a <code>...T</code> parameter if the argument
is followed by <code>...</code>. In this case no new slice is created.
Robert Griesemer's avatar
Robert Griesemer committed
3194
</p>
3195 3196

<p>
Robert Griesemer's avatar
Robert Griesemer committed
3197
Given the slice <code>s</code> and call
3198
</p>
3199

Robert Griesemer's avatar
Robert Griesemer committed
3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210
<pre>
s := []string{"James", "Jasmine"}
Greeting("goodbye:", s...)
</pre>

<p>
within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code>
with the same underlying array.
</p>


3211
<h3 id="Operators">Operators</h3>
3212

Rob Pike's avatar
Rob Pike committed
3213
<p>
3214
Operators combine operands into expressions.
Rob Pike's avatar
Rob Pike committed
3215
</p>
3216

3217
<pre class="ebnf">
3218
Expression = UnaryExpr | Expression binary_op UnaryExpr .
Rob Pike's avatar
Rob Pike committed
3219
UnaryExpr  = PrimaryExpr | unary_op UnaryExpr .
3220

3221
binary_op  = "||" | "&amp;&amp;" | rel_op | add_op | mul_op .
Rob Pike's avatar
Rob Pike committed
3222 3223
rel_op     = "==" | "!=" | "&lt;" | "&lt;=" | ">" | ">=" .
add_op     = "+" | "-" | "|" | "^" .
Robert Griesemer's avatar
Robert Griesemer committed
3224
mul_op     = "*" | "/" | "%" | "&lt;&lt;" | "&gt;&gt;" | "&amp;" | "&amp;^" .
3225

Rob Pike's avatar
Rob Pike committed
3226
unary_op   = "+" | "-" | "!" | "^" | "*" | "&amp;" | "&lt;-" .
3227
</pre>
3228

3229
<p>
3230
Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>.
3231
For other binary operators, the operand types must be <a href="#Type_identity">identical</a>
3232
unless the operation involves shifts or untyped <a href="#Constants">constants</a>.
3233 3234
For operations involving constants only, see the section on
<a href="#Constant_expressions">constant expressions</a>.
Rob Pike's avatar
Rob Pike committed
3235
</p>
3236

3237
<p>
3238
Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a>
3239 3240
and the other operand is not, the constant is <a href="#Conversions">converted</a>
to the type of the other operand.
3241
</p>
3242

3243
<p>
3244
The right operand in a shift expression must have unsigned integer type
3245
or be an untyped constant that can be converted to unsigned integer type.
3246 3247
If the left operand of a non-constant shift expression is an untyped constant,
the type of the constant is what it would be if the shift expression were
3248
replaced by its left operand alone.
3249
</p>
3250

3251
<pre>
3252
var s uint = 33
3253 3254 3255
var i = 1&lt;&lt;s           // 1 has type int
var j int32 = 1&lt;&lt;s     // 1 has type int32; j == 0
var k = uint64(1&lt;&lt;s)   // 1 has type uint64; k == 1&lt;&lt;33
Robert Griesemer's avatar
Robert Griesemer committed
3256
var m int = 1.0&lt;&lt;s     // 1.0 has type int
3257
var n = 1.0&lt;&lt;s != i    // 1.0 has type int; n == false if ints are 32bits in size
Robert Griesemer's avatar
Robert Griesemer committed
3258
var o = 1&lt;&lt;s == 2&lt;&lt;s   // 1 and 2 have type int; o == true if ints are 32bits in size
3259
var p = 1&lt;&lt;s == 1&lt;&lt;33  // illegal if ints are 32bits in size: 1 has type int, but 1&lt;&lt;33 overflows int
3260
var u = 1.0&lt;&lt;s         // illegal: 1.0 has type float64, cannot shift
3261 3262
var u1 = 1.0&lt;&lt;s != 0   // illegal: 1.0 has type float64, cannot shift
var u2 = 1&lt;&lt;s != 1.0   // illegal: 1 has type float64, cannot shift
3263
var v float32 = 1&lt;&lt;s   // illegal: 1 has type float32, cannot shift
Robert Griesemer's avatar
Robert Griesemer committed
3264
var w int64 = 1.0&lt;&lt;33  // 1.0&lt;&lt;33 is a constant shift expression
3265
</pre>
3266

3267
<h3 id="Operator_precedence">Operator precedence</h3>
3268
<p>
Russ Cox's avatar
Russ Cox committed
3269 3270
Unary operators have the highest precedence.
As the  <code>++</code> and <code>--</code> operators form
Rob Pike's avatar
Rob Pike committed
3271
statements, not expressions, they fall
Russ Cox's avatar
Russ Cox committed
3272
outside the operator hierarchy.
Rob Pike's avatar
Rob Pike committed
3273 3274
As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>.
<p>
3275
There are five precedence levels for binary operators.
Rob Pike's avatar
Rob Pike committed
3276
Multiplication operators bind strongest, followed by addition
3277 3278
operators, comparison operators, <code>&amp;&amp;</code> (logical AND),
and finally <code>||</code> (logical OR):
Rob Pike's avatar
Rob Pike committed
3279
</p>
3280

Rob Pike's avatar
Rob Pike committed
3281
<pre class="grammar">
3282
Precedence    Operator
3283 3284
    5             *  /  %  &lt;&lt;  &gt;&gt;  &amp;  &amp;^
    4             +  -  |  ^
3285
    3             ==  !=  &lt;  &lt;=  &gt;  &gt;=
3286 3287 3288
    2             &amp;&amp;
    1             ||
</pre>
3289

Rob Pike's avatar
Rob Pike committed
3290
<p>
3291
Binary operators of the same precedence associate from left to right.
3292
For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>.
Rob Pike's avatar
Rob Pike committed
3293
</p>
3294

3295 3296 3297 3298
<pre>
+x
23 + 3*x[i]
x &lt;= f()
Robert Griesemer's avatar
Robert Griesemer committed
3299
^a &gt;&gt; b
3300
f() || g()
3301
x == y+1 &amp;&amp; &lt;-chanPtr &gt; 0
3302
</pre>
3303 3304


3305
<h3 id="Arithmetic_operators">Arithmetic operators</h3>
3306
<p>
3307
Arithmetic operators apply to numeric values and yield a result of the same
Rob Pike's avatar
Rob Pike committed
3308
type as the first operand. The four standard arithmetic operators (<code>+</code>,
Rob Pike's avatar
Rob Pike committed
3309 3310
<code>-</code>,  <code>*</code>, <code>/</code>) apply to integer,
floating-point, and complex types; <code>+</code> also applies
3311
to strings. All other arithmetic operators apply to integers only.
Rob Pike's avatar
Rob Pike committed
3312
</p>
3313

Rob Pike's avatar
Rob Pike committed
3314
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
3315 3316 3317 3318
+    sum                    integers, floats, complex values, strings
-    difference             integers, floats, complex values
*    product                integers, floats, complex values
/    quotient               integers, floats, complex values
3319
%    remainder              integers
3320

3321 3322 3323 3324
&amp;    bitwise AND            integers
|    bitwise OR             integers
^    bitwise XOR            integers
&amp;^   bit clear (AND NOT)    integers
3325

Robert Griesemer's avatar
Robert Griesemer committed
3326 3327
&lt;&lt;   left shift             integer &lt;&lt; unsigned integer
&gt;&gt;   right shift            integer &gt;&gt; unsigned integer
3328
</pre>
3329

Rob Pike's avatar
Rob Pike committed
3330 3331 3332 3333
<p>
Strings can be concatenated using the <code>+</code> operator
or the <code>+=</code> assignment operator:
</p>
3334

3335
<pre>
3336 3337
s := "hi" + string(c)
s += " and good bye"
3338
</pre>
3339

3340
<p>
Rob Pike's avatar
Rob Pike committed
3341 3342 3343
String addition creates a new string by concatenating the operands.
</p>
<p>
3344 3345 3346
For two integer values <code>x</code> and <code>y</code>, the integer quotient
<code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following
relationships:
Rob Pike's avatar
Rob Pike committed
3347
</p>
3348

3349
<pre>
3350
x = q*y + r  and  |r| &lt; |y|
3351
</pre>
3352

Rob Pike's avatar
Rob Pike committed
3353
<p>
3354 3355
with <code>x / y</code> truncated towards zero
(<a href="http://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>).
Rob Pike's avatar
Rob Pike committed
3356
</p>
3357

3358 3359 3360 3361 3362 3363 3364
<pre>
 x     y     x / y     x % y
 5     3       1         2
-5     3      -1        -2
 5    -3      -1         2
-5    -3       1        -2
</pre>
3365

3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379
<p>
As an exception to this rule, if the dividend <code>x</code> is the most
negative value for the int type of <code>x</code>, the quotient
<code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>).
</p>

<pre>
			 x, q
int8                     -128
int16                  -32768
int32             -2147483648
int64    -9223372036854775808
</pre>

Rob Pike's avatar
Rob Pike committed
3380
<p>
3381 3382
If the divisor is a <a href="#Constants">constant</a>, it must not be zero.
If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3383
If the dividend is non-negative and the divisor is a constant power of 2,
3384
the division may be replaced by a right shift, and computing the remainder may
3385
be replaced by a bitwise AND operation:
Rob Pike's avatar
Rob Pike committed
3386
</p>
3387

3388
<pre>
Robert Griesemer's avatar
Robert Griesemer committed
3389
 x     x / 4     x % 4     x &gt;&gt; 2     x &amp; 3
3390 3391 3392
 11      2         3         2          3
-11     -2        -3        -3          1
</pre>
3393

Rob Pike's avatar
Rob Pike committed
3394
<p>
3395 3396
The shift operators shift the left operand by the shift count specified by the
right operand. They implement arithmetic shifts if the left operand is a signed
3397 3398
integer and logical shifts if it is an unsigned integer.
There is no upper limit on the shift count. Shifts behave
Rob Pike's avatar
Rob Pike committed
3399 3400
as if the left operand is shifted <code>n</code> times by 1 for a shift
count of <code>n</code>.
Robert Griesemer's avatar
Robert Griesemer committed
3401 3402
As a result, <code>x &lt;&lt; 1</code> is the same as <code>x*2</code>
and <code>x &gt;&gt; 1</code> is the same as
Robert Griesemer's avatar
Robert Griesemer committed
3403
<code>x/2</code> but truncated towards negative infinity.
Rob Pike's avatar
Rob Pike committed
3404
</p>
3405

Rob Pike's avatar
Rob Pike committed
3406 3407 3408
<p>
For integer operands, the unary operators
<code>+</code>, <code>-</code>, and <code>^</code> are defined as
Robert Griesemer's avatar
Robert Griesemer committed
3409
follows:
Rob Pike's avatar
Rob Pike committed
3410
</p>
3411

Rob Pike's avatar
Rob Pike committed
3412
<pre class="grammar">
3413 3414
+x                          is 0 + x
-x    negation              is 0 - x
Russ Cox's avatar
Russ Cox committed
3415 3416
^x    bitwise complement    is m ^ x  with m = "all bits set to 1" for unsigned x
                                      and  m = -1 for signed x
3417
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3418

3419
<p>
3420
For floating-point and complex numbers,
3421 3422
<code>+x</code> is the same as <code>x</code>,
while <code>-x</code> is the negation of <code>x</code>.
3423
The result of a floating-point or complex division by zero is not specified beyond the
3424 3425
IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a>
occurs is implementation-specific.
3426
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3427

3428
<h3 id="Integer_overflow">Integer overflow</h3>
Robert Griesemer's avatar
Robert Griesemer committed
3429

Rob Pike's avatar
Rob Pike committed
3430 3431 3432 3433
<p>
For unsigned integer values, the operations <code>+</code>,
<code>-</code>, <code>*</code>, and <code>&lt;&lt;</code> are
computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of
3434 3435
the <a href="#Numeric_types">unsigned integer</a>'s type.
Loosely speaking, these unsigned integer operations
Robert Griesemer's avatar
Robert Griesemer committed
3436
discard high bits upon overflow, and programs may rely on ``wrap around''.
Rob Pike's avatar
Rob Pike committed
3437
</p>
3438
<p>
Rob Pike's avatar
Rob Pike committed
3439 3440
For signed integers, the operations <code>+</code>,
<code>-</code>, <code>*</code>, and <code>&lt;&lt;</code> may legally
Robert Griesemer's avatar
Robert Griesemer committed
3441 3442
overflow and the resulting value exists and is deterministically defined
by the signed integer representation, the operation, and its operands.
Rob Pike's avatar
Rob Pike committed
3443
No exception is raised as a result of overflow. A
Robert Griesemer's avatar
Robert Griesemer committed
3444
compiler may not optimize code under the assumption that overflow does
Rob Pike's avatar
Rob Pike committed
3445 3446
not occur. For instance, it may not assume that <code>x &lt; x + 1</code> is always true.
</p>
3447 3448


3449
<h3 id="Comparison_operators">Comparison operators</h3>
3450

Rob Pike's avatar
Rob Pike committed
3451
<p>
3452
Comparison operators compare two operands and yield an untyped boolean value.
Rob Pike's avatar
Rob Pike committed
3453
</p>
3454

Rob Pike's avatar
Rob Pike committed
3455
<pre class="grammar">
3456 3457
==    equal
!=    not equal
Anthony Martin's avatar
Anthony Martin committed
3458 3459
&lt;     less
&lt;=    less or equal
3460 3461
&gt;     greater
&gt;=    greater or equal
3462
</pre>
3463

Rob Pike's avatar
Rob Pike committed
3464
<p>
3465
In any comparison, the first operand
3466 3467
must be <a href="#Assignability">assignable</a>
to the type of the second operand, or vice versa.
Rob Pike's avatar
Rob Pike committed
3468
</p>
3469
<p>
3470 3471 3472 3473 3474
The equality operators <code>==</code> and <code>!=</code> apply
to operands that are <i>comparable</i>.
The ordering operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code>
apply to operands that are <i>ordered</i>.
These terms and the result of the comparisons are defined as follows:
Rob Pike's avatar
Rob Pike committed
3475
</p>
3476

3477 3478
<ul>
	<li>
3479 3480 3481
	Boolean values are comparable.
	Two boolean values are equal if they are either both
	<code>true</code> or both <code>false</code>.
3482
	</li>
3483

3484
	<li>
3485
	Integer values are comparable and ordered, in the usual way.
3486
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3487

3488
	<li>
3489 3490
	Floating point values are comparable and ordered,
	as defined by the IEEE-754 standard.
3491
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3492

3493
	<li>
3494 3495 3496 3497
	Complex values are comparable.
	Two complex values <code>u</code> and <code>v</code> are
	equal if both <code>real(u) == real(v)</code> and
	<code>imag(u) == imag(v)</code>.
3498
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3499

3500
	<li>
3501
	String values are comparable and ordered, lexically byte-wise.
3502
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3503

3504
	<li>
3505
	Pointer values are comparable.
3506 3507
	Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>.
	Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal.
3508
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3509

3510
	<li>
3511
	Channel values are comparable.
3512 3513
	Two channel values are equal if they were created by the same call to
	<a href="#Making_slices_maps_and_channels"><code>make</code></a>
3514
	or if both have value <code>nil</code>.
3515
	</li>
3516

3517
	<li>
3518 3519 3520
	Interface values are comparable.
	Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types
	and equal dynamic values or if both have value <code>nil</code>.
3521
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3522

3523
	<li>
3524 3525 3526 3527 3528 3529
	A value <code>x</code> of non-interface type <code>X</code> and
	a value <code>t</code> of interface type <code>T</code> are comparable when values
	of type <code>X</code> are comparable and
	<code>X</code> implements <code>T</code>.
	They are equal if <code>t</code>'s dynamic type is identical to <code>X</code>
	and <code>t</code>'s dynamic value is equal to <code>x</code>.
3530
	</li>
3531

3532
	<li>
3533 3534 3535
	Struct values are comparable if all their fields are comparable.
	Two struct values are equal if their corresponding
	non-<a href="#Blank_identifier">blank</a> fields are equal.
3536
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3537

3538
	<li>
3539 3540
	Array values are comparable if values of the array element type are comparable.
	Two array values are equal if their corresponding elements are equal.
3541 3542 3543
	</li>
</ul>

3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558
<p>
A comparison of two interface values with identical dynamic types
causes a <a href="#Run_time_panics">run-time panic</a> if values
of that type are not comparable.  This behavior applies not only to direct interface
value comparisons but also when comparing arrays of interface values
or structs with interface-valued fields.
</p>

<p>
Slice, map, and function values are not comparable.
However, as a special case, a slice, map, or function value may
be compared to the predeclared identifier <code>nil</code>.
Comparison of pointer, channel, and interface values to <code>nil</code>
is also allowed and follows from the general rules above.
</p>
3559

3560
<pre>
Shenghou Ma's avatar
Shenghou Ma committed
3561
const c = 3 &lt; 4            // c is the untyped bool constant true
3562

3563
type MyBool bool
3564 3565
var x, y int
var (
3566 3567 3568 3569 3570
	// The result of a comparison is an untyped bool.
	// The usual assignment rules apply.
	b3        = x == y // b3 has type bool
	b4 bool   = x == y // b4 has type bool
	b5 MyBool = x == y // b5 has type MyBool
3571 3572 3573
)
</pre>

3574
<h3 id="Logical_operators">Logical operators</h3>
3575

Rob Pike's avatar
Rob Pike committed
3576
<p>
3577 3578
Logical operators apply to <a href="#Boolean_types">boolean</a> values
and yield a result of the same type as the operands.
3579
The right operand is evaluated conditionally.
Rob Pike's avatar
Rob Pike committed
3580
</p>
3581

Rob Pike's avatar
Rob Pike committed
3582
<pre class="grammar">
3583 3584 3585
&amp;&amp;    conditional AND    p &amp;&amp; q  is  "if p then q else false"
||    conditional OR     p || q  is  "if p then true else q"
!     NOT                !p      is  "not p"
3586
</pre>
3587 3588


3589
<h3 id="Address_operators">Address operators</h3>
3590

Rob Pike's avatar
Rob Pike committed
3591
<p>
3592 3593 3594
For an operand <code>x</code> of type <code>T</code>, the address operation
<code>&amp;x</code> generates a pointer of type <code>*T</code> to <code>x</code>.
The operand must be <i>addressable</i>,
3595
that is, either a variable, pointer indirection, or slice indexing
3596
operation; or a field selector of an addressable struct operand;
3597
or an array indexing operation of an addressable array.
3598
As an exception to the addressability requirement, <code>x</code> may also be a
3599
(possibly parenthesized)
3600
<a href="#Composite_literals">composite literal</a>.
3601
If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>,
3602
then the evaluation of <code>&amp;x</code> does too.
3603
</p>
Russ Cox's avatar
Russ Cox committed
3604

3605 3606 3607 3608
<p>
For an operand <code>x</code> of pointer type <code>*T</code>, the pointer
indirection <code>*x</code> denotes the value of type <code>T</code> pointed
to by <code>x</code>.
3609 3610
If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code>
will cause a <a href="#Run_time_panics">run-time panic</a>.
Rob Pike's avatar
Rob Pike committed
3611 3612 3613 3614 3615
</p>

<pre>
&amp;x
&amp;a[f(2)]
3616
&amp;Point{2, 3}
Rob Pike's avatar
Rob Pike committed
3617 3618
*p
*pf(x)
Russ Cox's avatar
Russ Cox committed
3619 3620 3621

var x *int = nil
*x   // causes a run-time panic
3622
&amp;*x  // causes a run-time panic
Rob Pike's avatar
Rob Pike committed
3623 3624
</pre>

Rob Pike's avatar
Rob Pike committed
3625

3626
<h3 id="Receive_operator">Receive operator</h3>
3627

Rob Pike's avatar
Rob Pike committed
3628
<p>
3629 3630
For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>,
the value of the receive operation <code>&lt;-ch</code> is the value received
3631 3632 3633
from the channel <code>ch</code>. The channel direction must permit receive operations,
and the type of the receive operation is the element type of the channel.
The expression blocks until a value is available.
3634
Receiving from a <code>nil</code> channel blocks forever.
3635
A receive operation on a <a href="#Close">closed</a> channel can always proceed
3636 3637
immediately, yielding the element type's <a href="#The_zero_value">zero value</a>
after any previously sent values have been received.
Rob Pike's avatar
Rob Pike committed
3638
</p>
3639

3640
<pre>
3641 3642 3643
v1 := &lt;-ch
v2 = &lt;-ch
f(&lt;-ch)
3644
&lt;-strobe  // wait until clock pulse and discard received value
3645
</pre>
3646

Rob Pike's avatar
Rob Pike committed
3647
<p>
3648
A receive expression used in an <a href="#Assignments">assignment</a> or initialization of the special form
Rob Pike's avatar
Rob Pike committed
3649
</p>
3650

3651
<pre>
3652 3653 3654
x, ok = &lt;-ch
x, ok := &lt;-ch
var x, ok = &lt;-ch
3655
</pre>
3656

Rob Pike's avatar
Rob Pike committed
3657
<p>
3658
yields an additional untyped boolean result reporting whether the
3659 3660 3661 3662
communication succeeded. The value of <code>ok</code> is <code>true</code>
if the value received was delivered by a successful send operation to the
channel, or <code>false</code> if it is a zero value generated because the
channel is closed and empty.
Rob Pike's avatar
Rob Pike committed
3663
</p>
3664

3665

3666 3667 3668 3669 3670 3671 3672 3673 3674
<h3 id="Conversions">Conversions</h3>

<p>
Conversions are expressions of the form <code>T(x)</code>
where <code>T</code> is a type and <code>x</code> is an expression
that can be converted to type <code>T</code>.
</p>

<pre class="ebnf">
3675
Conversion = Type "(" Expression [ "," ] ")" .
3676 3677 3678
</pre>

<p>
3679
If the type starts with the operator <code>*</code> or <code>&lt;-</code>,
3680 3681 3682
or if the type starts with the keyword <code>func</code>
and has no result list, it must be parenthesized when
necessary to avoid ambiguity:
3683 3684 3685 3686
</p>

<pre>
*Point(p)        // same as *(Point(p))
3687
(*Point)(p)      // p is converted to *Point
3688
&lt;-chan int(c)    // same as &lt;-(chan int(c))
3689
(&lt;-chan int)(c)  // c is converted to &lt;-chan int
3690
func()(x)        // function signature func() x
3691 3692 3693
(func())(x)      // x is converted to func()
(func() int)(x)  // x is converted to func() int
func() int(x)    // x is converted to func() int (unambiguous)
3694 3695 3696
</pre>

<p>
3697 3698 3699 3700 3701 3702 3703 3704 3705
A <a href="#Constants">constant</a> value <code>x</code> can be converted to
type <code>T</code> in any of these cases:
</p>

<ul>
	<li>
	<code>x</code> is representable by a value of type <code>T</code>.
	</li>
	<li>
3706 3707 3708 3709 3710 3711 3712 3713
	<code>x</code> is a floating-point constant,
	<code>T</code> is a floating-point type,
	and <code>x</code> is representable by a value
	of type <code>T</code> after rounding using
	IEEE 754 round-to-even rules.
	The constant <code>T(x)</code> is the rounded value.
	</li>
	<li>
3714 3715
	<code>x</code> is an integer constant and <code>T</code> is a
	<a href="#String_types">string type</a>.
3716 3717
	The <a href="#Conversions_to_and_from_a_string_type">same rule</a>
	as for non-constant <code>x</code> applies in this case.
3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728
	</li>
</ul>

<p>
Converting a constant yields a typed constant as result.
</p>

<pre>
uint(iota)               // iota value of type uint
float32(2.718281828)     // 2.718281828 of type float32
complex128(1)            // 1.0 + 0.0i of type complex128
3729
float32(0.49999999)      // 0.5 of type float32
3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741
string('x')              // "x" of type string
string(0x266c)           // "♬" of type string
MyString("foo" + "bar")  // "foobar" of type MyString
string([]byte{'a'})      // not a constant: []byte{'a'} is not a constant
(*int)(nil)              // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
int(1.2)                 // illegal: 1.2 cannot be represented as an int
string(65.0)             // illegal: 65.0 is not an integer constant
</pre>

<p>
A non-constant value <code>x</code> can be converted to type <code>T</code>
in any of these cases:
3742
</p>
3743

3744 3745
<ul>
	<li>
3746
	<code>x</code> is <a href="#Assignability">assignable</a>
3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764
	to <code>T</code>.
	</li>
	<li>
	<code>x</code>'s type and <code>T</code> have identical
	<a href="#Types">underlying types</a>.
	</li>
	<li>
	<code>x</code>'s type and <code>T</code> are unnamed pointer types
	and their pointer base types have identical underlying types.
	</li>
	<li>
	<code>x</code>'s type and <code>T</code> are both integer or floating
	point types.
	</li>
	<li>
	<code>x</code>'s type and <code>T</code> are both complex types.
	</li>
	<li>
3765 3766
	<code>x</code> is an integer or a slice of bytes or runes
	and <code>T</code> is a string type.
3767 3768
	</li>
	<li>
3769
	<code>x</code> is a string and <code>T</code> is a slice of bytes or runes.
3770 3771
	</li>
</ul>
3772 3773

<p>
3774 3775
Specific rules apply to (non-constant) conversions between numeric types or
to and from a string type.
3776 3777 3778 3779
These conversions may change the representation of <code>x</code>
and incur a run-time cost.
All other conversions only change the type but not the representation
of <code>x</code>.
3780 3781
</p>

3782 3783 3784 3785 3786 3787 3788
<p>
There is no linguistic mechanism to convert between pointers and integers.
The package <a href="#Package_unsafe"><code>unsafe</code></a>
implements this functionality under
restricted circumstances.
</p>

3789
<h4>Conversions between numeric types</h4>
3790 3791 3792 3793 3794

<p>
For the conversion of non-constant numeric values, the following rules apply:
</p>

3795
<ol>
3796
<li>
3797 3798 3799 3800 3801
When converting between integer types, if the value is a signed integer, it is
sign extended to implicit infinite precision; otherwise it is zero extended.
It is then truncated to fit in the result type's size.
For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>.
The conversion always yields a valid value; there is no indication of overflow.
3802 3803
</li>
<li>
3804 3805
When converting a floating-point number to an integer, the fraction is discarded
(truncation towards zero).
3806
</li>
Rob Pike's avatar
Rob Pike committed
3807
<li>
3808 3809
When converting an integer or floating-point number to a floating-point type,
or a complex number to another complex type, the result value is rounded
Rob Pike's avatar
Rob Pike committed
3810
to the precision specified by the destination type.
3811 3812 3813 3814
For instance, the value of a variable <code>x</code> of type <code>float32</code>
may be stored using additional precision beyond that of an IEEE-754 32-bit number,
but float32(x) represents the result of rounding <code>x</code>'s value to
32-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits
Evan Shaw's avatar
Evan Shaw committed
3815
of precision, but <code>float32(x + 0.1)</code> does not.
3816
</li>
3817 3818 3819
</ol>

<p>
3820
In all non-constant conversions involving floating-point or complex values,
Rob Pike's avatar
Rob Pike committed
3821
if the result type cannot represent the value the conversion
3822
succeeds but the result value is implementation-dependent.
3823 3824
</p>

3825
<h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4>
3826

3827
<ol>
3828
<li>
3829
Converting a signed or unsigned integer value to a string type yields a
3830 3831
string containing the UTF-8 representation of the integer. Values outside
the range of valid Unicode code points are converted to <code>"\uFFFD"</code>.
3832 3833

<pre>
3834
string('a')       // "a"
3835
string(-1)        // "\ufffd" == "\xef\xbf\xbd"
3836
string(0xf8)      // "\u00f8" == "ø" == "\xc3\xb8"
3837
type MyString string
3838
MyString(0x65e5)  // "\u65e5" == "日" == "\xe6\x97\xa5"
3839 3840 3841 3842
</pre>
</li>

<li>
3843
Converting a slice of bytes to a string type yields
3844
a string whose successive bytes are the elements of the slice.
3845 3846

<pre>
3847 3848 3849
string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'})   // "hellø"
string([]byte{})                                     // ""
string([]byte(nil))                                  // ""
3850 3851 3852

type MyBytes []byte
string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'})  // "hellø"
3853 3854
</pre>
</li>
3855

3856
<li>
3857
Converting a slice of runes to a string type yields
3858
a string that is the concatenation of the individual rune values
3859
converted to strings.
3860

3861
<pre>
3862 3863 3864
string([]rune{0x767d, 0x9d6c, 0x7fd4})   // "\u767d\u9d6c\u7fd4" == "白鵬翔"
string([]rune{})                         // ""
string([]rune(nil))                      // ""
3865 3866 3867

type MyRunes []rune
string(MyRunes{0x767d, 0x9d6c, 0x7fd4})  // "\u767d\u9d6c\u7fd4" == "白鵬翔"
3868
</pre>
3869 3870 3871
</li>

<li>
3872
Converting a value of a string type to a slice of bytes type
3873 3874 3875
yields a slice whose successive elements are the bytes of the string.

<pre>
3876
[]byte("hellø")   // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
3877 3878
[]byte("")        // []byte{}

3879
MyBytes("hellø")  // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
3880 3881
</pre>
</li>
3882

3883
<li>
3884 3885
Converting a value of a string type to a slice of runes type
yields a slice containing the individual Unicode code points of the string.
3886

3887
<pre>
3888
[]rune(MyString("白鵬翔"))  // []rune{0x767d, 0x9d6c, 0x7fd4}
3889 3890
[]rune("")                 // []rune{}

3891
MyRunes("白鵬翔")           // []rune{0x767d, 0x9d6c, 0x7fd4}
3892 3893
</pre>
</li>
3894
</ol>
3895 3896


3897
<h3 id="Constant_expressions">Constant expressions</h3>
Robert Griesemer's avatar
Robert Griesemer committed
3898

3899
<p>
3900
Constant expressions may contain only <a href="#Constants">constant</a>
3901
operands and are evaluated at compile time.
3902
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3903

3904
<p>
3905 3906
Untyped boolean, numeric, and string constants may be used as operands
wherever it is legal to use an operand of boolean, numeric, or string type,
3907 3908
respectively.
Except for shift operations, if the operands of a binary operation are
3909
different kinds of untyped constants, the operation and, for non-boolean operations, the result use
3910
the kind that appears later in this list: integer, rune, floating-point, complex.
3911 3912
For example, an untyped integer constant divided by an
untyped complex constant yields an untyped complex constant.
3913
</p>
3914 3915

<p>
3916
A constant <a href="#Comparison_operators">comparison</a> always yields
3917
an untyped boolean constant.  If the left operand of a constant
3918 3919
<a href="#Operators">shift expression</a> is an untyped constant, the
result is an integer constant; otherwise it is a constant of the same
3920 3921
type as the left operand, which must be of
<a href="#Numeric_types">integer type</a>.
3922
Applying all other operators to untyped constants results in an untyped
Rob Pike's avatar
Rob Pike committed
3923
constant of the same kind (that is, a boolean, integer, floating-point,
3924
complex, or string constant).
3925 3926
</p>

3927
<pre>
3928 3929 3930
const a = 2 + 3.0          // a == 5.0   (untyped floating-point constant)
const b = 15 / 4           // b == 3     (untyped integer constant)
const c = 15 / 4.0         // c == 3.75  (untyped floating-point constant)
3931 3932
const Θ float64 = 3/2      // Θ == 1.0   (type float64, 3/2 is integer division)
const Π float64 = 3/2.     // Π == 1.5   (type float64, 3/2. is float division)
3933 3934
const d = 1 &lt;&lt; 3.0         // d == 8     (untyped integer constant)
const e = 1.0 &lt;&lt; 3         // e == 8     (untyped integer constant)
Robert Griesemer's avatar
Robert Griesemer committed
3935
const f = int32(1) &lt;&lt; 33   // illegal    (constant 8589934592 overflows int32)
3936
const g = float64(2) &gt;&gt; 1  // illegal    (float64(2) is a typed floating-point constant)
3937 3938
const h = "foo" &gt; "bar"    // h == true  (untyped boolean constant)
const j = true             // j == true  (untyped boolean constant)
3939
const k = 'w' + 1          // k == 'x'   (untyped rune constant)
3940 3941
const l = "hi"             // l == "hi"  (untyped string constant)
const m = string(k)        // m == "x"   (type string)
3942
const Σ = 1 - 0.707i       //            (untyped complex constant)
3943 3944
const Δ = Σ + 2.0e-4       //            (untyped complex constant)
const Φ = iota*1i - 1/1i   //            (untyped complex constant)
3945 3946
</pre>

Rob Pike's avatar
Rob Pike committed
3947
<p>
3948
Applying the built-in function <code>complex</code> to untyped
3949
integer, rune, or floating-point constants yields
3950
an untyped complex constant.
Rob Pike's avatar
Rob Pike committed
3951 3952 3953
</p>

<pre>
3954
const ic = complex(0, c)   // ic == 3.75i  (untyped complex constant)
3955
const iΘ = complex(0, Θ)   // iΘ == 1i     (type complex128)
Rob Pike's avatar
Rob Pike committed
3956 3957
</pre>

3958
<p>
3959 3960 3961
Constant expressions are always evaluated exactly; intermediate values and the
constants themselves may require precision significantly larger than supported
by any predeclared type in the language. The following are legal declarations:
3962 3963 3964
</p>

<pre>
3965 3966
const Huge = 1 &lt;&lt; 100         // Huge == 1267650600228229401496703205376  (untyped integer constant)
const Four int8 = Huge &gt;&gt; 98  // Four == 4                                (type int8)
3967
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3968

3969 3970 3971 3972 3973 3974 3975 3976
<p>
The divisor of a constant division or remainder operation must not be zero:
</p>

<pre>
3.14 / 0.0   // illegal: division by zero
</pre>

3977
<p>
3978 3979
The values of <i>typed</i> constants must always be accurately representable as values
of the constant type. The following constant expressions are illegal:
3980 3981 3982
</p>

<pre>
3983 3984
uint(-1)     // -1 cannot be represented as a uint
int(3.14)    // 3.14 cannot be represented as an int
3985 3986 3987
int64(Huge)  // 1267650600228229401496703205376 cannot be represented as an int64
Four * 300   // operand 300 cannot be represented as an int8 (type of Four)
Four * 100   // product 400 cannot be represented as an int8 (type of Four)
3988 3989 3990
</pre>

<p>
3991
The mask used by the unary bitwise complement operator <code>^</code> matches
Rob Pike's avatar
Rob Pike committed
3992
the rule for non-constants: the mask is all 1s for unsigned constants
3993
and -1 for signed and untyped constants.
3994 3995 3996
</p>

<pre>
3997
^1         // untyped integer constant, equal to -2
3998
uint8(^1)  // illegal: same as uint8(-2), -2 cannot be represented as a uint8
3999 4000 4001
^uint8(1)  // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)
int8(^1)   // same as int8(-2)
^int8(1)   // same as -1 ^ int8(1) = -2
4002 4003
</pre>

4004 4005 4006 4007 4008 4009 4010 4011 4012 4013
<p>
Implementation restriction: A compiler may use rounding while
computing untyped floating-point or complex constant expressions; see
the implementation restriction in the section
on <a href="#Constants">constants</a>.  This rounding may cause a
floating-point constant expression to be invalid in an integer
context, even if it would be integral when calculated using infinite
precision.
</p>

4014

4015
<h3 id="Order_of_evaluation">Order of evaluation</h3>
4016 4017

<p>
4018
At package level, <a href="#Package_initialization">initialization dependencies</a>
4019 4020 4021 4022
determine the evaluation order of individual initialization expressions in
<a href="#Variable_declarations">variable declarations</a>.
Otherwise, when evaluating the <a href="#Operands">operands</a> of an
expression, assignment, or
4023 4024
<a href="#Return_statements">return statement</a>,
all function calls, method calls, and
4025
communication operations are evaluated in lexical left-to-right
4026 4027 4028
order.
</p>

4029
<p>
4030
For example, in the (function-local) assignment
4031 4032
</p>
<pre>
4033
y[f()], ok = g(h(), i()+x[j()], &lt;-c), k()
4034 4035
</pre>
<p>
4036 4037
the function calls and communication happen in the order
<code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>,
4038
<code>&lt;-c</code>, <code>g()</code>, and <code>k()</code>.
4039 4040 4041
However, the order of those events compared to the evaluation
and indexing of <code>x</code> and the evaluation
of <code>y</code> is not specified.
4042 4043
</p>

4044 4045
<pre>
a := 1
4046
f := func() int { a++; return a }
4047 4048 4049
x := []int{a, f()}            // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified
m := map[int]int{a: 1, a: 2}  // m may be {2: 1} or {2: 2}: evaluation order between the two map assignments is not specified
n := map[int]int{a: f()}      // n may be {2: 3} or {3: 3}: evaluation order between the key and the value is not specified
4050 4051
</pre>

4052 4053 4054
<p>
At package level, initialization dependencies override the left-to-right rule
for individual initialization expressions, but not for operands within each
4055
expression:
4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073
</p>

<pre>
var a, b, c = f() + v(), g(), sqr(u()) + v()

func f() int        { return c }
func g() int        { return a }
func sqr(x int) int { return x*x }

// functions u and v are independent of all other variables and functions
</pre>

<p>
The function calls happen in the order
<code>u()</code>, <code>sqr()</code>, <code>v()</code>,
<code>f()</code>, <code>v()</code>, and <code>g()</code>.
</p>

4074 4075 4076 4077 4078 4079 4080 4081
<p>
Floating-point operations within a single expression are evaluated according to
the associativity of the operators.  Explicit parentheses affect the evaluation
by overriding the default associativity.
In the expression <code>x + (y + z)</code> the addition <code>y + z</code>
is performed before adding <code>x</code>.
</p>

4082
<h2 id="Statements">Statements</h2>
4083

Rob Pike's avatar
Rob Pike committed
4084
<p>
4085
Statements control execution.
Rob Pike's avatar
Rob Pike committed
4086
</p>
4087

4088
<pre class="ebnf">
4089
Statement =
4090 4091
	Declaration | LabeledStmt | SimpleStmt |
	GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
4092 4093
	FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
	DeferStmt .
Robert Griesemer's avatar
Robert Griesemer committed
4094

4095
SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
4096
</pre>
4097

4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
<h3 id="Terminating_statements">Terminating statements</h3>

<p>
A terminating statement is one of the following:
</p>

<ol>
<li>
	A <a href="#Return_statements">"return"</a> or
    	<a href="#Goto_statements">"goto"</a> statement.
	<!-- ul below only for regular layout -->
	<ul> </ul>
</li>

<li>
	A call to the built-in function
	<a href="#Handling_panics"><code>panic</code></a>.
	<!-- ul below only for regular layout -->
	<ul> </ul>
</li>

<li>
	A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement.
	<!-- ul below only for regular layout -->
	<ul> </ul>
</li>

<li>
	An <a href="#If_statements">"if" statement</a> in which:
	<ul>
	<li>the "else" branch is present, and</li>
	<li>both branches are terminating statements.</li>
	</ul>
</li>

<li>
	A <a href="#For_statements">"for" statement</a> in which:
	<ul>
	<li>there are no "break" statements referring to the "for" statement, and</li>
	<li>the loop condition is absent.</li>
	</ul>
</li>

<li>
	A <a href="#Switch_statements">"switch" statement</a> in which:
	<ul>
	<li>there are no "break" statements referring to the "switch" statement,</li>
	<li>there is a default case, and</li>
	<li>the statement lists in each case, including the default, end in a terminating
	    statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough"
	    statement</a>.</li>
	</ul>
</li>

<li>
	A <a href="#Select_statements">"select" statement</a> in which:
	<ul>
	<li>there are no "break" statements referring to the "select" statement, and</li>
	<li>the statement lists in each case, including the default if present,
	    end in a terminating statement.</li>
	</ul>
</li>

<li>
	A <a href="#Labeled_statements">labeled statement</a> labeling
	a terminating statement.
</li>
</ol>

<p>
All other statements are not terminating.
</p>

<p>
A <a href="#Blocks">statement list</a> ends in a terminating statement if the list
is not empty and its final statement is terminating.
</p>

4176

4177
<h3 id="Empty_statements">Empty statements</h3>
4178

Rob Pike's avatar
Rob Pike committed
4179
<p>
4180
The empty statement does nothing.
Rob Pike's avatar
Rob Pike committed
4181
</p>
4182

4183
<pre class="ebnf">
4184
EmptyStmt = .
4185
</pre>
4186 4187


4188
<h3 id="Labeled_statements">Labeled statements</h3>
4189 4190 4191 4192 4193 4194

<p>
A labeled statement may be the target of a <code>goto</code>,
<code>break</code> or <code>continue</code> statement.
</p>

4195
<pre class="ebnf">
4196
LabeledStmt = Label ":" Statement .
4197 4198 4199 4200
Label       = identifier .
</pre>

<pre>
4201
Error: log.Panic("error encountered")
4202 4203 4204
</pre>


4205
<h3 id="Expression_statements">Expression statements</h3>
4206

Rob Pike's avatar
Rob Pike committed
4207
<p>
4208 4209 4210
With the exception of specific built-in functions,
function and method <a href="#Calls">calls</a> and
<a href="#Receive_operator">receive operations</a>
4211
can appear in statement context. Such statements may be parenthesized.
Rob Pike's avatar
Rob Pike committed
4212 4213
</p>

4214
<pre class="ebnf">
4215
ExpressionStmt = Expression .
4216
</pre>
4217

4218 4219 4220 4221 4222 4223 4224 4225 4226
<p>
The following built-in functions are not permitted in statement context:
</p>

<pre>
append cap complex imag len make new real
unsafe.Alignof unsafe.Offsetof unsafe.Sizeof
</pre>

4227
<pre>
4228 4229
h(x+y)
f.Close()
4230
&lt;-ch
4231
(&lt;-ch)
4232
len("foo")  // illegal if len is the built-in function
4233
</pre>
4234 4235


4236 4237 4238 4239
<h3 id="Send_statements">Send statements</h3>

<p>
A send statement sends a value on a channel.
4240 4241 4242
The channel expression must be of <a href="#Channel_types">channel type</a>,
the channel direction must permit send operations,
and the type of the value to be sent must be <a href="#Assignability">assignable</a>
4243 4244 4245 4246 4247 4248 4249 4250 4251 4252
to the channel's element type.
</p>

<pre class="ebnf">
SendStmt = Channel "&lt;-" Expression .
Channel  = Expression .
</pre>

<p>
Both the channel and the value expression are evaluated before communication
4253
begins. Communication blocks until the send can proceed.
4254 4255
A send on an unbuffered channel can proceed if a receiver is ready.
A send on a buffered channel can proceed if there is room in the buffer.
4256
A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>.
4257
A send on a <code>nil</code> channel blocks forever.
4258 4259 4260
</p>

<pre>
4261
ch &lt;- 3  // send value 3 to channel ch
4262 4263 4264
</pre>


4265
<h3 id="IncDec_statements">IncDec statements</h3>
4266

Rob Pike's avatar
Rob Pike committed
4267
<p>
4268
The "++" and "--" statements increment or decrement their operands
4269
by the untyped <a href="#Constants">constant</a> <code>1</code>.
4270 4271
As with an assignment, the operand must be <a href="#Address_operators">addressable</a>
or a map index expression.
Rob Pike's avatar
Rob Pike committed
4272
</p>
4273

4274
<pre class="ebnf">
4275
IncDecStmt = Expression ( "++" | "--" ) .
4276
</pre>
4277

Rob Pike's avatar
Rob Pike committed
4278
<p>
Robert Griesemer's avatar
Robert Griesemer committed
4279
The following <a href="#Assignments">assignment statements</a> are semantically
4280
equivalent:
Rob Pike's avatar
Rob Pike committed
4281
</p>
4282

Rob Pike's avatar
Rob Pike committed
4283
<pre class="grammar">
4284 4285 4286 4287
IncDec statement    Assignment
x++                 x += 1
x--                 x -= 1
</pre>
4288

4289

4290
<h3 id="Assignments">Assignments</h3>
4291

4292
<pre class="ebnf">
4293
Assignment = ExpressionList assign_op ExpressionList .
Rob Pike's avatar
Rob Pike committed
4294

4295 4296
assign_op = [ add_op | mul_op ] "=" .
</pre>
4297

Rob Pike's avatar
Rob Pike committed
4298
<p>
Rob Pike's avatar
Rob Pike committed
4299
Each left-hand side operand must be <a href="#Address_operators">addressable</a>,
4300 4301
a map index expression, or (for <code>=</code> assignments only) the
<a href="#Blank_identifier">blank identifier</a>.
4302
Operands may be parenthesized.
Rob Pike's avatar
Rob Pike committed
4303
</p>
4304

4305 4306 4307 4308
<pre>
x = 1
*p = f()
a[i] = 23
4309
(k) = &lt;-ch  // same as: k = &lt;-ch
4310
</pre>
4311

Rob Pike's avatar
Rob Pike committed
4312 4313
<p>
An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code>
4314
<code>y</code> where <i>op</i> is a binary arithmetic operation equivalent
Rob Pike's avatar
Rob Pike committed
4315
to <code>x</code> <code>=</code> <code>x</code> <i>op</i>
4316
<code>y</code> but evaluates <code>x</code>
Rob Pike's avatar
Rob Pike committed
4317
only once.  The <i>op</i><code>=</code> construct is a single token.
Rob Pike's avatar
Rob Pike committed
4318
In assignment operations, both the left- and right-hand expression lists
4319 4320
must contain exactly one single-valued expression, and the left-hand
expression must not be the blank identifier.
Rob Pike's avatar
Rob Pike committed
4321
</p>
4322

4323
<pre>
Robert Griesemer's avatar
Robert Griesemer committed
4324
a[i] &lt;&lt;= 2
Rob Pike's avatar
Rob Pike committed
4325
i &amp;^= 1&lt;&lt;n
4326
</pre>
4327

Rob Pike's avatar
Rob Pike committed
4328 4329 4330 4331
<p>
A tuple assignment assigns the individual elements of a multi-valued
operation to a list of variables.  There are two forms.  In the
first, the right hand operand is a single multi-valued expression
Robert Griesemer's avatar
Robert Griesemer committed
4332 4333
such as a function evaluation or <a href="#Channel_types">channel</a> or
<a href="#Map_types">map</a> operation or a <a href="#Type_assertions">type assertion</a>.
4334
The number of operands on the left
Robert Griesemer's avatar
Robert Griesemer committed
4335
hand side must match the number of values.  For instance, if
Rob Pike's avatar
Rob Pike committed
4336 4337
<code>f</code> is a function returning two values,
</p>
4338

4339 4340 4341
<pre>
x, y = f()
</pre>
4342

Rob Pike's avatar
Rob Pike committed
4343 4344
<p>
assigns the first value to <code>x</code> and the second to <code>y</code>.
4345 4346 4347 4348
In the second form, the number of operands on the left must equal the number
of expressions on the right, each of which must be single-valued, and the
<i>n</i>th expression on the right is assigned to the <i>n</i>th
operand on the left:
Rob Pike's avatar
Rob Pike committed
4349
</p>
4350

Robert Griesemer's avatar
Robert Griesemer committed
4351
<pre>
4352
one, two, three = '一', '二', '三'
Robert Griesemer's avatar
Robert Griesemer committed
4353 4354
</pre>

Rob Pike's avatar
Rob Pike committed
4355
<p>
4356 4357
The <a href="#Blank_identifier">blank identifier</a> provides a way to
ignore right-hand side values in an assignment:
4358 4359
</p>

4360 4361 4362 4363 4364
<pre>
_ = x       // evaluate x but ignore it
x, _ = f()  // evaluate f() but ignore second result value
</pre>

4365 4366
<p>
The assignment proceeds in two phases.
4367
First, the operands of <a href="#Index_expressions">index expressions</a>
4368 4369 4370 4371 4372
and <a href="#Address_operators">pointer indirections</a>
(including implicit pointer indirections in <a href="#Selectors">selectors</a>)
on the left and the expressions on the right are all
<a href="#Order_of_evaluation">evaluated in the usual order</a>.
Second, the assignments are carried out in left-to-right order.
Rob Pike's avatar
Rob Pike committed
4373
</p>
4374

4375
<pre>
Rob Pike's avatar
Rob Pike committed
4376
a, b = b, a  // exchange a and b
4377 4378 4379

x := []int{1, 2, 3}
i := 0
4380
i, x[i] = 1, 2  // set i = 1, x[0] = 2
4381 4382 4383 4384

i = 0
x[i], i = 2, 1  // set x[0] = 2, i = 1

4385
x[0], x[0] = 1, 2  // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end)
4386

4387
x[1], x[3] = 4, 5  // set x[1] = 4, then panic setting x[3] = 5.
4388 4389 4390 4391

type Point struct { x, y int }
var p *Point
x[2], p.x = 6, 7  // set x[2] = 6, then panic setting p.x = 7
4392 4393 4394 4395 4396 4397 4398

i = 2
x = []int{3, 5, 7}
for i, x[i] = range x {  // set i, x[2] = 0, x[0]
	break
}
// after this loop, i == 0 and x == []int{3, 5, 3}
4399
</pre>
Rob Pike's avatar
Rob Pike committed
4400 4401

<p>
4402 4403
In assignments, each value must be <a href="#Assignability">assignable</a>
to the type of the operand to which it is assigned, with the following special cases:
Rob Pike's avatar
Rob Pike committed
4404
</p>
4405

4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424
<ol>
<li><p>
	If an untyped <a href="#Constants">constant</a>
	is assigned to a variable of interface type or the blank identifier,
	the constant is first <a href="#Conversions">converted</a> to type
	<code>bool</code>, <code>rune</code>, <code>int</code>, <code>float64</code>,
	<code>complex128</code> or <code>string</code> respectively, depending on
	whether the value is a boolean, rune, integer, floating-point, complex, or
	string constant.
</p></li>

<li><p>
	<!-- Note that the result of a comparison is an untyped bool that may not be constant. -->
	If a left-hand side is the blank identifier, any typed or non-constant
	value except for the predeclared identifier
	<a href="#Predeclared_identifiers"><code>nil</code></a>
	may be assigned to it.
</p></li>
</ol>
4425

4426
<h3 id="If_statements">If statements</h3>
4427

Rob Pike's avatar
Rob Pike committed
4428 4429 4430 4431
<p>
"If" statements specify the conditional execution of two branches
according to the value of a boolean expression.  If the expression
evaluates to true, the "if" branch is executed, otherwise, if
4432
present, the "else" branch is executed.
Rob Pike's avatar
Rob Pike committed
4433
</p>
4434

4435
<pre class="ebnf">
Russ Cox's avatar
Russ Cox committed
4436
IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
4437
</pre>
4438

4439
<pre>
4440 4441
if x &gt; max {
	x = max
4442 4443
}
</pre>
4444

4445
<p>
Russ Cox's avatar
Russ Cox committed
4446 4447
The expression may be preceded by a simple statement, which
executes before the expression is evaluated.
4448
</p>
4449

4450
<pre>
4451 4452
if x := f(); x &lt; y {
	return x
4453
} else if x &gt; z {
4454
	return z
4455
} else {
4456
	return y
4457 4458
}
</pre>
4459 4460


4461
<h3 id="Switch_statements">Switch statements</h3>
4462

Rob Pike's avatar
Rob Pike committed
4463 4464
<p>
"Switch" statements provide multi-way execution.
Rob Pike's avatar
Rob Pike committed
4465 4466 4467
An expression or type specifier is compared to the "cases"
inside the "switch" to determine which branch
to execute.
Rob Pike's avatar
Rob Pike committed
4468
</p>
4469

4470
<pre class="ebnf">
4471
SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4472 4473
</pre>

Rob Pike's avatar
Rob Pike committed
4474
<p>
Rob Pike's avatar
Rob Pike committed
4475 4476 4477 4478 4479 4480 4481
There are two forms: expression switches and type switches.
In an expression switch, the cases contain expressions that are compared
against the value of the switch expression.
In a type switch, the cases contain types that are compared against the
type of a specially annotated switch expression.
</p>

4482
<h4 id="Expression_switches">Expression switches</h4>
Rob Pike's avatar
Rob Pike committed
4483 4484 4485 4486 4487

<p>
In an expression switch,
the switch expression is evaluated and
the case expressions, which need not be constants,
4488
are evaluated left-to-right and top-to-bottom; the first one that equals the
Rob Pike's avatar
Rob Pike committed
4489
switch expression
Rob Pike's avatar
Rob Pike committed
4490 4491
triggers execution of the statements of the associated case;
the other cases are skipped.
Rob Pike's avatar
Rob Pike committed
4492 4493
If no case matches and there is a "default" case,
its statements are executed.
Rob Pike's avatar
Rob Pike committed
4494 4495
There can be at most one default case and it may appear anywhere in the
"switch" statement.
4496 4497
A missing switch expression is equivalent to the boolean value
<code>true</code>.
Rob Pike's avatar
Rob Pike committed
4498
</p>
4499

4500
<pre class="ebnf">
4501
ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
4502
ExprCaseClause = ExprSwitchCase ":" StatementList .
4503
ExprSwitchCase = "case" ExpressionList | "default" .
4504 4505
</pre>

Rob Pike's avatar
Rob Pike committed
4506
<p>
4507 4508 4509
In a case or default clause, the last non-empty statement
may be a (possibly <a href="#Labeled_statements">labeled</a>)
<a href="#Fallthrough_statements">"fallthrough" statement</a> to
Rob Pike's avatar
Rob Pike committed
4510
indicate that control should flow from the end of this clause to
4511
the first statement of the next clause.
Rob Pike's avatar
Rob Pike committed
4512
Otherwise control flows to the end of the "switch" statement.
4513 4514
A "fallthrough" statement may appear as the last statement of all
but the last clause of an expression switch.
Rob Pike's avatar
Rob Pike committed
4515
</p>
Robert Griesemer's avatar
Robert Griesemer committed
4516

4517
<p>
Russ Cox's avatar
Russ Cox committed
4518 4519
The expression may be preceded by a simple statement, which
executes before the expression is evaluated.
Rob Pike's avatar
Rob Pike committed
4520
</p>
4521

4522 4523
<pre>
switch tag {
4524 4525 4526
default: s3()
case 0, 1, 2, 3: s1()
case 4, 5, 6, 7: s2()
4527
}
4528

4529
switch x := f(); {  // missing switch expression means "true"
4530 4531
case x &lt; 0: return -x
default: return x
4532
}
4533

Robert Griesemer's avatar
Robert Griesemer committed
4534
switch {
4535 4536 4537
case x &lt; y: f1()
case x &lt; z: f2()
case x == 4: f3()
4538 4539
}
</pre>
4540

4541
<h4 id="Type_switches">Type switches</h4>
Rob Pike's avatar
Rob Pike committed
4542 4543

<p>
4544
A type switch compares types rather than values. It is otherwise similar
Robert Griesemer's avatar
tweaks  
Robert Griesemer committed
4545
to an expression switch. It is marked by a special switch expression that
4546
has the form of a <a href="#Type_assertions">type assertion</a>
4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560
using the reserved word <code>type</code> rather than an actual type:
</p>

<pre>
switch x.(type) {
// cases
}
</pre>

<p>
Cases then match actual types <code>T</code> against the dynamic type of the
expression <code>x</code>. As with type assertions, <code>x</code> must be of
<a href="#Interface_types">interface type</a>, and each non-interface type
<code>T</code> listed in a case must implement the type of <code>x</code>.
Rob Pike's avatar
Rob Pike committed
4561 4562
</p>

4563
<pre class="ebnf">
4564
TypeSwitchStmt  = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
4565
TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
4566
TypeCaseClause  = TypeSwitchCase ":" StatementList .
Rob Pike's avatar
Rob Pike committed
4567 4568
TypeSwitchCase  = "case" TypeList | "default" .
TypeList        = Type { "," Type } .
Rob Pike's avatar
Rob Pike committed
4569 4570
</pre>

4571
<p>
4572 4573
The TypeSwitchGuard may include a
<a href="#Short_variable_declarations">short variable declaration</a>.
4574 4575
When that form is used, the variable is declared at the beginning of
the <a href="#Blocks">implicit block</a> in each clause.
4576 4577 4578
In clauses with a case listing exactly one type, the variable
has that type; otherwise, the variable has the type of the expression
in the TypeSwitchGuard.
4579 4580
</p>

Rob Pike's avatar
Rob Pike committed
4581
<p>
4582
The type in a case may be <a href="#Predeclared_identifiers"><code>nil</code></a>;
4583
that case is used when the expression in the TypeSwitchGuard
Robert Griesemer's avatar
tweaks  
Robert Griesemer committed
4584
is a <code>nil</code> interface value.
4585 4586 4587
</p>

<p>
Robert Griesemer's avatar
Robert Griesemer committed
4588
Given an expression <code>x</code> of type <code>interface{}</code>,
4589
the following type switch:
Rob Pike's avatar
Rob Pike committed
4590 4591 4592
</p>

<pre>
Robert Griesemer's avatar
Robert Griesemer committed
4593
switch i := x.(type) {
4594
case nil:
4595
	printString("x is nil")                // type of i is type of x (interface{})
Rob Pike's avatar
Rob Pike committed
4596
case int:
4597
	printInt(i)                            // type of i is int
4598
case float64:
4599
	printFloat64(i)                        // type of i is float64
4600
case func(int) float64:
4601
	printFunction(i)                       // type of i is func(int) float64
4602
case bool, string:
4603
	printString("type is bool or string")  // type of i is type of x (interface{})
Rob Pike's avatar
Rob Pike committed
4604
default:
4605
	printString("don't know the type")     // type of i is type of x (interface{})
Rob Pike's avatar
Rob Pike committed
4606
}
4607
</pre>
Rob Pike's avatar
Rob Pike committed
4608

4609 4610 4611 4612 4613
<p>
could be rewritten:
</p>

<pre>
4614
v := x  // x is evaluated exactly once
4615
if v == nil {
4616
	i := v                                 // type of i is type of x (interface{})
4617
	printString("x is nil")
4618
} else if i, isInt := v.(int); isInt {
4619
	printInt(i)                            // type of i is int
4620
} else if i, isFloat64 := v.(float64); isFloat64 {
4621
	printFloat64(i)                        // type of i is float64
4622
} else if i, isFunc := v.(func(int) float64); isFunc {
4623
	printFunction(i)                       // type of i is func(int) float64
4624
} else {
4625 4626
	_, isBool := v.(bool)
	_, isString := v.(string)
4627
	if isBool || isString {
4628 4629
		i := v                         // type of i is type of x (interface{})
		printString("type is bool or string")
4630
	} else {
4631 4632
		i := v                         // type of i is type of x (interface{})
		printString("don't know the type")
4633
	}
Rob Pike's avatar
Rob Pike committed
4634 4635
}
</pre>
4636

4637
<p>
Russ Cox's avatar
Russ Cox committed
4638 4639
The type switch guard may be preceded by a simple statement, which
executes before the guard is evaluated.
Robert Griesemer's avatar
tweaks  
Robert Griesemer committed
4640
</p>
4641 4642 4643

<p>
The "fallthrough" statement is not permitted in a type switch.
Russ Cox's avatar
Russ Cox committed
4644 4645
</p>

4646
<h3 id="For_statements">For statements</h3>
4647

Rob Pike's avatar
Rob Pike committed
4648 4649 4650 4651
<p>
A "for" statement specifies repeated execution of a block. The iteration is
controlled by a condition, a "for" clause, or a "range" clause.
</p>
4652

4653
<pre class="ebnf">
4654
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
4655 4656
Condition = Expression .
</pre>
4657

Rob Pike's avatar
Rob Pike committed
4658 4659 4660 4661
<p>
In its simplest form, a "for" statement specifies the repeated execution of
a block as long as a boolean condition evaluates to true.
The condition is evaluated before each iteration.
4662 4663
If the condition is absent, it is equivalent to the boolean value
<code>true</code>.
Rob Pike's avatar
Rob Pike committed
4664
</p>
4665

4666 4667 4668 4669 4670
<pre>
for a &lt; b {
	a *= 2
}
</pre>
4671

Rob Pike's avatar
Rob Pike committed
4672
<p>
Rob Pike's avatar
Rob Pike committed
4673
A "for" statement with a ForClause is also controlled by its condition, but
Rob Pike's avatar
Rob Pike committed
4674 4675
additionally it may specify an <i>init</i>
and a <i>post</i> statement, such as an assignment,
Russ Cox's avatar
Russ Cox committed
4676
an increment or decrement statement. The init statement may be a
Robert Griesemer's avatar
Robert Griesemer committed
4677
<a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not.
Rob Pike's avatar
Rob Pike committed
4678
</p>
4679

4680
<pre class="ebnf">
4681
ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
4682 4683
InitStmt = SimpleStmt .
PostStmt = SimpleStmt .
4684
</pre>
4685

4686
<pre>
4687
for i := 0; i &lt; 10; i++ {
4688 4689 4690
	f(i)
}
</pre>
4691

4692
<p>
Rob Pike's avatar
Rob Pike committed
4693 4694 4695 4696
If non-empty, the init statement is executed once before evaluating the
condition for the first iteration;
the post statement is executed after each execution of the block (and
only if the block was executed).
4697 4698
Any element of the ForClause may be empty but the
<a href="#Semicolons">semicolons</a> are
Rob Pike's avatar
Rob Pike committed
4699
required unless there is only a condition.
4700 4701
If the condition is absent, it is equivalent to the boolean value
<code>true</code>.
Rob Pike's avatar
Rob Pike committed
4702
</p>
Robert Griesemer's avatar
Robert Griesemer committed
4703

4704
<pre>
Rob Pike's avatar
Rob Pike committed
4705 4706
for cond { S() }    is the same as    for ; cond ; { S() }
for      { S() }    is the same as    for true     { S() }
4707
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
4708

Rob Pike's avatar
Rob Pike committed
4709 4710
<p>
A "for" statement with a "range" clause
Rob Pike's avatar
Rob Pike committed
4711
iterates through all entries of an array, slice, string or map,
4712
or values received on a channel. For each entry it assigns <i>iteration values</i>
4713
to corresponding <i>iteration variables</i> if present and then executes the block.
Rob Pike's avatar
Rob Pike committed
4714
</p>
Robert Griesemer's avatar
Robert Griesemer committed
4715

4716
<pre class="ebnf">
4717
RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .
4718 4719 4720 4721
</pre>

<p>
The expression on the right in the "range" clause is called the <i>range expression</i>,
4722 4723
which may be an array, pointer to an array, slice, string, map, or channel permitting
<a href="#Receive_operator">receive operations</a>.
4724
As with an assignment, if present the operands on the left must be
4725
<a href="#Address_operators">addressable</a> or map index expressions; they
4726 4727 4728 4729
denote the iteration variables. If the range expression is a channel, at most
one iteration variable is permitted, otherwise there may be up to two.
If the last iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
the range clause is equivalent to the same clause without that identifier.
4730
</p>
4731 4732

<p>
4733
The range expression is evaluated once before beginning the loop,
4734 4735 4736 4737
with one exception: if the range expression is an array or a pointer to an array
and at most one iteration variable is present, only the range expression's
length is evaluated; if that length is constant,
<a href="#Length_and_capacity">by definition</a>
4738 4739 4740 4741
the range expression itself will not be evaluated.
</p>

<p>
4742
Function calls on the left are evaluated once per iteration.
4743 4744
For each iteration, iteration values are produced as follows
if the respective iteration variables are present:
4745 4746 4747
</p>

<pre class="grammar">
4748
Range expression                          1st value          2nd value
4749 4750

array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
4751
string          s  string type            index    i  int    see below  rune
4752
map             m  map[K]V                key      k  K      m[k]       V
4753
channel         c  chan E, &lt;-chan E       element  e  E
4754 4755 4756 4757
</pre>

<ol>
<li>
4758
For an array, pointer to array, or slice value <code>a</code>, the index iteration
4759
values are produced in increasing order, starting at element index 0.
4760
If at most one iteration variable is present, the range loop produces
4761
iteration values from 0 up to <code>len(a)-1</code> and does not index into the array
4762
or slice itself. For a <code>nil</code> slice, the number of iterations is 0.
4763 4764 4765 4766 4767 4768
</li>

<li>
For a string value, the "range" clause iterates over the Unicode code points
in the string starting at byte index 0.  On successive iterations, the index value will be the
index of the first byte of successive UTF-8-encoded code points in the string,
4769
and the second value, of type <code>rune</code>, will be the value of
Rob Pike's avatar
Rob Pike committed
4770
the corresponding code point.  If the iteration encounters an invalid
4771
UTF-8 sequence, the second value will be <code>0xFFFD</code>,
Rob Pike's avatar
Rob Pike committed
4772 4773
the Unicode replacement character, and the next iteration will advance
a single byte in the string.
4774 4775 4776
</li>

<li>
4777 4778
The iteration order over maps is not specified
and is not guaranteed to be the same from one iteration to the next.
4779
If map entries that have not yet been reached are removed during iteration,
4780
the corresponding iteration values will not be produced. If map entries are
4781 4782 4783 4784
created during iteration, that entry may be produced during the iteration or
may be skipped. The choice may vary for each entry created and from one
iteration to the next.
If the map is <code>nil</code>, the number of iterations is 0.
4785 4786 4787 4788
</li>

<li>
For channels, the iteration values produced are the successive values sent on
4789 4790
the channel until the channel is <a href="#Close">closed</a>. If the channel
is <code>nil</code>, the range expression blocks forever.
4791
</li>
Anthony Martin's avatar
Anthony Martin committed
4792
</ol>
4793

Rob Pike's avatar
Rob Pike committed
4794
<p>
4795 4796
The iteration values are assigned to the respective
iteration variables as in an <a href="#Assignments">assignment statement</a>.
4797
</p>
4798

4799
<p>
Robert Griesemer's avatar
Robert Griesemer committed
4800
The iteration variables may be declared by the "range" clause using a form of
4801 4802
<a href="#Short_variable_declarations">short variable declaration</a>
(<code>:=</code>).
4803 4804 4805
In this case their types are set to the types of the respective iteration values
and their <a href="#Declarations_and_scope">scope</a> ends at the end of the "for"
statement; they are re-used in each iteration.
Rob Pike's avatar
Rob Pike committed
4806 4807 4808
If the iteration variables are declared outside the "for" statement,
after execution their values will be those of the last iteration.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
4809

4810
<pre>
4811 4812 4813 4814 4815 4816 4817 4818 4819
var testdata *struct {
	a *[7]int
}
for i, _ := range testdata.a {
	// testdata.a is never evaluated; len(testdata.a) is constant
	// i ranges from 0 to 6
	f(i)
}

4820
var a [10]string
4821 4822 4823 4824 4825 4826 4827
for i, s := range a {
	// type of i is int
	// type of s is string
	// s == a[i]
	g(i, s)
}

4828
var key string
4829
var val interface {}  // value type of m is assignable to val
4830
m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}
Rob Pike's avatar
Rob Pike committed
4831 4832
for key, val = range m {
	h(key, val)
4833 4834 4835
}
// key == last map key encountered in iteration
// val == map[key]
4836 4837 4838 4839 4840

var ch chan Work = producer()
for w := range ch {
	doWork(w)
}
4841 4842 4843

// empty a channel
for range ch {}
4844
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
4845

4846

4847
<h3 id="Go_statements">Go statements</h3>
4848

Rob Pike's avatar
Rob Pike committed
4849
<p>
4850
A "go" statement starts the execution of a function call
Rob Pike's avatar
Rob Pike committed
4851 4852 4853
as an independent concurrent thread of control, or <i>goroutine</i>,
within the same address space.
</p>
4854

4855
<pre class="ebnf">
4856
GoStmt = "go" Expression .
4857
</pre>
4858

Rob Pike's avatar
Rob Pike committed
4859
<p>
4860 4861 4862 4863 4864 4865
The expression must be a function or method call; it cannot be parenthesized.
Calls of built-in functions are restricted as for
<a href="#Expression_statements">expression statements</a>.
</p>

<p>
4866 4867 4868
The function value and parameters are
<a href="#Calls">evaluated as usual</a>
in the calling goroutine, but
Rob Pike's avatar
Rob Pike committed
4869
unlike with a regular call, program execution does not wait
4870
for the invoked function to complete.
4871 4872 4873 4874 4875
Instead, the function begins executing independently
in a new goroutine.
When the function terminates, its goroutine also terminates.
If the function has any return values, they are discarded when the
function completes.
Rob Pike's avatar
Rob Pike committed
4876
</p>
4877

4878 4879
<pre>
go Server()
4880
go func(ch chan&lt;- bool) { for { sleep(10); ch &lt;- true; }} (c)
4881
</pre>
4882 4883


4884
<h3 id="Select_statements">Select statements</h3>
4885

Rob Pike's avatar
Rob Pike committed
4886
<p>
4887 4888 4889 4890 4891 4892
A "select" statement chooses which of a set of possible
<a href="#Send_statements">send</a> or
<a href="#Receive_operator">receive</a>
operations will proceed.
It looks similar to a
<a href="#Switch_statements">"switch"</a> statement but with the
4893
cases all referring to communication operations.
Rob Pike's avatar
Rob Pike committed
4894
</p>
4895

4896
<pre class="ebnf">
4897
SelectStmt = "select" "{" { CommClause } "}" .
4898
CommClause = CommCase ":" StatementList .
4899
CommCase   = "case" ( SendStmt | RecvStmt ) | "default" .
4900
RecvStmt   = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
4901
RecvExpr   = Expression .
4902
</pre>
4903

4904
<p>
4905 4906 4907 4908 4909 4910
A case with a RecvStmt may assign the result of a RecvExpr to one or
two variables, which may be declared using a
<a href="#Short_variable_declarations">short variable declaration</a>.
The RecvExpr must be a (possibly parenthesized) receive operation.
There can be at most one default case and it may appear anywhere
in the list of cases.
Rob Pike's avatar
Rob Pike committed
4911
</p>
4912

4913
<p>
4914
Execution of a "select" statement proceeds in several steps:
Rob Pike's avatar
Rob Pike committed
4915
</p>
4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953

<ol>
<li>
For all the cases in the statement, the channel operands of receive operations
and the channel and right-hand-side expressions of send statements are
evaluated exactly once, in source order, upon entering the "select" statement.
The result is a set of channels to receive from or send to,
and the corresponding values to send.
Any side effects in that evaluation will occur irrespective of which (if any)
communication operation is selected to proceed.
Expressions on the left-hand side of a RecvStmt with a short variable declaration
or assignment are not yet evaluated.
</li>

<li>
If one or more of the communications can proceed,
a single one that can proceed is chosen via a uniform pseudo-random selection.
Otherwise, if there is a default case, that case is chosen.
If there is no default case, the "select" statement blocks until
at least one of the communications can proceed.
</li>

<li>
Unless the selected case is the default case, the respective communication
operation is executed.
</li>

<li>
If the selected case is a RecvStmt with a short variable declaration or
an assignment, the left-hand side expressions are evaluated and the
received value (or values) are assigned.
</li>

<li>
The statement list of the selected case is executed.
</li>
</ol>

4954
<p>
4955 4956
Since communication on <code>nil</code> channels can never proceed,
a select with only <code>nil</code> channels and no default case blocks forever.
Rob Pike's avatar
Rob Pike committed
4957
</p>
4958

4959
<pre>
4960 4961
var a []int
var c, c1, c2, c3, c4 chan int
4962
var i1, i2 int
4963 4964
select {
case i1 = &lt;-c1:
4965
	print("received ", i1, " from c1\n")
4966
case c2 &lt;- i2:
4967
	print("sent ", i2, " to c2\n")
4968
case i3, ok := (&lt;-c3):  // same as: i3, ok := &lt;-c3
4969 4970 4971 4972 4973
	if ok {
		print("received ", i3, " from c3\n")
	} else {
		print("c3 is closed\n")
	}
4974 4975 4976 4977
case a[f()] = &lt;-c4:
	// same as:
	// case t := &lt;-c4
	//	a[f()] = t
4978
default:
4979
	print("no communication\n")
4980 4981 4982
}

for {  // send random sequence of bits to c
4983
	select {
4984 4985
	case c &lt;- 0:  // note: no statement, no fallthrough, no folding of cases
	case c &lt;- 1:
4986
	}
4987
}
4988

4989
select {}  // block forever
4990
</pre>
4991 4992


4993
<h3 id="Return_statements">Return statements</h3>
4994

Rob Pike's avatar
Rob Pike committed
4995
<p>
4996 4997 4998 4999
A "return" statement in a function <code>F</code> terminates the execution
of <code>F</code>, and optionally provides one or more result values.
Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
are executed before <code>F</code> returns to its caller.
Rob Pike's avatar
Rob Pike committed
5000
</p>
5001

5002
<pre class="ebnf">
5003
ReturnStmt = "return" [ ExpressionList ] .
5004
</pre>
5005

5006 5007 5008 5009
<p>
In a function without a result type, a "return" statement must not
specify any result values.
</p>
Rob Pike's avatar
Rob Pike committed
5010
<pre>
5011
func noResult() {
Rob Pike's avatar
Rob Pike committed
5012 5013 5014
	return
}
</pre>
5015

Rob Pike's avatar
Rob Pike committed
5016
<p>
5017 5018
There are three ways to return values from a function with a result
type:
Rob Pike's avatar
Rob Pike committed
5019
</p>
5020

5021 5022 5023
<ol>
	<li>The return value or values may be explicitly listed
		in the "return" statement. Each expression must be single-valued
5024 5025
		and <a href="#Assignability">assignable</a>
		to the corresponding element of the function's result type.
5026
<pre>
5027
func simpleF() int {
Rob Pike's avatar
Rob Pike committed
5028 5029 5030
	return 2
}

5031
func complexF1() (re float64, im float64) {
Rob Pike's avatar
Rob Pike committed
5032
	return -7.0, -4.0
5033 5034
}
</pre>
5035 5036 5037 5038 5039 5040 5041
	</li>
	<li>The expression list in the "return" statement may be a single
		call to a multi-valued function. The effect is as if each value
		returned from that function were assigned to a temporary
		variable with the type of the respective value, followed by a
		"return" statement listing these variables, at which point the
		rules of the previous case apply.
5042
<pre>
5043 5044
func complexF2() (re float64, im float64) {
	return complexF1()
5045 5046
}
</pre>
5047
	</li>
Peter Mundy's avatar
Peter Mundy committed
5048
	<li>The expression list may be empty if the function's result
5049
		type specifies names for its <a href="#Function_types">result parameters</a>.
5050
		The result parameters act as ordinary local variables
5051 5052
		and the function may assign values to them as necessary.
		The "return" statement returns the values of these variables.
5053
<pre>
5054
func complexF3() (re float64, im float64) {
5055 5056 5057
	re = 7.0
	im = 4.0
	return
5058
}
5059

Russ Cox's avatar
Russ Cox committed
5060
func (devnull) Write(p []byte) (n int, _ error) {
5061 5062
	n = len(p)
	return
5063
}
5064
</pre>
5065 5066
	</li>
</ol>
5067

5068
<p>
5069 5070
Regardless of how they are declared, all the result values are initialized to
the <a href="#The_zero_value">zero values</a> for their type upon entry to the
5071 5072
function. A "return" statement that specifies results sets the result parameters before
any deferred functions are executed.
5073 5074
</p>

5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089
<p>
Implementation restriction: A compiler may disallow an empty expression list
in a "return" statement if a different entity (constant, type, or variable)
with the same name as a result parameter is in
<a href="#Declarations_and_scope">scope</a> at the place of the return.
</p>

<pre>
func f(n int) (res int, err error) {
	if _, err := f(n-1); err != nil {
		return  // invalid return statement: err is shadowed
	}
	return
}
</pre>
5090

5091
<h3 id="Break_statements">Break statements</h3>
5092

Rob Pike's avatar
Rob Pike committed
5093 5094
<p>
A "break" statement terminates execution of the innermost
5095 5096
<a href="#For_statements">"for"</a>,
<a href="#Switch_statements">"switch"</a>, or
5097 5098
<a href="#Select_statements">"select"</a> statement
within the same function.
Rob Pike's avatar
Rob Pike committed
5099
</p>
5100

5101
<pre class="ebnf">
5102
BreakStmt = "break" [ Label ] .
5103
</pre>
5104

Rob Pike's avatar
Rob Pike committed
5105 5106
<p>
If there is a label, it must be that of an enclosing
5107 5108
"for", "switch", or "select" statement,
and that is the one whose execution terminates.
Rob Pike's avatar
Rob Pike committed
5109
</p>
5110

5111
<pre>
5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122
OuterLoop:
	for i = 0; i &lt; n; i++ {
		for j = 0; j &lt; m; j++ {
			switch a[i][j] {
			case nil:
				state = Error
				break OuterLoop
			case item:
				state = Found
				break OuterLoop
			}
Russ Cox's avatar
Russ Cox committed
5123
		}
5124
	}
5125
</pre>
5126

5127
<h3 id="Continue_statements">Continue statements</h3>
5128

Rob Pike's avatar
Rob Pike committed
5129 5130
<p>
A "continue" statement begins the next iteration of the
5131
innermost <a href="#For_statements">"for" loop</a> at its post statement.
5132
The "for" loop must be within the same function.
Rob Pike's avatar
Rob Pike committed
5133
</p>
5134

5135
<pre class="ebnf">
5136
ContinueStmt = "continue" [ Label ] .
5137
</pre>
5138

Rob Pike's avatar
Rob Pike committed
5139
<p>
5140 5141
If there is a label, it must be that of an enclosing
"for" statement, and that is the one whose execution
5142
advances.
Rob Pike's avatar
Rob Pike committed
5143
</p>
5144

5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156
<pre>
RowLoop:
	for y, row := range rows {
		for x, data := range row {
			if data == endOfRow {
				continue RowLoop
			}
			row[x] = data + bias(x, y)
		}
	}
</pre>

5157
<h3 id="Goto_statements">Goto statements</h3>
5158

Rob Pike's avatar
Rob Pike committed
5159
<p>
5160 5161
A "goto" statement transfers control to the statement with the corresponding label
within the same function.
Rob Pike's avatar
Rob Pike committed
5162
</p>
5163

5164
<pre class="ebnf">
5165
GotoStmt = "goto" Label .
5166
</pre>
5167

5168 5169 5170
<pre>
goto Error
</pre>
5171

Rob Pike's avatar
Rob Pike committed
5172 5173
<p>
Executing the "goto" statement must not cause any variables to come into
Russ Cox's avatar
Russ Cox committed
5174 5175
<a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto.
For instance, this example:
Rob Pike's avatar
Rob Pike committed
5176
</p>
5177

5178
<pre>
Russ Cox's avatar
Russ Cox committed
5179 5180
	goto L  // BAD
	v := 3
5181 5182
L:
</pre>
5183

Rob Pike's avatar
Rob Pike committed
5184 5185 5186
<p>
is erroneous because the jump to label <code>L</code> skips
the creation of <code>v</code>.
Russ Cox's avatar
Russ Cox committed
5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207
</p>

<p>
A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block.
For instance, this example:
</p>

<pre>
if n%2 == 1 {
	goto L1
}
for n &gt; 0 {
	f()
	n--
L1:
	f()
	n--
}
</pre>

<p>
5208
is erroneous because the label <code>L1</code> is inside
Russ Cox's avatar
Russ Cox committed
5209
the "for" statement's block but the <code>goto</code> is not.
Rob Pike's avatar
Rob Pike committed
5210
</p>
5211

5212
<h3 id="Fallthrough_statements">Fallthrough statements</h3>
5213

Rob Pike's avatar
Rob Pike committed
5214 5215
<p>
A "fallthrough" statement transfers control to the first statement of the
5216 5217
next case clause in a <a href="#Expression_switches">expression "switch" statement</a>.
It may be used only as the final non-empty statement in such a clause.
Rob Pike's avatar
Rob Pike committed
5218
</p>
5219

5220
<pre class="ebnf">
5221
FallthroughStmt = "fallthrough" .
5222
</pre>
5223 5224


5225
<h3 id="Defer_statements">Defer statements</h3>
Robert Griesemer's avatar
Robert Griesemer committed
5226

Rob Pike's avatar
Rob Pike committed
5227
<p>
5228 5229 5230 5231 5232
A "defer" statement invokes a function whose execution is deferred
to the moment the surrounding function returns, either because the
surrounding function executed a <a href="#Return_statements">return statement</a>,
reached the end of its <a href="#Function_declarations">function body</a>,
or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>.
Rob Pike's avatar
Rob Pike committed
5233
</p>
Robert Griesemer's avatar
Robert Griesemer committed
5234

5235
<pre class="ebnf">
5236
DeferStmt = "defer" Expression .
5237
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
5238

Rob Pike's avatar
Rob Pike committed
5239
<p>
5240 5241 5242 5243 5244 5245
The expression must be a function or method call; it cannot be parenthesized.
Calls of built-in functions are restricted as for
<a href="#Expression_statements">expression statements</a>.
</p>

<p>
Rob Pike's avatar
Rob Pike committed
5246
Each time the "defer" statement
5247 5248
executes, the function value and parameters to the call are
<a href="#Calls">evaluated as usual</a>
5249 5250 5251 5252 5253 5254 5255 5256
and saved anew but the actual function body is not executed.
Instead, deferred functions are executed immediately before
the surrounding function returns, in the reverse order
they were deferred.
</p>

<p>
For instance, if the deferred function is
Rob Pike's avatar
Rob Pike committed
5257
a <a href="#Function_literals">function literal</a> and the surrounding
5258 5259 5260
function has <a href="#Function_types">named result parameters</a> that
are in scope within the literal, the deferred function may access and modify
the result parameters before they are returned.
5261 5262
If the deferred function has any return values, they are discarded when
the function completes.
5263 5264 5265
(See also the section on <a href="#Handling_panics">handling panics</a>.)
</p>

5266
<pre>
5267 5268
lock(l)
defer unlock(l)  // unlocking happens before surrounding function returns
Robert Griesemer's avatar
Robert Griesemer committed
5269

5270 5271
// prints 3 2 1 0 before surrounding function returns
for i := 0; i &lt;= 3; i++ {
5272
	defer fmt.Print(i)
5273
}
5274 5275 5276 5277 5278 5279 5280 5281

// f returns 1
func f() (result int) {
	defer func() {
		result++
	}()
	return 0
}
5282
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
5283

5284
<h2 id="Built-in_functions">Built-in functions</h2>
5285 5286

<p>
Rob Pike's avatar
Rob Pike committed
5287
Built-in functions are
5288 5289 5290 5291
<a href="#Predeclared_identifiers">predeclared</a>.
They are called like any other function but some of them
accept a type instead of an expression as the first argument.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
5292

5293 5294 5295 5296 5297 5298
<p>
The built-in functions do not have standard Go types,
so they can only appear in <a href="#Calls">call expressions</a>;
they cannot be used as function values.
</p>

5299
<pre class="ebnf">
Robert Griesemer's avatar
Robert Griesemer committed
5300
BuiltinCall = identifier "(" [ BuiltinArgs [ "," ] ] ")" .
5301
BuiltinArgs = Type [ "," ArgumentList ] | ArgumentList .
5302
</pre>
5303

5304
<h3 id="Close">Close</h3>
5305

Rob Pike's avatar
Rob Pike committed
5306
<p>
5307
For a channel <code>c</code>, the built-in function <code>close(c)</code>
5308 5309 5310 5311
records that no more values will be sent on the channel.
It is an error if <code>c</code> is a receive-only channel.
Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>.
Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>.
5312
After calling <code>close</code>, and after any previously
5313
sent values have been received, receive operations will return
5314
the zero value for the channel's type without blocking.
5315 5316
The multi-valued <a href="#Receive_operator">receive operation</a>
returns a received value along with an indication of whether the channel is closed.
Rob Pike's avatar
Rob Pike committed
5317
</p>
5318

5319

5320
<h3 id="Length_and_capacity">Length and capacity</h3>
5321

Rob Pike's avatar
Rob Pike committed
5322
<p>
5323 5324 5325
The built-in functions <code>len</code> and <code>cap</code> take arguments
of various types and return a result of type <code>int</code>.
The implementation guarantees that the result always fits into an <code>int</code>.
5326 5327
</p>

5328
<pre class="grammar">
5329
Call      Argument type    Result
5330

5331 5332 5333 5334 5335
len(s)    string type      string length in bytes
          [n]T, *[n]T      array length (== n)
          []T              slice length
          map[K]T          map length (number of defined keys)
          chan T           number of elements queued in channel buffer
5336

5337 5338 5339
cap(s)    [n]T, *[n]T      array length (== n)
          []T              slice capacity
          chan T           channel buffer capacity
5340
</pre>
5341

5342 5343 5344 5345 5346
<p>
The capacity of a slice is the number of elements for which there is
space allocated in the underlying array.
At any time the following relationship holds:
</p>
5347

5348
<pre>
Anthony Martin's avatar
Anthony Martin committed
5349
0 &lt;= len(s) &lt;= cap(s)
5350
</pre>
5351

5352
<p>
5353
The length of a <code>nil</code> slice, map or channel is 0.
5354
The capacity of a <code>nil</code> slice or channel is 0.
5355 5356
</p>

5357
<p>
5358 5359 5360 5361
The expression <code>len(s)</code> is <a href="#Constants">constant</a> if
<code>s</code> is a string constant. The expressions <code>len(s)</code> and
<code>cap(s)</code> are constants if the type of <code>s</code> is an array
or pointer to an array and the expression <code>s</code> does not contain
5362
<a href="#Receive_operator">channel receives</a> or (non-constant)
5363 5364 5365
<a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated.
Otherwise, invocations of <code>len</code> and <code>cap</code> are not
constant and <code>s</code> is evaluated.
5366
</p>
5367

5368 5369 5370 5371 5372 5373 5374 5375 5376 5377
<pre>
const (
	c1 = imag(2i)                    // imag(2i) = 2.0 is a constant
	c2 = len([10]float64{2})         // [10]float64{2} contains no function calls
	c3 = len([10]float64{c1})        // [10]float64{c1} contains no function calls
	c4 = len([10]float64{imag(2i)})  // imag(2i) is a constant and no function call is issued
	c5 = len([10]float64{imag(z)})   // invalid: imag(x) is a (non-constant) function call
)
var z complex128
</pre>
5378

5379
<h3 id="Allocation">Allocation</h3>
5380

Rob Pike's avatar
Rob Pike committed
5381 5382 5383
<p>
The built-in function <code>new</code> takes a type <code>T</code> and
returns a value of type <code>*T</code>.
5384 5385
The memory is initialized as described in the section on
<a href="#The_zero_value">initial values</a>.
Rob Pike's avatar
Rob Pike committed
5386
</p>
5387

5388
<pre class="grammar">
5389 5390
new(T)
</pre>
5391

Rob Pike's avatar
Rob Pike committed
5392
<p>
5393
For instance
Rob Pike's avatar
Rob Pike committed
5394
</p>
5395

5396
<pre>
5397
type S struct { a int; b float64 }
5398 5399
new(S)
</pre>
5400

5401
<p>
Rob Pike's avatar
Rob Pike committed
5402 5403 5404 5405 5406
dynamically allocates memory for a variable of type <code>S</code>,
initializes it (<code>a=0</code>, <code>b=0.0</code>),
and returns a value of type <code>*S</code> containing the address
of the memory.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
5407

5408
<h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3>
Robert Griesemer's avatar
Robert Griesemer committed
5409

Rob Pike's avatar
Rob Pike committed
5410 5411 5412 5413 5414
<p>
The built-in function <code>make</code> takes a type <code>T</code>,
which must be a slice, map or channel type,
optionally followed by a type-specific list of expressions.
It returns a value of type <code>T</code> (not <code>*T</code>).
5415 5416
The memory is initialized as described in the section on
<a href="#The_zero_value">initial values</a>.
Rob Pike's avatar
Rob Pike committed
5417
</p>
Robert Griesemer's avatar
Robert Griesemer committed
5418

5419
<pre class="grammar">
5420
Call             Type T     Result
Robert Griesemer's avatar
Robert Griesemer committed
5421

5422 5423
make(T, n)       slice      slice of type T with length n and capacity n
make(T, n, m)    slice      slice of type T with length n and capacity m
Robert Griesemer's avatar
Robert Griesemer committed
5424

5425 5426 5427
make(T)          map        map of type T
make(T, n)       map        map of type T with initial space for n elements

5428 5429
make(T)          channel    unbuffered channel of type T
make(T, n)       channel    buffered channel of type T, buffer size n
5430
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
5431 5432


Rob Pike's avatar
Rob Pike committed
5433
<p>
5434
The size arguments <code>n</code> and <code>m</code> must be of integer type or untyped.
5435 5436 5437
A <a href="#Constants">constant</a> size argument must be non-negative and
representable by a value of type <code>int</code>.
If both <code>n</code> and <code>m</code> are provided and are constant, then
5438 5439 5440
<code>n</code> must be no larger than <code>m</code>.
If <code>n</code> is negative or larger than <code>m</code> at run time,
a <a href="#Run_time_panics">run-time panic</a> occurs.
Rob Pike's avatar
Rob Pike committed
5441
</p>
Robert Griesemer's avatar
Robert Griesemer committed
5442

5443
<pre>
5444
s := make([]int, 10, 100)       // slice with len(s) == 10, cap(s) == 100
5445
s := make([]int, 1e3)           // slice with len(s) == cap(s) == 1000
5446
s := make([]int, 1&lt;&lt;63)         // illegal: len(s) is not representable by a value of type int
5447
s := make([]int, 10, 0)         // illegal: len(s) > cap(s)
5448 5449
c := make(chan int, 10)         // channel with a buffer size of 10
m := make(map[string]int, 100)  // map with initial space for 100 elements
5450
</pre>
5451

5452

Robert Griesemer's avatar
Robert Griesemer committed
5453
<h3 id="Appending_and_copying_slices">Appending to and copying slices</h3>
5454 5455

<p>
5456 5457 5458 5459
The built-in functions <code>append</code> and <code>copy</code> assist in
common slice operations.
For both functions, the result is independent of whether the memory referenced
by the arguments overlaps.
Robert Griesemer's avatar
Robert Griesemer committed
5460 5461 5462
</p>

<p>
5463 5464
The <a href="#Function_types">variadic</a> function <code>append</code>
appends zero or more values <code>x</code>
5465 5466
to <code>s</code> of type <code>S</code>, which must be a slice type, and
returns the resulting slice, also of type <code>S</code>.
5467 5468 5469 5470
The values <code>x</code> are passed to a parameter of type <code>...T</code>
where <code>T</code> is the <a href="#Slice_types">element type</a> of
<code>S</code> and the respective
<a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply.
5471 5472 5473 5474
As a special case, <code>append</code> also accepts a first argument
assignable to type <code>[]byte</code> with a second argument of
string type followed by <code>...</code>. This form appends the
bytes of the string.
Robert Griesemer's avatar
Robert Griesemer committed
5475 5476 5477
</p>

<pre class="grammar">
5478
append(s S, x ...T) S  // T is the element type of S
Robert Griesemer's avatar
Robert Griesemer committed
5479 5480 5481 5482
</pre>

<p>
If the capacity of <code>s</code> is not large enough to fit the additional
5483 5484 5485
values, <code>append</code> allocates a new, sufficiently large underlying
array that fits both the existing slice elements and the additional values.
Otherwise, <code>append</code> re-uses the underlying array.
Robert Griesemer's avatar
Robert Griesemer committed
5486 5487 5488 5489
</p>

<pre>
s0 := []int{0, 0}
5490 5491 5492 5493
s1 := append(s0, 2)                // append a single element     s1 == []int{0, 0, 2}
s2 := append(s1, 3, 5, 7)          // append multiple elements    s2 == []int{0, 0, 2, 3, 5, 7}
s3 := append(s2, s0...)            // append a slice              s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
s4 := append(s3[3:6], s3[2:]...)   // append overlapping slice    s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
5494 5495

var t []interface{}
5496
t = append(t, 42, 3.1415, "foo")                                  t == []interface{}{42, 3.1415, "foo"}
5497 5498

var b []byte
5499
b = append(b, "bar"...)            // append string contents      b == []byte{'b', 'a', 'r' }
Robert Griesemer's avatar
Robert Griesemer committed
5500 5501 5502 5503
</pre>

<p>
The function <code>copy</code> copies slice elements from
5504
a source <code>src</code> to a destination <code>dst</code> and returns the
5505
number of elements copied.
5506
Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be
5507
<a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>.
5508
The number of elements copied is the minimum of
5509
<code>len(src)</code> and <code>len(dst)</code>.
5510 5511 5512
As a special case, <code>copy</code> also accepts a destination argument assignable
to type <code>[]byte</code> with a source argument of a string type.
This form copies the bytes from the string into the byte slice.
5513 5514 5515 5516
</p>

<pre class="grammar">
copy(dst, src []T) int
5517
copy(dst []byte, src string) int
5518 5519 5520 5521 5522 5523 5524
</pre>

<p>
Examples:
</p>

<pre>
5525 5526
var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7}
var s = make([]int, 6)
5527 5528 5529 5530
var b = make([]byte, 5)
n1 := copy(s, a[0:])            // n1 == 6, s == []int{0, 1, 2, 3, 4, 5}
n2 := copy(s, s[2:])            // n2 == 4, s == []int{2, 3, 4, 5, 4, 5}
n3 := copy(b, "Hello, World!")  // n3 == 5, b == []byte("Hello")
5531 5532
</pre>

5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547

<h3 id="Deletion_of_map_elements">Deletion of map elements</h3>

<p>
The built-in function <code>delete</code> removes the element with key
<code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The
type of <code>k</code> must be <a href="#Assignability">assignable</a>
to the key type of <code>m</code>.
</p>

<pre class="grammar">
delete(m, k)  // remove element m[k] from map m
</pre>

<p>
5548 5549
If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code>
does not exist, <code>delete</code> is a no-op.
5550 5551 5552
</p>


5553
<h3 id="Complex_numbers">Manipulating complex numbers</h3>
Rob Pike's avatar
Rob Pike committed
5554 5555 5556

<p>
Three functions assemble and disassemble complex numbers.
5557
The built-in function <code>complex</code> constructs a complex
Rob Pike's avatar
Rob Pike committed
5558 5559 5560 5561 5562 5563
value from a floating-point real and imaginary part, while
<code>real</code> and <code>imag</code>
extract the real and imaginary parts of a complex value.
</p>

<pre class="grammar">
5564
complex(realPart, imaginaryPart floatT) complexT
Rob Pike's avatar
Rob Pike committed
5565 5566 5567 5568 5569 5570
real(complexT) floatT
imag(complexT) floatT
</pre>

<p>
The type of the arguments and return value correspond.
5571
For <code>complex</code>, the two arguments must be of the same
Rob Pike's avatar
Rob Pike committed
5572 5573 5574 5575 5576 5577
floating-point type and the return type is the complex type
with the corresponding floating-point constituents:
<code>complex64</code> for <code>float32</code>,
<code>complex128</code> for <code>float64</code>.
The <code>real</code> and <code>imag</code> functions
together form the inverse, so for a complex value <code>z</code>,
5578
<code>z</code> <code>==</code> <code>complex(real(z),</code> <code>imag(z))</code>.
Rob Pike's avatar
Rob Pike committed
5579 5580 5581 5582 5583 5584 5585 5586
</p>

<p>
If the operands of these functions are all constants, the return
value is a constant.
</p>

<pre>
5587 5588 5589 5590 5591 5592
var a = complex(2, -2)             // complex128
var b = complex(1.0, -1.4)         // complex128
x := float32(math.Cos(math.Pi/2))  // float32
var c64 = complex(5, -x)           // complex64
var im = imag(b)                   // float64
var rl = real(c64)                 // float32
Rob Pike's avatar
Rob Pike committed
5593 5594
</pre>

Rob Pike's avatar
Rob Pike committed
5595 5596 5597 5598
<h3 id="Handling_panics">Handling panics</h3>

<p> Two built-in functions, <code>panic</code> and <code>recover</code>,
assist in reporting and handling <a href="#Run_time_panics">run-time panics</a>
5599
and program-defined error conditions.
Rob Pike's avatar
Rob Pike committed
5600 5601 5602 5603 5604 5605 5606 5607
</p>

<pre class="grammar">
func panic(interface{})
func recover() interface{}
</pre>

<p>
5608 5609 5610
While executing a function <code>F</code>,
an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a>
terminates the execution of <code>F</code>.
5611
Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
5612 5613 5614 5615
are then executed as usual.
Next, any deferred functions run by <code>F's</code> caller are run,
and so on up to any deferred by the top-level function in the executing goroutine.
At that point, the program is terminated and the error
5616 5617
condition is reported, including the value of the argument to <code>panic</code>.
This termination sequence is called <i>panicking</i>.
Rob Pike's avatar
Rob Pike committed
5618 5619
</p>

5620 5621 5622 5623 5624 5625
<pre>
panic(42)
panic("unreachable")
panic(Error("cannot parse"))
</pre>

Rob Pike's avatar
Rob Pike committed
5626 5627
<p>
The <code>recover</code> function allows a program to manage behavior
5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643
of a panicking goroutine.
Suppose a function <code>G</code> defers a function <code>D</code> that calls
<code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code>
is executing.
When the running of deferred functions reaches <code>D</code>,
the return value of <code>D</code>'s call to <code>recover</code> will be the value passed to the call of <code>panic</code>.
If <code>D</code> returns normally, without starting a new
<code>panic</code>, the panicking sequence stops. In that case,
the state of functions called between <code>G</code> and the call to <code>panic</code>
is discarded, and normal execution resumes.
Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s
execution terminates by returning to its caller.
</p>

<p>
The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds:
Rob Pike's avatar
Rob Pike committed
5644
</p>
5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655
<ul>
<li>
<code>panic</code>'s argument was <code>nil</code>;
</li>
<li>
the goroutine is not panicking;
</li>
<li>
<code>recover</code> was not called directly by a deferred function.
</li>
</ul>
Rob Pike's avatar
Rob Pike committed
5656 5657

<p>
5658 5659 5660
The <code>protect</code> function in the example below invokes
the function argument <code>g</code> and protects callers from
run-time panics raised by <code>g</code>.
Rob Pike's avatar
Rob Pike committed
5661 5662 5663
</p>

<pre>
5664
func protect(g func()) {
Rob Pike's avatar
Rob Pike committed
5665
	defer func() {
5666
		log.Println("done")  // Println executes normally even if there is a panic
Rob Pike's avatar
Rob Pike committed
5667
		if x := recover(); x != nil {
5668
			log.Printf("run time panic: %v", x)
Rob Pike's avatar
Rob Pike committed
5669
		}
5670
	}()
5671 5672
	log.Println("start")
	g()
Rob Pike's avatar
Rob Pike committed
5673 5674 5675
}
</pre>

5676

5677 5678
<h3 id="Bootstrapping">Bootstrapping</h3>

5679
<p>
5680 5681 5682
Current implementations provide several built-in functions useful during
bootstrapping. These functions are documented for completeness but are not
guaranteed to stay in the language. They do not return a result.
5683 5684
</p>

5685
<pre class="grammar">
5686
Function   Behavior
5687 5688 5689 5690 5691 5692

print      prints all arguments; formatting of arguments is implementation-specific
println    like print but prints spaces between arguments and a newline at the end
</pre>


5693
<h2 id="Packages">Packages</h2>
5694

Rob Pike's avatar
Rob Pike committed
5695 5696
<p>
Go programs are constructed by linking together <i>packages</i>.
5697 5698 5699 5700 5701
A package in turn is constructed from one or more source files
that together declare constants, types, variables and functions
belonging to the package and which are accessible in all files
of the same package. Those elements may be
<a href="#Exported_identifiers">exported</a> and used in another package.
Rob Pike's avatar
Rob Pike committed
5702 5703
</p>

5704
<h3 id="Source_file_organization">Source file organization</h3>
Rob Pike's avatar
Rob Pike committed
5705 5706 5707 5708 5709 5710

<p>
Each source file consists of a package clause defining the package
to which it belongs, followed by a possibly empty set of import
declarations that declare packages whose contents it wishes to use,
followed by a possibly empty set of declarations of functions,
Robert Griesemer's avatar
Robert Griesemer committed
5711
types, variables, and constants.
Rob Pike's avatar
Rob Pike committed
5712
</p>
5713

5714
<pre class="ebnf">
5715
SourceFile       = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
5716
</pre>
5717

5718
<h3 id="Package_clause">Package clause</h3>
Rob Pike's avatar
Rob Pike committed
5719

5720
<p>
Rob Pike's avatar
Rob Pike committed
5721 5722 5723
A package clause begins each source file and defines the package
to which the file belongs.
</p>
5724

5725
<pre class="ebnf">
Robert Griesemer's avatar
Robert Griesemer committed
5726 5727
PackageClause  = "package" PackageName .
PackageName    = identifier .
Rob Pike's avatar
Rob Pike committed
5728
</pre>
5729

Robert Griesemer's avatar
Robert Griesemer committed
5730 5731 5732 5733
<p>
The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>.
</p>

Rob Pike's avatar
Rob Pike committed
5734 5735
<pre>
package math
5736
</pre>
5737

Rob Pike's avatar
Rob Pike committed
5738 5739 5740 5741
<p>
A set of files sharing the same PackageName form the implementation of a package.
An implementation may require that all source files for a package inhabit the same directory.
</p>
5742

5743
<h3 id="Import_declarations">Import declarations</h3>
Rob Pike's avatar
Rob Pike committed
5744 5745

<p>
5746 5747 5748
An import declaration states that the source file containing the declaration
depends on functionality of the <i>imported</i> package
(<a href="#Program_initialization_and_execution">§Program initialization and execution</a>)
5749
and enables access to <a href="#Exported_identifiers">exported</a> identifiers
5750 5751
of that package.
The import names an identifier (PackageName) to be used for access and an ImportPath
Rob Pike's avatar
Rob Pike committed
5752
that specifies the package to be imported.
Rob Pike's avatar
Rob Pike committed
5753
</p>
5754

5755
<pre class="ebnf">
5756
ImportDecl       = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
5757
ImportSpec       = [ "." | PackageName ] ImportPath .
5758
ImportPath       = string_lit .
5759
</pre>
5760

5761
<p>
Rob Pike's avatar
Rob Pike committed
5762
The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a>
5763
to access exported identifiers of the package within the importing source file.
Rob Pike's avatar
Rob Pike committed
5764 5765
It is declared in the <a href="#Blocks">file block</a>.
If the PackageName is omitted, it defaults to the identifier specified in the
Robert Griesemer's avatar
Robert Griesemer committed
5766
<a href="#Package_clause">package clause</a> of the imported package.
Rob Pike's avatar
Rob Pike committed
5767
If an explicit period (<code>.</code>) appears instead of a name, all the
5768 5769
package's exported identifiers declared in that package's
<a href="#Blocks">package block</a> will be declared in the importing source
5770
file's file block and must be accessed without a qualifier.
Rob Pike's avatar
Rob Pike committed
5771 5772 5773 5774 5775 5776
</p>

<p>
The interpretation of the ImportPath is implementation-dependent but
it is typically a substring of the full file name of the compiled
package and may be relative to a repository of installed packages.
Rob Pike's avatar
Rob Pike committed
5777
</p>
Russ Cox's avatar
Russ Cox committed
5778

5779 5780 5781
<p>
Implementation restriction: A compiler may restrict ImportPaths to
non-empty strings using only characters belonging to
5782
<a href="http://www.unicode.org/versions/Unicode6.3.0/">Unicode's</a>
5783
L, M, N, P, and S general categories (the Graphic characters without
5784 5785 5786
spaces) and may also exclude the characters
<code>!"#$%&amp;'()*,:;&lt;=&gt;?[\]^`{|}</code>
and the Unicode replacement character U+FFFD.
5787 5788
</p>

5789
<p>
Rob Pike's avatar
Rob Pike committed
5790 5791 5792
Assume we have compiled a package containing the package clause
<code>package math</code>, which exports function <code>Sin</code>, and
installed the compiled package in the file identified by
Rob Pike's avatar
Rob Pike committed
5793
<code>"lib/math"</code>.
5794
This table illustrates how <code>Sin</code> is accessed in files
Rob Pike's avatar
Rob Pike committed
5795 5796
that import the package after the
various types of import declaration.
Rob Pike's avatar
Rob Pike committed
5797
</p>
5798

Rob Pike's avatar
Rob Pike committed
5799
<pre class="grammar">
5800
Import declaration          Local name of Sin
Rob Pike's avatar
Rob Pike committed
5801 5802

import   "lib/math"         math.Sin
5803
import m "lib/math"         m.Sin
Rob Pike's avatar
Rob Pike committed
5804
import . "lib/math"         Sin
5805
</pre>
5806

5807
<p>
Rob Pike's avatar
Rob Pike committed
5808 5809
An import declaration declares a dependency relation between
the importing and imported package.
5810 5811
It is illegal for a package to import itself, directly or indirectly,
or to directly import a package without
5812 5813 5814 5815 5816 5817 5818 5819 5820 5821
referring to any of its exported identifiers. To import a package solely for
its side-effects (initialization), use the <a href="#Blank_identifier">blank</a>
identifier as explicit package name:
</p>

<pre>
import _ "lib/math"
</pre>


5822
<h3 id="An_example_package">An example package</h3>
Rob Pike's avatar
Rob Pike committed
5823 5824 5825 5826

<p>
Here is a complete Go package that implements a concurrent prime sieve.
</p>
5827

5828 5829 5830
<pre>
package main

Rob Pike's avatar
Rob Pike committed
5831 5832
import "fmt"

5833
// Send the sequence 2, 3, 4, … to channel 'ch'.
5834
func generate(ch chan&lt;- int) {
5835
	for i := 2; ; i++ {
5836
		ch &lt;- i  // Send 'i' to channel 'ch'.
5837
	}
5838 5839
}

Fazlul Shahriar's avatar
Fazlul Shahriar committed
5840
// Copy the values from channel 'src' to channel 'dst',
5841
// removing those divisible by 'prime'.
5842
func filter(src &lt;-chan int, dst chan&lt;- int, prime int) {
5843
	for i := range src {  // Loop over values received from 'src'.
5844
		if i%prime != 0 {
5845
			dst &lt;- i  // Send 'i' to channel 'dst'.
5846 5847
		}
	}
5848 5849 5850 5851
}

// The prime sieve: Daisy-chain filter processes together.
func sieve() {
5852 5853
	ch := make(chan int)  // Create a new channel.
	go generate(ch)       // Start generate() as a subprocess.
5854
	for {
5855 5856 5857 5858 5859
		prime := &lt;-ch
		fmt.Print(prime, "\n")
		ch1 := make(chan int)
		go filter(ch, ch1, prime)
		ch = ch1
5860
	}
5861
}
5862

5863
func main() {
5864
	sieve()
5865 5866
}
</pre>
5867

5868
<h2 id="Program_initialization_and_execution">Program initialization and execution</h2>
5869

5870
<h3 id="The_zero_value">The zero value</h3>
Rob Pike's avatar
Rob Pike committed
5871
<p>
5872
When memory is allocated to store a value, either through a declaration
5873
or a call of <code>make</code> or <code>new</code>,
Rob Pike's avatar
Rob Pike committed
5874
and no explicit initialization is provided, the memory is
5875
given a default initialization.  Each element of such a value is
5876
set to the <i>zero value</i> for its type: <code>false</code> for booleans,
Rob Pike's avatar
Rob Pike committed
5877
<code>0</code> for integers, <code>0.0</code> for floats, <code>""</code>
5878
for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps.
Rob Pike's avatar
Rob Pike committed
5879
This initialization is done recursively, so for instance each element of an
Rob Pike's avatar
Rob Pike committed
5880 5881
array of structs will have its fields zeroed if no value is specified.
</p>
5882
<p>
5883
These two simple declarations are equivalent:
Rob Pike's avatar
Rob Pike committed
5884
</p>
5885

5886
<pre>
5887 5888
var i int
var i int = 0
5889
</pre>
5890

Rob Pike's avatar
Rob Pike committed
5891
<p>
5892
After
Rob Pike's avatar
Rob Pike committed
5893
</p>
5894

5895
<pre>
5896
type T struct { i int; f float64; next *T }
5897
t := new(T)
5898
</pre>
5899

Rob Pike's avatar
Rob Pike committed
5900
<p>
5901
the following holds:
Rob Pike's avatar
Rob Pike committed
5902
</p>
5903

5904 5905 5906 5907 5908
<pre>
t.i == 0
t.f == 0.0
t.next == nil
</pre>
5909

Rob Pike's avatar
Rob Pike committed
5910 5911 5912 5913 5914 5915 5916 5917
<p>
The same would also be true after
</p>

<pre>
var t T
</pre>

5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944
<h3 id="Package_initialization">Package initialization</h3>
<p>
Within a package, package-level variables are initialized according
to their <i>dependencies</i>: if a variable <code>x</code> depends on
a variable <code>y</code>, <code>x</code> will be initialized after
<code>y</code>.
</p>

<p>
Dependency analysis does not rely on the actual values of the
variables, only on lexical <i>references</i> to them in the source,
analyzed transitively. For instance, a variable <code>x</code>'s
<a href="#Variable_declarations">initialization expression</a>
may refer to a function whose body refers to variable <code>y</code>;
if so, <code>x</code> depends on <code>y</code>.
Specifically:
</p>

<ul>
<li>
A reference to a variable or function is an identifier denoting that
variable or function.
</li>

<li>
A reference to a method <code>m</code> is a
<a href="#Method_values">method value</a> or
5945
<a href="#Method_expressions">method expression</a> of the form
5946 5947 5948 5949 5950 5951 5952 5953
<code>t.m</code>, where the (static) type of <code>t</code> is
not an interface type, and the method <code>m</code> is in the
<a href="#Method_sets">method set</a> of <code>t</code>.
It is immaterial whether the resulting function value
<code>t.m</code> is invoked.
</li>

<li>
5954
A variable, function, or method <code>x</code> depends on a variable
5955 5956 5957 5958 5959 5960
<code>y</code> if <code>x</code>'s initialization expression or body
(for functions and methods) contains a reference to <code>y</code>
or to a function or method that depends on <code>y</code>.
</li>
</ul>

Rob Pike's avatar
Rob Pike committed
5961
<p>
5962 5963 5964 5965 5966 5967 5968 5969
Dependency analysis is performed per package; only references referring
to variables, functions, and methods declared in the current package
are considered.
It is an error if variable dependencies form a cycle
(but dependency cycles containing no variables are permitted).
If two variables are independent of each other,
they are initialized in the order they are declared
in the source, possibly in multiple files, as presented to the compiler.
Rob Pike's avatar
Rob Pike committed
5970
</p>
5971 5972 5973 5974 5975

<p>
For example, given the declarations
</p>

Rob Pike's avatar
Rob Pike committed
5976
<pre>
5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987
var (
	a = c + b
	b = f()
	c = f()
	d = 3
)

func f() int {
	d++
	return d
}
Rob Pike's avatar
Rob Pike committed
5988
</pre>
5989

Rob Pike's avatar
Rob Pike committed
5990
<p>
5991 5992 5993
the initialization order is <code>d</code>, <code>b</code>, <code>c</code>, <code>a</code>.
Since <code>b</code> and <code>c</code> are independent of each other, they are
initialized in declaration order (<code>b</code> before <code>c</code>).
Rob Pike's avatar
Rob Pike committed
5994
</p>
5995

5996
<p>
5997 5998
Variables may also be initialized using functions named <code>init</code>
declared in the package block, with no arguments and no result parameters.
5999
</p>
6000 6001 6002 6003 6004

<pre>
func init() { … }
</pre>

6005
<p>
6006
Multiple such functions may be defined, even within a single
6007 6008 6009 6010
source file. The <code>init</code> identifier is not
<a href="#Declarations_and_scope">declared</a> and thus
<code>init</code> functions cannot be referred to from anywhere
in a program.
Rob Pike's avatar
Rob Pike committed
6011
</p>
6012

6013
<p>
6014 6015
A package with no imports is initialized by assigning initial values
to all its package-level variables followed by calling all <code>init</code>
6016 6017
functions in the order they appear in the source, possibly in multiple files,
as presented to the compiler.
6018
If a package has imports, the imported packages are initialized
6019
before initializing the package itself. If multiple packages import
6020 6021 6022
a package, the imported package will be initialized only once.
The importing of packages, by construction, guarantees that there
can be no cyclic initialization dependencies.
Rob Pike's avatar
Rob Pike committed
6023
</p>
6024

6025
<p>
6026 6027 6028 6029 6030 6031 6032 6033
Package initialization&mdash;variable initialization and the invocation of
<code>init</code> functions&mdash;happens in a single goroutine,
sequentially, one package at a time.
An <code>init</code> function may launch other goroutines, which can run
concurrently with the initialization code. However, initialization
always sequences
the <code>init</code> functions: it will not invoke the next one
until the previous one has returned.
Rob Pike's avatar
Rob Pike committed
6034
</p>
6035 6036 6037


<h3 id="Program_execution">Program execution</h3>
6038
<p>
6039 6040 6041 6042
A complete program is created by linking a single, unimported package
called the <i>main package</i> with all the packages it imports, transitively.
The main package must
have package name <code>main</code> and
6043
declare a function <code>main</code> that takes no
6044
arguments and returns no value.
Rob Pike's avatar
Rob Pike committed
6045
</p>
6046

6047
<pre>
6048
func main() { … }
6049
</pre>
6050

Rob Pike's avatar
Rob Pike committed
6051
<p>
6052 6053
Program execution begins by initializing the main package and then
invoking the function <code>main</code>.
6054
When that function invocation returns, the program exits.
6055
It does not wait for other (non-<code>main</code>) goroutines to complete.
Rob Pike's avatar
Rob Pike committed
6056
</p>
6057

Russ Cox's avatar
Russ Cox committed
6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079
<h2 id="Errors">Errors</h2>

<p>
The predeclared type <code>error</code> is defined as
</p>

<pre>
type error interface {
	Error() string
}
</pre>

<p>
It is the conventional interface for representing an error condition,
with the nil value representing no error.
For instance, a function to read data from a file might be defined:
</p>

<pre>
func Read(f *File, b []byte) (n int, err error)
</pre>

Evan Shaw's avatar
Evan Shaw committed
6080
<h2 id="Run_time_panics">Run-time panics</h2>
Rob Pike's avatar
Rob Pike committed
6081 6082 6083 6084 6085 6086

<p>
Execution errors such as attempting to index an array out
of bounds trigger a <i>run-time panic</i> equivalent to a call of
the built-in function <a href="#Handling_panics"><code>panic</code></a>
with a value of the implementation-defined interface type <code>runtime.Error</code>.
6087
That type satisfies the predeclared interface type
Russ Cox's avatar
Russ Cox committed
6088 6089 6090
<a href="#Errors"><code>error</code></a>.
The exact error values that
represent distinct run-time error conditions are unspecified.
Rob Pike's avatar
Rob Pike committed
6091 6092 6093 6094 6095 6096
</p>

<pre>
package runtime

type Error interface {
Russ Cox's avatar
Russ Cox committed
6097 6098
	error
	// and perhaps other methods
Rob Pike's avatar
Rob Pike committed
6099 6100 6101
}
</pre>

6102
<h2 id="System_considerations">System considerations</h2>
6103

6104
<h3 id="Package_unsafe">Package <code>unsafe</code></h3>
6105

6106
<p>
Rob Pike's avatar
Rob Pike committed
6107 6108 6109 6110 6111
The built-in package <code>unsafe</code>, known to the compiler,
provides facilities for low-level programming including operations
that violate the type system. A package using <code>unsafe</code>
must be vetted manually for type safety.  The package provides the
following interface:
6112
</p>
6113

Rob Pike's avatar
Rob Pike committed
6114
<pre class="grammar">
6115
package unsafe
6116

6117 6118
type ArbitraryType int  // shorthand for an arbitrary Go type; it is not a real type
type Pointer *ArbitraryType
6119

6120
func Alignof(variable ArbitraryType) uintptr
Hong Ruiqi's avatar
Hong Ruiqi committed
6121
func Offsetof(selector ArbitraryType) uintptr
6122
func Sizeof(variable ArbitraryType) uintptr
6123
</pre>
6124

6125
<p>
6126 6127
Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to
a <code>Pointer</code> type and vice versa.
6128 6129
A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code>
value may not be <a href="#Address_operators">dereferenced</a>.
6130
</p>
6131 6132 6133 6134 6135 6136 6137

<pre>
var f float64
bits = *(*uint64)(unsafe.Pointer(&amp;f))

type ptr unsafe.Pointer
bits = *(*uint64)(ptr(&amp;f))
6138 6139

var p ptr = nil
6140 6141
</pre>

6142
<p>
6143 6144 6145
The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code>
of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code>
as if <code>v</code> was declared via <code>var v = x</code>.
6146
</p>
6147
<p>
6148
The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a>
6149 6150 6151 6152
<code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code>
or <code>*s</code>, and returns the field offset in bytes relative to the struct's address.
If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable
without pointer indirections through fields of the struct.
Rob Pike's avatar
Rob Pike committed
6153
For a struct <code>s</code> with field <code>f</code>:
6154
</p>
6155

6156
<pre>
6157
uintptr(unsafe.Pointer(&amp;s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&amp;s.f))
6158
</pre>
6159

6160
<p>
6161 6162 6163 6164 6165 6166 6167
Computer architectures may require memory addresses to be <i>aligned</i>;
that is, for addresses of a variable to be a multiple of a factor,
the variable's type's <i>alignment</i>.  The function <code>Alignof</code>
takes an expression denoting a variable of any type and returns the
alignment of the (type of the) variable in bytes.  For a variable
<code>x</code>:
</p>
6168

6169
<pre>
6170
uintptr(unsafe.Pointer(&amp;x)) % unsafe.Alignof(x) == 0
6171
</pre>
6172

6173 6174
<p>
Calls to <code>Alignof</code>, <code>Offsetof</code>, and
6175
<code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>.
Rob Pike's avatar
Rob Pike committed
6176
</p>
6177

6178
<h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3>
6179

6180
<p>
6181
For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed:
6182
</p>
6183

Rob Pike's avatar
Rob Pike committed
6184
<pre class="grammar">
6185
type                                 size in bytes
6186

6187 6188 6189 6190 6191
byte, uint8, int8                     1
uint16, int16                         2
uint32, int32, float32                4
uint64, int64, float64, complex64     8
complex128                           16
6192
</pre>
6193

6194
<p>
6195
The following minimal alignment properties are guaranteed:
Rob Pike's avatar
Rob Pike committed
6196
</p>
6197
<ol>
6198
<li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1.
6199
</li>
6200

6201
<li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of
6202
   all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1.
6203
</li>
6204

6205 6206
<li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as
   <code>unsafe.Alignof(x[0])</code>, but at least 1.
6207
</li>
6208
</ol>
6209

6210 6211 6212
<p>
A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory.
</p>