]> Cypherpunks.ru repositories - gostls13.git/blob - doc/go1.17_spec.html
cmd/compile/internal/inline: score call sites exposed by inlines
[gostls13.git] / doc / go1.17_spec.html
1 <!--{
2         "Title": "The Go Programming Language Specification",
3         "Subtitle": "Version of Oct 15, 2021",
4         "Path": "/ref/spec"
5 }-->
6
7 <h2 id="Introduction">Introduction</h2>
8
9 <p>
10 This is a reference manual for the Go programming language. For
11 more information and other documents, see <a href="/">golang.org</a>.
12 </p>
13
14 <p>
15 Go is a general-purpose language designed with systems programming
16 in mind. It is strongly typed and garbage-collected and has explicit
17 support for concurrent programming.  Programs are constructed from
18 <i>packages</i>, whose properties allow efficient management of
19 dependencies.
20 </p>
21
22 <p>
23 The grammar is compact and simple to parse, allowing for easy analysis
24 by automatic tools such as integrated development environments.
25 </p>
26
27 <h2 id="Notation">Notation</h2>
28 <p>
29 The syntax is specified using Extended Backus-Naur Form (EBNF):
30 </p>
31
32 <pre class="grammar">
33 Production  = production_name "=" [ Expression ] "." .
34 Expression  = Alternative { "|" Alternative } .
35 Alternative = Term { Term } .
36 Term        = production_name | token [ "…" token ] | Group | Option | Repetition .
37 Group       = "(" Expression ")" .
38 Option      = "[" Expression "]" .
39 Repetition  = "{" Expression "}" .
40 </pre>
41
42 <p>
43 Productions are expressions constructed from terms and the following
44 operators, in increasing precedence:
45 </p>
46 <pre class="grammar">
47 |   alternation
48 ()  grouping
49 []  option (0 or 1 times)
50 {}  repetition (0 to n times)
51 </pre>
52
53 <p>
54 Lower-case production names are used to identify lexical tokens.
55 Non-terminals are in CamelCase. Lexical tokens are enclosed in
56 double quotes <code>""</code> or back quotes <code>``</code>.
57 </p>
58
59 <p>
60 The form <code>a … b</code> represents the set of characters from
61 <code>a</code> through <code>b</code> as alternatives. The horizontal
62 ellipsis <code>…</code> is also used elsewhere in the spec to informally denote various
63 enumerations or code snippets that are not further specified. The character <code>…</code>
64 (as opposed to the three characters <code>...</code>) is not a token of the Go
65 language.
66 </p>
67
68 <h2 id="Source_code_representation">Source code representation</h2>
69
70 <p>
71 Source code is Unicode text encoded in
72 <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. The text is not
73 canonicalized, so a single accented code point is distinct from the
74 same character constructed from combining an accent and a letter;
75 those are treated as two code points.  For simplicity, this document
76 will use the unqualified term <i>character</i> to refer to a Unicode code point
77 in the source text.
78 </p>
79 <p>
80 Each code point is distinct; for instance, upper and lower case letters
81 are different characters.
82 </p>
83 <p>
84 Implementation restriction: For compatibility with other tools, a
85 compiler may disallow the NUL character (U+0000) in the source text.
86 </p>
87 <p>
88 Implementation restriction: For compatibility with other tools, a
89 compiler may ignore a UTF-8-encoded byte order mark
90 (U+FEFF) if it is the first Unicode code point in the source text.
91 A byte order mark may be disallowed anywhere else in the source.
92 </p>
93
94 <h3 id="Characters">Characters</h3>
95
96 <p>
97 The following terms are used to denote specific Unicode character classes:
98 </p>
99 <pre class="ebnf">
100 newline        = /* the Unicode code point U+000A */ .
101 unicode_char   = /* an arbitrary Unicode code point except newline */ .
102 unicode_letter = /* a Unicode code point classified as "Letter" */ .
103 unicode_digit  = /* a Unicode code point classified as "Number, decimal digit" */ .
104 </pre>
105
106 <p>
107 In <a href="https://www.unicode.org/versions/Unicode8.0.0/">The Unicode Standard 8.0</a>,
108 Section 4.5 "General Category" defines a set of character categories.
109 Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo
110 as Unicode letters, and those in the Number category Nd as Unicode digits.
111 </p>
112
113 <h3 id="Letters_and_digits">Letters and digits</h3>
114
115 <p>
116 The underscore character <code>_</code> (U+005F) is considered a letter.
117 </p>
118 <pre class="ebnf">
119 letter        = unicode_letter | "_" .
120 decimal_digit = "0" … "9" .
121 binary_digit  = "0" | "1" .
122 octal_digit   = "0" … "7" .
123 hex_digit     = "0" … "9" | "A" … "F" | "a" … "f" .
124 </pre>
125
126 <h2 id="Lexical_elements">Lexical elements</h2>
127
128 <h3 id="Comments">Comments</h3>
129
130 <p>
131 Comments serve as program documentation. There are two forms:
132 </p>
133
134 <ol>
135 <li>
136 <i>Line comments</i> start with the character sequence <code>//</code>
137 and stop at the end of the line.
138 </li>
139 <li>
140 <i>General comments</i> start with the character sequence <code>/*</code>
141 and stop with the first subsequent character sequence <code>*/</code>.
142 </li>
143 </ol>
144
145 <p>
146 A comment cannot start inside a <a href="#Rune_literals">rune</a> or
147 <a href="#String_literals">string literal</a>, or inside a comment.
148 A general comment containing no newlines acts like a space.
149 Any other comment acts like a newline.
150 </p>
151
152 <h3 id="Tokens">Tokens</h3>
153
154 <p>
155 Tokens form the vocabulary of the Go language.
156 There are four classes: <i>identifiers</i>, <i>keywords</i>, <i>operators
157 and punctuation</i>, and <i>literals</i>.  <i>White space</i>, formed from
158 spaces (U+0020), horizontal tabs (U+0009),
159 carriage returns (U+000D), and newlines (U+000A),
160 is ignored except as it separates tokens
161 that would otherwise combine into a single token. Also, a newline or end of file
162 may trigger the insertion of a <a href="#Semicolons">semicolon</a>.
163 While breaking the input into tokens,
164 the next token is the longest sequence of characters that form a
165 valid token.
166 </p>
167
168 <h3 id="Semicolons">Semicolons</h3>
169
170 <p>
171 The formal grammar uses semicolons <code>";"</code> as terminators in
172 a number of productions. Go programs may omit most of these semicolons
173 using the following two rules:
174 </p>
175
176 <ol>
177 <li>
178 When the input is broken into tokens, a semicolon is automatically inserted
179 into the token stream immediately after a line's final token if that token is
180 <ul>
181         <li>an
182             <a href="#Identifiers">identifier</a>
183         </li>
184
185         <li>an
186             <a href="#Integer_literals">integer</a>,
187             <a href="#Floating-point_literals">floating-point</a>,
188             <a href="#Imaginary_literals">imaginary</a>,
189             <a href="#Rune_literals">rune</a>, or
190             <a href="#String_literals">string</a> literal
191         </li>
192
193         <li>one of the <a href="#Keywords">keywords</a>
194             <code>break</code>,
195             <code>continue</code>,
196             <code>fallthrough</code>, or
197             <code>return</code>
198         </li>
199
200         <li>one of the <a href="#Operators_and_punctuation">operators and punctuation</a>
201             <code>++</code>,
202             <code>--</code>,
203             <code>)</code>,
204             <code>]</code>, or
205             <code>}</code>
206         </li>
207 </ul>
208 </li>
209
210 <li>
211 To allow complex statements to occupy a single line, a semicolon
212 may be omitted before a closing <code>")"</code> or <code>"}"</code>.
213 </li>
214 </ol>
215
216 <p>
217 To reflect idiomatic use, code examples in this document elide semicolons
218 using these rules.
219 </p>
220
221
222 <h3 id="Identifiers">Identifiers</h3>
223
224 <p>
225 Identifiers name program entities such as variables and types.
226 An identifier is a sequence of one or more letters and digits.
227 The first character in an identifier must be a letter.
228 </p>
229 <pre class="ebnf">
230 identifier = letter { letter | unicode_digit } .
231 </pre>
232 <pre>
233 a
234 _x9
235 ThisVariableIsExported
236 αβ
237 </pre>
238
239 <p>
240 Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>.
241 </p>
242
243
244 <h3 id="Keywords">Keywords</h3>
245
246 <p>
247 The following keywords are reserved and may not be used as identifiers.
248 </p>
249 <pre class="grammar">
250 break        default      func         interface    select
251 case         defer        go           map          struct
252 chan         else         goto         package      switch
253 const        fallthrough  if           range        type
254 continue     for          import       return       var
255 </pre>
256
257 <h3 id="Operators_and_punctuation">Operators and punctuation</h3>
258
259 <p>
260 The following character sequences represent <a href="#Operators">operators</a>
261 (including <a href="#Assignments">assignment operators</a>) and punctuation:
262 </p>
263 <pre class="grammar">
264 +    &amp;     +=    &amp;=     &amp;&amp;    ==    !=    (    )
265 -    |     -=    |=     ||    &lt;     &lt;=    [    ]
266 *    ^     *=    ^=     &lt;-    &gt;     &gt;=    {    }
267 /    &lt;&lt;    /=    &lt;&lt;=    ++    =     :=    ,    ;
268 %    &gt;&gt;    %=    &gt;&gt;=    --    !     ...   .    :
269      &amp;^          &amp;^=
270 </pre>
271
272 <h3 id="Integer_literals">Integer literals</h3>
273
274 <p>
275 An integer literal is a sequence of digits representing an
276 <a href="#Constants">integer constant</a>.
277 An optional prefix sets a non-decimal base: <code>0b</code> or <code>0B</code>
278 for binary, <code>0</code>, <code>0o</code>, or <code>0O</code> for octal,
279 and <code>0x</code> or <code>0X</code> for hexadecimal.
280 A single <code>0</code> is considered a decimal zero.
281 In hexadecimal literals, letters <code>a</code> through <code>f</code>
282 and <code>A</code> through <code>F</code> represent values 10 through 15.
283 </p>
284
285 <p>
286 For readability, an underscore character <code>_</code> may appear after
287 a base prefix or between successive digits; such underscores do not change
288 the literal's value.
289 </p>
290 <pre class="ebnf">
291 int_lit        = decimal_lit | binary_lit | octal_lit | hex_lit .
292 decimal_lit    = "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] .
293 binary_lit     = "0" ( "b" | "B" ) [ "_" ] binary_digits .
294 octal_lit      = "0" [ "o" | "O" ] [ "_" ] octal_digits .
295 hex_lit        = "0" ( "x" | "X" ) [ "_" ] hex_digits .
296
297 decimal_digits = decimal_digit { [ "_" ] decimal_digit } .
298 binary_digits  = binary_digit { [ "_" ] binary_digit } .
299 octal_digits   = octal_digit { [ "_" ] octal_digit } .
300 hex_digits     = hex_digit { [ "_" ] hex_digit } .
301 </pre>
302
303 <pre>
304 42
305 4_2
306 0600
307 0_600
308 0o600
309 0O600       // second character is capital letter 'O'
310 0xBadFace
311 0xBad_Face
312 0x_67_7a_2f_cc_40_c6
313 170141183460469231731687303715884105727
314 170_141183_460469_231731_687303_715884_105727
315
316 _42         // an identifier, not an integer literal
317 42_         // invalid: _ must separate successive digits
318 4__2        // invalid: only one _ at a time
319 0_xBadFace  // invalid: _ must separate successive digits
320 </pre>
321
322
323 <h3 id="Floating-point_literals">Floating-point literals</h3>
324
325 <p>
326 A floating-point literal is a decimal or hexadecimal representation of a
327 <a href="#Constants">floating-point constant</a>.
328 </p>
329
330 <p>
331 A decimal floating-point literal consists of an integer part (decimal digits),
332 a decimal point, a fractional part (decimal digits), and an exponent part
333 (<code>e</code> or <code>E</code> followed by an optional sign and decimal digits).
334 One of the integer part or the fractional part may be elided; one of the decimal point
335 or the exponent part may be elided.
336 An exponent value exp scales the mantissa (integer and fractional part) by 10<sup>exp</sup>.
337 </p>
338
339 <p>
340 A hexadecimal floating-point literal consists of a <code>0x</code> or <code>0X</code>
341 prefix, an integer part (hexadecimal digits), a radix point, a fractional part (hexadecimal digits),
342 and an exponent part (<code>p</code> or <code>P</code> followed by an optional sign and decimal digits).
343 One of the integer part or the fractional part may be elided; the radix point may be elided as well,
344 but the exponent part is required. (This syntax matches the one given in IEEE 754-2008 §5.12.3.)
345 An exponent value exp scales the mantissa (integer and fractional part) by 2<sup>exp</sup>.
346 </p>
347
348 <p>
349 For readability, an underscore character <code>_</code> may appear after
350 a base prefix or between successive digits; such underscores do not change
351 the literal value.
352 </p>
353
354 <pre class="ebnf">
355 float_lit         = decimal_float_lit | hex_float_lit .
356
357 decimal_float_lit = decimal_digits "." [ decimal_digits ] [ decimal_exponent ] |
358                     decimal_digits decimal_exponent |
359                     "." decimal_digits [ decimal_exponent ] .
360 decimal_exponent  = ( "e" | "E" ) [ "+" | "-" ] decimal_digits .
361
362 hex_float_lit     = "0" ( "x" | "X" ) hex_mantissa hex_exponent .
363 hex_mantissa      = [ "_" ] hex_digits "." [ hex_digits ] |
364                     [ "_" ] hex_digits |
365                     "." hex_digits .
366 hex_exponent      = ( "p" | "P" ) [ "+" | "-" ] decimal_digits .
367 </pre>
368
369 <pre>
370 0.
371 72.40
372 072.40       // == 72.40
373 2.71828
374 1.e+0
375 6.67428e-11
376 1E6
377 .25
378 .12345E+5
379 1_5.         // == 15.0
380 0.15e+0_2    // == 15.0
381
382 0x1p-2       // == 0.25
383 0x2.p10      // == 2048.0
384 0x1.Fp+0     // == 1.9375
385 0X.8p-0      // == 0.5
386 0X_1FFFP-16  // == 0.1249847412109375
387 0x15e-2      // == 0x15e - 2 (integer subtraction)
388
389 0x.p1        // invalid: mantissa has no digits
390 1p-2         // invalid: p exponent requires hexadecimal mantissa
391 0x1.5e-2     // invalid: hexadecimal mantissa requires p exponent
392 1_.5         // invalid: _ must separate successive digits
393 1._5         // invalid: _ must separate successive digits
394 1.5_e1       // invalid: _ must separate successive digits
395 1.5e_1       // invalid: _ must separate successive digits
396 1.5e1_       // invalid: _ must separate successive digits
397 </pre>
398
399
400 <h3 id="Imaginary_literals">Imaginary literals</h3>
401
402 <p>
403 An imaginary literal represents the imaginary part of a
404 <a href="#Constants">complex constant</a>.
405 It consists of an <a href="#Integer_literals">integer</a> or
406 <a href="#Floating-point_literals">floating-point</a> literal
407 followed by the lower-case letter <code>i</code>.
408 The value of an imaginary literal is the value of the respective
409 integer or floating-point literal multiplied by the imaginary unit <i>i</i>.
410 </p>
411
412 <pre class="ebnf">
413 imaginary_lit = (decimal_digits | int_lit | float_lit) "i" .
414 </pre>
415
416 <p>
417 For backward compatibility, an imaginary literal's integer part consisting
418 entirely of decimal digits (and possibly underscores) is considered a decimal
419 integer, even if it starts with a leading <code>0</code>.
420 </p>
421
422 <pre>
423 0i
424 0123i         // == 123i for backward-compatibility
425 0o123i        // == 0o123 * 1i == 83i
426 0xabci        // == 0xabc * 1i == 2748i
427 0.i
428 2.71828i
429 1.e+0i
430 6.67428e-11i
431 1E6i
432 .25i
433 .12345E+5i
434 0x1p-2i       // == 0x1p-2 * 1i == 0.25i
435 </pre>
436
437
438 <h3 id="Rune_literals">Rune literals</h3>
439
440 <p>
441 A rune literal represents a <a href="#Constants">rune constant</a>,
442 an integer value identifying a Unicode code point.
443 A rune literal is expressed as one or more characters enclosed in single quotes,
444 as in <code>'x'</code> or <code>'\n'</code>.
445 Within the quotes, any character may appear except newline and unescaped single
446 quote. A single quoted character represents the Unicode value
447 of the character itself,
448 while multi-character sequences beginning with a backslash encode
449 values in various formats.
450 </p>
451
452 <p>
453 The simplest form represents the single character within the quotes;
454 since Go source text is Unicode characters encoded in UTF-8, multiple
455 UTF-8-encoded bytes may represent a single integer value.  For
456 instance, the literal <code>'a'</code> holds a single byte representing
457 a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while
458 <code>'ä'</code> holds two bytes (<code>0xc3</code> <code>0xa4</code>) representing
459 a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>.
460 </p>
461
462 <p>
463 Several backslash escapes allow arbitrary values to be encoded as
464 ASCII text.  There are four ways to represent the integer value
465 as a numeric constant: <code>\x</code> followed by exactly two hexadecimal
466 digits; <code>\u</code> followed by exactly four hexadecimal digits;
467 <code>\U</code> followed by exactly eight hexadecimal digits, and a
468 plain backslash <code>\</code> followed by exactly three octal digits.
469 In each case the value of the literal is the value represented by
470 the digits in the corresponding base.
471 </p>
472
473 <p>
474 Although these representations all result in an integer, they have
475 different valid ranges.  Octal escapes must represent a value between
476 0 and 255 inclusive.  Hexadecimal escapes satisfy this condition
477 by construction. The escapes <code>\u</code> and <code>\U</code>
478 represent Unicode code points so within them some values are illegal,
479 in particular those above <code>0x10FFFF</code> and surrogate halves.
480 </p>
481
482 <p>
483 After a backslash, certain single-character escapes represent special values:
484 </p>
485
486 <pre class="grammar">
487 \a   U+0007 alert or bell
488 \b   U+0008 backspace
489 \f   U+000C form feed
490 \n   U+000A line feed or newline
491 \r   U+000D carriage return
492 \t   U+0009 horizontal tab
493 \v   U+000B vertical tab
494 \\   U+005C backslash
495 \'   U+0027 single quote  (valid escape only within rune literals)
496 \"   U+0022 double quote  (valid escape only within string literals)
497 </pre>
498
499 <p>
500 All other sequences starting with a backslash are illegal inside rune literals.
501 </p>
502 <pre class="ebnf">
503 rune_lit         = "'" ( unicode_value | byte_value ) "'" .
504 unicode_value    = unicode_char | little_u_value | big_u_value | escaped_char .
505 byte_value       = octal_byte_value | hex_byte_value .
506 octal_byte_value = `\` octal_digit octal_digit octal_digit .
507 hex_byte_value   = `\` "x" hex_digit hex_digit .
508 little_u_value   = `\` "u" hex_digit hex_digit hex_digit hex_digit .
509 big_u_value      = `\` "U" hex_digit hex_digit hex_digit hex_digit
510                            hex_digit hex_digit hex_digit hex_digit .
511 escaped_char     = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
512 </pre>
513
514 <pre>
515 'a'
516 'ä'
517 '本'
518 '\t'
519 '\000'
520 '\007'
521 '\377'
522 '\x07'
523 '\xff'
524 '\u12e4'
525 '\U00101234'
526 '\''         // rune literal containing single quote character
527 'aa'         // illegal: too many characters
528 '\xa'        // illegal: too few hexadecimal digits
529 '\0'         // illegal: too few octal digits
530 '\uDFFF'     // illegal: surrogate half
531 '\U00110000' // illegal: invalid Unicode code point
532 </pre>
533
534
535 <h3 id="String_literals">String literals</h3>
536
537 <p>
538 A string literal represents a <a href="#Constants">string constant</a>
539 obtained from concatenating a sequence of characters. There are two forms:
540 raw string literals and interpreted string literals.
541 </p>
542
543 <p>
544 Raw string literals are character sequences between back quotes, as in
545 <code>`foo`</code>.  Within the quotes, any character may appear except
546 back quote. The value of a raw string literal is the
547 string composed of the uninterpreted (implicitly UTF-8-encoded) characters
548 between the quotes;
549 in particular, backslashes have no special meaning and the string may
550 contain newlines.
551 Carriage return characters ('\r') inside raw string literals
552 are discarded from the raw string value.
553 </p>
554
555 <p>
556 Interpreted string literals are character sequences between double
557 quotes, as in <code>&quot;bar&quot;</code>.
558 Within the quotes, any character may appear except newline and unescaped double quote.
559 The text between the quotes forms the
560 value of the literal, with backslash escapes interpreted as they
561 are in <a href="#Rune_literals">rune literals</a> (except that <code>\'</code> is illegal and
562 <code>\"</code> is legal), with the same restrictions.
563 The three-digit octal (<code>\</code><i>nnn</i>)
564 and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual
565 <i>bytes</i> of the resulting string; all other escapes represent
566 the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
567 Thus inside a string literal <code>\377</code> and <code>\xFF</code> represent
568 a single byte of value <code>0xFF</code>=255, while <code>ÿ</code>,
569 <code>\u00FF</code>, <code>\U000000FF</code> and <code>\xc3\xbf</code> represent
570 the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character
571 U+00FF.
572 </p>
573
574 <pre class="ebnf">
575 string_lit             = raw_string_lit | interpreted_string_lit .
576 raw_string_lit         = "`" { unicode_char | newline } "`" .
577 interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
578 </pre>
579
580 <pre>
581 `abc`                // same as "abc"
582 `\n
583 \n`                  // same as "\\n\n\\n"
584 "\n"
585 "\""                 // same as `"`
586 "Hello, world!\n"
587 "日本語"
588 "\u65e5本\U00008a9e"
589 "\xff\u00FF"
590 "\uD800"             // illegal: surrogate half
591 "\U00110000"         // illegal: invalid Unicode code point
592 </pre>
593
594 <p>
595 These examples all represent the same string:
596 </p>
597
598 <pre>
599 "日本語"                                 // UTF-8 input text
600 `日本語`                                 // UTF-8 input text as a raw literal
601 "\u65e5\u672c\u8a9e"                    // the explicit Unicode code points
602 "\U000065e5\U0000672c\U00008a9e"        // the explicit Unicode code points
603 "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"  // the explicit UTF-8 bytes
604 </pre>
605
606 <p>
607 If the source code represents a character as two code points, such as
608 a combining form involving an accent and a letter, the result will be
609 an error if placed in a rune literal (it is not a single code
610 point), and will appear as two code points if placed in a string
611 literal.
612 </p>
613
614
615 <h2 id="Constants">Constants</h2>
616
617 <p>There are <i>boolean constants</i>,
618 <i>rune constants</i>,
619 <i>integer constants</i>,
620 <i>floating-point constants</i>, <i>complex constants</i>,
621 and <i>string constants</i>. Rune, integer, floating-point,
622 and complex constants are
623 collectively called <i>numeric constants</i>.
624 </p>
625
626 <p>
627 A constant value is represented by a
628 <a href="#Rune_literals">rune</a>,
629 <a href="#Integer_literals">integer</a>,
630 <a href="#Floating-point_literals">floating-point</a>,
631 <a href="#Imaginary_literals">imaginary</a>,
632 or
633 <a href="#String_literals">string</a> literal,
634 an identifier denoting a constant,
635 a <a href="#Constant_expressions">constant expression</a>,
636 a <a href="#Conversions">conversion</a> with a result that is a constant, or
637 the result value of some built-in functions such as
638 <code>unsafe.Sizeof</code> applied to any value,
639 <code>cap</code> or <code>len</code> applied to
640 <a href="#Length_and_capacity">some expressions</a>,
641 <code>real</code> and <code>imag</code> applied to a complex constant
642 and <code>complex</code> applied to numeric constants.
643 The boolean truth values are represented by the predeclared constants
644 <code>true</code> and <code>false</code>. The predeclared identifier
645 <a href="#Iota">iota</a> denotes an integer constant.
646 </p>
647
648 <p>
649 In general, complex constants are a form of
650 <a href="#Constant_expressions">constant expression</a>
651 and are discussed in that section.
652 </p>
653
654 <p>
655 Numeric constants represent exact values of arbitrary precision and do not overflow.
656 Consequently, there are no constants denoting the IEEE-754 negative zero, infinity,
657 and not-a-number values.
658 </p>
659
660 <p>
661 Constants may be <a href="#Types">typed</a> or <i>untyped</i>.
662 Literal constants, <code>true</code>, <code>false</code>, <code>iota</code>,
663 and certain <a href="#Constant_expressions">constant expressions</a>
664 containing only untyped constant operands are untyped.
665 </p>
666
667 <p>
668 A constant may be given a type explicitly by a <a href="#Constant_declarations">constant declaration</a>
669 or <a href="#Conversions">conversion</a>, or implicitly when used in a
670 <a href="#Variable_declarations">variable declaration</a> or an
671 <a href="#Assignments">assignment</a> or as an
672 operand in an <a href="#Expressions">expression</a>.
673 It is an error if the constant value
674 cannot be <a href="#Representability">represented</a> as a value of the respective type.
675 </p>
676
677 <p>
678 An untyped constant has a <i>default type</i> which is the type to which the
679 constant is implicitly converted in contexts where a typed value is required,
680 for instance, in a <a href="#Short_variable_declarations">short variable declaration</a>
681 such as <code>i := 0</code> where there is no explicit type.
682 The default type of an untyped constant is <code>bool</code>, <code>rune</code>,
683 <code>int</code>, <code>float64</code>, <code>complex128</code> or <code>string</code>
684 respectively, depending on whether it is a boolean, rune, integer, floating-point,
685 complex, or string constant.
686 </p>
687
688 <p>
689 Implementation restriction: Although numeric constants have arbitrary
690 precision in the language, a compiler may implement them using an
691 internal representation with limited precision.  That said, every
692 implementation must:
693 </p>
694
695 <ul>
696         <li>Represent integer constants with at least 256 bits.</li>
697
698         <li>Represent floating-point constants, including the parts of
699             a complex constant, with a mantissa of at least 256 bits
700             and a signed binary exponent of at least 16 bits.</li>
701
702         <li>Give an error if unable to represent an integer constant
703             precisely.</li>
704
705         <li>Give an error if unable to represent a floating-point or
706             complex constant due to overflow.</li>
707
708         <li>Round to the nearest representable constant if unable to
709             represent a floating-point or complex constant due to limits
710             on precision.</li>
711 </ul>
712
713 <p>
714 These requirements apply both to literal constants and to the result
715 of evaluating <a href="#Constant_expressions">constant
716 expressions</a>.
717 </p>
718
719
720 <h2 id="Variables">Variables</h2>
721
722 <p>
723 A variable is a storage location for holding a <i>value</i>.
724 The set of permissible values is determined by the
725 variable's <i><a href="#Types">type</a></i>.
726 </p>
727
728 <p>
729 A <a href="#Variable_declarations">variable declaration</a>
730 or, for function parameters and results, the signature
731 of a <a href="#Function_declarations">function declaration</a>
732 or <a href="#Function_literals">function literal</a> reserves
733 storage for a named variable.
734
735 Calling the built-in function <a href="#Allocation"><code>new</code></a>
736 or taking the address of a <a href="#Composite_literals">composite literal</a>
737 allocates storage for a variable at run time.
738 Such an anonymous variable is referred to via a (possibly implicit)
739 <a href="#Address_operators">pointer indirection</a>.
740 </p>
741
742 <p>
743 <i>Structured</i> variables of <a href="#Array_types">array</a>, <a href="#Slice_types">slice</a>,
744 and <a href="#Struct_types">struct</a> types have elements and fields that may
745 be <a href="#Address_operators">addressed</a> individually. Each such element
746 acts like a variable.
747 </p>
748
749 <p>
750 The <i>static type</i> (or just <i>type</i>) of a variable is the
751 type given in its declaration, the type provided in the
752 <code>new</code> call or composite literal, or the type of
753 an element of a structured variable.
754 Variables of interface type also have a distinct <i>dynamic type</i>,
755 which is the concrete type of the value assigned to the variable at run time
756 (unless the value is the predeclared identifier <code>nil</code>,
757 which has no type).
758 The dynamic type may vary during execution but values stored in interface
759 variables are always <a href="#Assignability">assignable</a>
760 to the static type of the variable.
761 </p>
762
763 <pre>
764 var x interface{}  // x is nil and has static type interface{}
765 var v *T           // v has value nil, static type *T
766 x = 42             // x has value 42 and dynamic type int
767 x = v              // x has value (*T)(nil) and dynamic type *T
768 </pre>
769
770 <p>
771 A variable's value is retrieved by referring to the variable in an
772 <a href="#Expressions">expression</a>; it is the most recent value
773 <a href="#Assignments">assigned</a> to the variable.
774 If a variable has not yet been assigned a value, its value is the
775 <a href="#The_zero_value">zero value</a> for its type.
776 </p>
777
778
779 <h2 id="Types">Types</h2>
780
781 <p>
782 A type determines a set of values together with operations and methods specific
783 to those values. A type may be denoted by a <i>type name</i>, if it has one,
784 or specified using a <i>type literal</i>, which composes a type from existing types.
785 </p>
786
787 <pre class="ebnf">
788 Type      = TypeName | TypeLit | "(" Type ")" .
789 TypeName  = identifier | QualifiedIdent .
790 TypeLit   = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
791             SliceType | MapType | ChannelType .
792 </pre>
793
794 <p>
795 The language <a href="#Predeclared_identifiers">predeclares</a> certain type names.
796 Others are introduced with <a href="#Type_declarations">type declarations</a>.
797 <i>Composite types</i>&mdash;array, struct, pointer, function,
798 interface, slice, map, and channel types&mdash;may be constructed using
799 type literals.
800 </p>
801
802 <p>
803 Each type <code>T</code> has an <i>underlying type</i>: If <code>T</code>
804 is one of the predeclared boolean, numeric, or string types, or a type literal,
805 the corresponding underlying
806 type is <code>T</code> itself. Otherwise, <code>T</code>'s underlying type
807 is the underlying type of the type to which <code>T</code> refers in its
808 <a href="#Type_declarations">type declaration</a>.
809 </p>
810
811 <pre>
812 type (
813         A1 = string
814         A2 = A1
815 )
816
817 type (
818         B1 string
819         B2 B1
820         B3 []B1
821         B4 B3
822 )
823 </pre>
824
825 <p>
826 The underlying type of <code>string</code>, <code>A1</code>, <code>A2</code>, <code>B1</code>,
827 and <code>B2</code> is <code>string</code>.
828 The underlying type of <code>[]B1</code>, <code>B3</code>, and <code>B4</code> is <code>[]B1</code>.
829 </p>
830
831 <h3 id="Method_sets">Method sets</h3>
832 <p>
833 A type has a (possibly empty) <i>method set</i> associated with it.
834 The method set of an <a href="#Interface_types">interface type</a> is its interface.
835 The method set of any other type <code>T</code> consists of all
836 <a href="#Method_declarations">methods</a> declared with receiver type <code>T</code>.
837 The method set of the corresponding <a href="#Pointer_types">pointer type</a> <code>*T</code>
838 is the set of all methods declared with receiver <code>*T</code> or <code>T</code>
839 (that is, it also contains the method set of <code>T</code>).
840 Further rules apply to structs containing embedded fields, as described
841 in the section on <a href="#Struct_types">struct types</a>.
842 Any other type has an empty method set.
843 In a method set, each method must have a
844 <a href="#Uniqueness_of_identifiers">unique</a>
845 non-<a href="#Blank_identifier">blank</a> <a href="#MethodName">method name</a>.
846 </p>
847
848 <p>
849 The method set of a type determines the interfaces that the
850 type <a href="#Interface_types">implements</a>
851 and the methods that can be <a href="#Calls">called</a>
852 using a receiver of that type.
853 </p>
854
855 <h3 id="Boolean_types">Boolean types</h3>
856
857 <p>
858 A <i>boolean type</i> represents the set of Boolean truth values
859 denoted by the predeclared constants <code>true</code>
860 and <code>false</code>. The predeclared boolean type is <code>bool</code>;
861 it is a <a href="#Type_definitions">defined type</a>.
862 </p>
863
864 <h3 id="Numeric_types">Numeric types</h3>
865
866 <p>
867 A <i>numeric type</i> represents sets of integer or floating-point values.
868 The predeclared architecture-independent numeric types are:
869 </p>
870
871 <pre class="grammar">
872 uint8       the set of all unsigned  8-bit integers (0 to 255)
873 uint16      the set of all unsigned 16-bit integers (0 to 65535)
874 uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
875 uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)
876
877 int8        the set of all signed  8-bit integers (-128 to 127)
878 int16       the set of all signed 16-bit integers (-32768 to 32767)
879 int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
880 int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
881
882 float32     the set of all IEEE-754 32-bit floating-point numbers
883 float64     the set of all IEEE-754 64-bit floating-point numbers
884
885 complex64   the set of all complex numbers with float32 real and imaginary parts
886 complex128  the set of all complex numbers with float64 real and imaginary parts
887
888 byte        alias for uint8
889 rune        alias for int32
890 </pre>
891
892 <p>
893 The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using
894 <a href="https://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>.
895 </p>
896
897 <p>
898 There is also a set of predeclared numeric types with implementation-specific sizes:
899 </p>
900
901 <pre class="grammar">
902 uint     either 32 or 64 bits
903 int      same size as uint
904 uintptr  an unsigned integer large enough to store the uninterpreted bits of a pointer value
905 </pre>
906
907 <p>
908 To avoid portability issues all numeric types are <a href="#Type_definitions">defined
909 types</a> and thus distinct except
910 <code>byte</code>, which is an <a href="#Alias_declarations">alias</a> for <code>uint8</code>, and
911 <code>rune</code>, which is an alias for <code>int32</code>.
912 Explicit conversions
913 are required when different numeric types are mixed in an expression
914 or assignment. For instance, <code>int32</code> and <code>int</code>
915 are not the same type even though they may have the same size on a
916 particular architecture.
917 </p>
918
919 <h3 id="String_types">String types</h3>
920
921 <p>
922 A <i>string type</i> represents the set of string values.
923 A string value is a (possibly empty) sequence of bytes.
924 The number of bytes is called the length of the string and is never negative.
925 Strings are immutable: once created,
926 it is impossible to change the contents of a string.
927 The predeclared string type is <code>string</code>;
928 it is a <a href="#Type_definitions">defined type</a>.
929 </p>
930
931 <p>
932 The length of a string <code>s</code> can be discovered using
933 the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
934 The length is a compile-time constant if the string is a constant.
935 A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>
936 0 through <code>len(s)-1</code>.
937 It is illegal to take the address of such an element; if
938 <code>s[i]</code> is the <code>i</code>'th byte of a
939 string, <code>&amp;s[i]</code> is invalid.
940 </p>
941
942
943 <h3 id="Array_types">Array types</h3>
944
945 <p>
946 An array is a numbered sequence of elements of a single
947 type, called the element type.
948 The number of elements is called the length of the array and is never negative.
949 </p>
950
951 <pre class="ebnf">
952 ArrayType   = "[" ArrayLength "]" ElementType .
953 ArrayLength = Expression .
954 ElementType = Type .
955 </pre>
956
957 <p>
958 The length is part of the array's type; it must evaluate to a
959 non-negative <a href="#Constants">constant</a>
960 <a href="#Representability">representable</a> by a value
961 of type <code>int</code>.
962 The length of array <code>a</code> can be discovered
963 using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
964 The elements can be addressed by integer <a href="#Index_expressions">indices</a>
965 0 through <code>len(a)-1</code>.
966 Array types are always one-dimensional but may be composed to form
967 multi-dimensional types.
968 </p>
969
970 <pre>
971 [32]byte
972 [2*N] struct { x, y int32 }
973 [1000]*float64
974 [3][5]int
975 [2][2][2]float64  // same as [2]([2]([2]float64))
976 </pre>
977
978 <h3 id="Slice_types">Slice types</h3>
979
980 <p>
981 A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and
982 provides access to a numbered sequence of elements from that array.
983 A slice type denotes the set of all slices of arrays of its element type.
984 The number of elements is called the length of the slice and is never negative.
985 The value of an uninitialized slice is <code>nil</code>.
986 </p>
987
988 <pre class="ebnf">
989 SliceType = "[" "]" ElementType .
990 </pre>
991
992 <p>
993 The length of a slice <code>s</code> can be discovered by the built-in function
994 <a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during
995 execution.  The elements can be addressed by integer <a href="#Index_expressions">indices</a>
996 0 through <code>len(s)-1</code>.  The slice index of a
997 given element may be less than the index of the same element in the
998 underlying array.
999 </p>
1000 <p>
1001 A slice, once initialized, is always associated with an underlying
1002 array that holds its elements.  A slice therefore shares storage
1003 with its array and with other slices of the same array; by contrast,
1004 distinct arrays always represent distinct storage.
1005 </p>
1006 <p>
1007 The array underlying a slice may extend past the end of the slice.
1008 The <i>capacity</i> is a measure of that extent: it is the sum of
1009 the length of the slice and the length of the array beyond the slice;
1010 a slice of length up to that capacity can be created by
1011 <a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice.
1012 The capacity of a slice <code>a</code> can be discovered using the
1013 built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.
1014 </p>
1015
1016 <p>
1017 A new, initialized slice value for a given element type <code>T</code> is
1018 made using the built-in function
1019 <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1020 which takes a slice type
1021 and parameters specifying the length and optionally the capacity.
1022 A slice created with <code>make</code> always allocates a new, hidden array
1023 to which the returned slice value refers. That is, executing
1024 </p>
1025
1026 <pre>
1027 make([]T, length, capacity)
1028 </pre>
1029
1030 <p>
1031 produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a>
1032 it, so these two expressions are equivalent:
1033 </p>
1034
1035 <pre>
1036 make([]int, 50, 100)
1037 new([100]int)[0:50]
1038 </pre>
1039
1040 <p>
1041 Like arrays, slices are always one-dimensional but may be composed to construct
1042 higher-dimensional objects.
1043 With arrays of arrays, the inner arrays are, by construction, always the same length;
1044 however with slices of slices (or arrays of slices), the inner lengths may vary dynamically.
1045 Moreover, the inner slices must be initialized individually.
1046 </p>
1047
1048 <h3 id="Struct_types">Struct types</h3>
1049
1050 <p>
1051 A struct is a sequence of named elements, called fields, each of which has a
1052 name and a type. Field names may be specified explicitly (IdentifierList) or
1053 implicitly (EmbeddedField).
1054 Within a struct, non-<a href="#Blank_identifier">blank</a> field names must
1055 be <a href="#Uniqueness_of_identifiers">unique</a>.
1056 </p>
1057
1058 <pre class="ebnf">
1059 StructType    = "struct" "{" { FieldDecl ";" } "}" .
1060 FieldDecl     = (IdentifierList Type | EmbeddedField) [ Tag ] .
1061 EmbeddedField = [ "*" ] TypeName .
1062 Tag           = string_lit .
1063 </pre>
1064
1065 <pre>
1066 // An empty struct.
1067 struct {}
1068
1069 // A struct with 6 fields.
1070 struct {
1071         x, y int
1072         u float32
1073         _ float32  // padding
1074         A *[]int
1075         F func()
1076 }
1077 </pre>
1078
1079 <p>
1080 A field declared with a type but no explicit field name is called an <i>embedded field</i>.
1081 An embedded field must be specified as
1082 a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>,
1083 and <code>T</code> itself may not be
1084 a pointer type. The unqualified type name acts as the field name.
1085 </p>
1086
1087 <pre>
1088 // A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4
1089 struct {
1090         T1        // field name is T1
1091         *T2       // field name is T2
1092         P.T3      // field name is T3
1093         *P.T4     // field name is T4
1094         x, y int  // field names are x and y
1095 }
1096 </pre>
1097
1098 <p>
1099 The following declaration is illegal because field names must be unique
1100 in a struct type:
1101 </p>
1102
1103 <pre>
1104 struct {
1105         T     // conflicts with embedded field *T and *P.T
1106         *T    // conflicts with embedded field T and *P.T
1107         *P.T  // conflicts with embedded field T and *T
1108 }
1109 </pre>
1110
1111 <p>
1112 A field or <a href="#Method_declarations">method</a> <code>f</code> of an
1113 embedded field in a struct <code>x</code> is called <i>promoted</i> if
1114 <code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes
1115 that field or method <code>f</code>.
1116 </p>
1117
1118 <p>
1119 Promoted fields act like ordinary fields
1120 of a struct except that they cannot be used as field names in
1121 <a href="#Composite_literals">composite literals</a> of the struct.
1122 </p>
1123
1124 <p>
1125 Given a struct type <code>S</code> and a <a href="#Type_definitions">defined type</a>
1126 <code>T</code>, promoted methods are included in the method set of the struct as follows:
1127 </p>
1128 <ul>
1129         <li>
1130         If <code>S</code> contains an embedded field <code>T</code>,
1131         the <a href="#Method_sets">method sets</a> of <code>S</code>
1132         and <code>*S</code> both include promoted methods with receiver
1133         <code>T</code>. The method set of <code>*S</code> also
1134         includes promoted methods with receiver <code>*T</code>.
1135         </li>
1136
1137         <li>
1138         If <code>S</code> contains an embedded field <code>*T</code>,
1139         the method sets of <code>S</code> and <code>*S</code> both
1140         include promoted methods with receiver <code>T</code> or
1141         <code>*T</code>.
1142         </li>
1143 </ul>
1144
1145 <p>
1146 A field declaration may be followed by an optional string literal <i>tag</i>,
1147 which becomes an attribute for all the fields in the corresponding
1148 field declaration. An empty tag string is equivalent to an absent tag.
1149 The tags are made visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a>
1150 and take part in <a href="#Type_identity">type identity</a> for structs
1151 but are otherwise ignored.
1152 </p>
1153
1154 <pre>
1155 struct {
1156         x, y float64 ""  // an empty tag string is like an absent tag
1157         name string  "any string is permitted as a tag"
1158         _    [4]byte "ceci n'est pas un champ de structure"
1159 }
1160
1161 // A struct corresponding to a TimeStamp protocol buffer.
1162 // The tag strings define the protocol buffer field numbers;
1163 // they follow the convention outlined by the reflect package.
1164 struct {
1165         microsec  uint64 `protobuf:"1"`
1166         serverIP6 uint64 `protobuf:"2"`
1167 }
1168 </pre>
1169
1170 <h3 id="Pointer_types">Pointer types</h3>
1171
1172 <p>
1173 A pointer type denotes the set of all pointers to <a href="#Variables">variables</a> of a given
1174 type, called the <i>base type</i> of the pointer.
1175 The value of an uninitialized pointer is <code>nil</code>.
1176 </p>
1177
1178 <pre class="ebnf">
1179 PointerType = "*" BaseType .
1180 BaseType    = Type .
1181 </pre>
1182
1183 <pre>
1184 *Point
1185 *[4]int
1186 </pre>
1187
1188 <h3 id="Function_types">Function types</h3>
1189
1190 <p>
1191 A function type denotes the set of all functions with the same parameter
1192 and result types. The value of an uninitialized variable of function type
1193 is <code>nil</code>.
1194 </p>
1195
1196 <pre class="ebnf">
1197 FunctionType   = "func" Signature .
1198 Signature      = Parameters [ Result ] .
1199 Result         = Parameters | Type .
1200 Parameters     = "(" [ ParameterList [ "," ] ] ")" .
1201 ParameterList  = ParameterDecl { "," ParameterDecl } .
1202 ParameterDecl  = [ IdentifierList ] [ "..." ] Type .
1203 </pre>
1204
1205 <p>
1206 Within a list of parameters or results, the names (IdentifierList)
1207 must either all be present or all be absent. If present, each name
1208 stands for one item (parameter or result) of the specified type and
1209 all non-<a href="#Blank_identifier">blank</a> names in the signature
1210 must be <a href="#Uniqueness_of_identifiers">unique</a>.
1211 If absent, each type stands for one item of that type.
1212 Parameter and result
1213 lists are always parenthesized except that if there is exactly
1214 one unnamed result it may be written as an unparenthesized type.
1215 </p>
1216
1217 <p>
1218 The final incoming parameter in a function signature may have
1219 a type prefixed with <code>...</code>.
1220 A function with such a parameter is called <i>variadic</i> and
1221 may be invoked with zero or more arguments for that parameter.
1222 </p>
1223
1224 <pre>
1225 func()
1226 func(x int) int
1227 func(a, _ int, z float32) bool
1228 func(a, b int, z float32) (bool)
1229 func(prefix string, values ...int)
1230 func(a, b int, z float64, opt ...interface{}) (success bool)
1231 func(int, int, float64) (float64, *[]int)
1232 func(n int) func(p *T)
1233 </pre>
1234
1235
1236 <h3 id="Interface_types">Interface types</h3>
1237
1238 <p>
1239 An interface type specifies a <a href="#Method_sets">method set</a> called its <i>interface</i>.
1240 A variable of interface type can store a value of any type with a method set
1241 that is any superset of the interface. Such a type is said to
1242 <i>implement the interface</i>.
1243 The value of an uninitialized variable of interface type is <code>nil</code>.
1244 </p>
1245
1246 <pre class="ebnf">
1247 InterfaceType      = "interface" "{" { ( MethodSpec | InterfaceTypeName ) ";" } "}" .
1248 MethodSpec         = MethodName Signature .
1249 MethodName         = identifier .
1250 InterfaceTypeName  = TypeName .
1251 </pre>
1252
1253 <p>
1254 An interface type may specify methods <i>explicitly</i> through method specifications,
1255 or it may <i>embed</i> methods of other interfaces through interface type names.
1256 </p>
1257
1258 <pre>
1259 // A simple File interface.
1260 interface {
1261         Read([]byte) (int, error)
1262         Write([]byte) (int, error)
1263         Close() error
1264 }
1265 </pre>
1266
1267 <p>
1268 The name of each explicitly specified method must be <a href="#Uniqueness_of_identifiers">unique</a>
1269 and not <a href="#Blank_identifier">blank</a>.
1270 </p>
1271
1272 <pre>
1273 interface {
1274         String() string
1275         String() string  // illegal: String not unique
1276         _(x int)         // illegal: method must have non-blank name
1277 }
1278 </pre>
1279
1280 <p>
1281 More than one type may implement an interface.
1282 For instance, if two types <code>S1</code> and <code>S2</code>
1283 have the method set
1284 </p>
1285
1286 <pre>
1287 func (p T) Read(p []byte) (n int, err error)
1288 func (p T) Write(p []byte) (n int, err error)
1289 func (p T) Close() error
1290 </pre>
1291
1292 <p>
1293 (where <code>T</code> stands for either <code>S1</code> or <code>S2</code>)
1294 then the <code>File</code> interface is implemented by both <code>S1</code> and
1295 <code>S2</code>, regardless of what other methods
1296 <code>S1</code> and <code>S2</code> may have or share.
1297 </p>
1298
1299 <p>
1300 A type implements any interface comprising any subset of its methods
1301 and may therefore implement several distinct interfaces. For
1302 instance, all types implement the <i>empty interface</i>:
1303 </p>
1304
1305 <pre>
1306 interface{}
1307 </pre>
1308
1309 <p>
1310 Similarly, consider this interface specification,
1311 which appears within a <a href="#Type_declarations">type declaration</a>
1312 to define an interface called <code>Locker</code>:
1313 </p>
1314
1315 <pre>
1316 type Locker interface {
1317         Lock()
1318         Unlock()
1319 }
1320 </pre>
1321
1322 <p>
1323 If <code>S1</code> and <code>S2</code> also implement
1324 </p>
1325
1326 <pre>
1327 func (p T) Lock() { … }
1328 func (p T) Unlock() { … }
1329 </pre>
1330
1331 <p>
1332 they implement the <code>Locker</code> interface as well
1333 as the <code>File</code> interface.
1334 </p>
1335
1336 <p>
1337 An interface <code>T</code> may use a (possibly qualified) interface type
1338 name <code>E</code> in place of a method specification. This is called
1339 <i>embedding</i> interface <code>E</code> in <code>T</code>.
1340 The <a href="#Method_sets">method set</a> of <code>T</code> is the <i>union</i>
1341 of the method sets of <code>T</code>’s explicitly declared methods and of
1342 <code>T</code>’s embedded interfaces.
1343 </p>
1344
1345 <pre>
1346 type Reader interface {
1347         Read(p []byte) (n int, err error)
1348         Close() error
1349 }
1350
1351 type Writer interface {
1352         Write(p []byte) (n int, err error)
1353         Close() error
1354 }
1355
1356 // ReadWriter's methods are Read, Write, and Close.
1357 type ReadWriter interface {
1358         Reader  // includes methods of Reader in ReadWriter's method set
1359         Writer  // includes methods of Writer in ReadWriter's method set
1360 }
1361 </pre>
1362
1363 <p>
1364 A <i>union</i> of method sets contains the (exported and non-exported)
1365 methods of each method set exactly once, and methods with the
1366 <a href="#Uniqueness_of_identifiers">same</a> names must
1367 have <a href="#Type_identity">identical</a> signatures.
1368 </p>
1369
1370 <pre>
1371 type ReadCloser interface {
1372         Reader   // includes methods of Reader in ReadCloser's method set
1373         Close()  // illegal: signatures of Reader.Close and Close are different
1374 }
1375 </pre>
1376
1377 <p>
1378 An interface type <code>T</code> may not embed itself
1379 or any interface type that embeds <code>T</code>, recursively.
1380 </p>
1381
1382 <pre>
1383 // illegal: Bad cannot embed itself
1384 type Bad interface {
1385         Bad
1386 }
1387
1388 // illegal: Bad1 cannot embed itself using Bad2
1389 type Bad1 interface {
1390         Bad2
1391 }
1392 type Bad2 interface {
1393         Bad1
1394 }
1395 </pre>
1396
1397 <h3 id="Map_types">Map types</h3>
1398
1399 <p>
1400 A map is an unordered group of elements of one type, called the
1401 element type, indexed by a set of unique <i>keys</i> of another type,
1402 called the key type.
1403 The value of an uninitialized map is <code>nil</code>.
1404 </p>
1405
1406 <pre class="ebnf">
1407 MapType     = "map" "[" KeyType "]" ElementType .
1408 KeyType     = Type .
1409 </pre>
1410
1411 <p>
1412 The <a href="#Comparison_operators">comparison operators</a>
1413 <code>==</code> and <code>!=</code> must be fully defined
1414 for operands of the key type; thus the key type must not be a function, map, or
1415 slice.
1416 If the key type is an interface type, these
1417 comparison operators must be defined for the dynamic key values;
1418 failure will cause a <a href="#Run_time_panics">run-time panic</a>.
1419
1420 </p>
1421
1422 <pre>
1423 map[string]int
1424 map[*T]struct{ x, y float64 }
1425 map[string]interface{}
1426 </pre>
1427
1428 <p>
1429 The number of map elements is called its length.
1430 For a map <code>m</code>, it can be discovered using the
1431 built-in function <a href="#Length_and_capacity"><code>len</code></a>
1432 and may change during execution. Elements may be added during execution
1433 using <a href="#Assignments">assignments</a> and retrieved with
1434 <a href="#Index_expressions">index expressions</a>; they may be removed with the
1435 <a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function.
1436 </p>
1437 <p>
1438 A new, empty map value is made using the built-in
1439 function <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1440 which takes the map type and an optional capacity hint as arguments:
1441 </p>
1442
1443 <pre>
1444 make(map[string]int)
1445 make(map[string]int, 100)
1446 </pre>
1447
1448 <p>
1449 The initial capacity does not bound its size:
1450 maps grow to accommodate the number of items
1451 stored in them, with the exception of <code>nil</code> maps.
1452 A <code>nil</code> map is equivalent to an empty map except that no elements
1453 may be added.
1454 </p>
1455
1456 <h3 id="Channel_types">Channel types</h3>
1457
1458 <p>
1459 A channel provides a mechanism for
1460 <a href="#Go_statements">concurrently executing functions</a>
1461 to communicate by
1462 <a href="#Send_statements">sending</a> and
1463 <a href="#Receive_operator">receiving</a>
1464 values of a specified element type.
1465 The value of an uninitialized channel is <code>nil</code>.
1466 </p>
1467
1468 <pre class="ebnf">
1469 ChannelType = ( "chan" | "chan" "&lt;-" | "&lt;-" "chan" ) ElementType .
1470 </pre>
1471
1472 <p>
1473 The optional <code>&lt;-</code> operator specifies the channel <i>direction</i>,
1474 <i>send</i> or <i>receive</i>. If no direction is given, the channel is
1475 <i>bidirectional</i>.
1476 A channel may be constrained only to send or only to receive by
1477 <a href="#Assignments">assignment</a> or
1478 explicit <a href="#Conversions">conversion</a>.
1479 </p>
1480
1481 <pre>
1482 chan T          // can be used to send and receive values of type T
1483 chan&lt;- float64  // can only be used to send float64s
1484 &lt;-chan int      // can only be used to receive ints
1485 </pre>
1486
1487 <p>
1488 The <code>&lt;-</code> operator associates with the leftmost <code>chan</code>
1489 possible:
1490 </p>
1491
1492 <pre>
1493 chan&lt;- chan int    // same as chan&lt;- (chan int)
1494 chan&lt;- &lt;-chan int  // same as chan&lt;- (&lt;-chan int)
1495 &lt;-chan &lt;-chan int  // same as &lt;-chan (&lt;-chan int)
1496 chan (&lt;-chan int)
1497 </pre>
1498
1499 <p>
1500 A new, initialized channel
1501 value can be made using the built-in function
1502 <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1503 which takes the channel type and an optional <i>capacity</i> as arguments:
1504 </p>
1505
1506 <pre>
1507 make(chan int, 100)
1508 </pre>
1509
1510 <p>
1511 The capacity, in number of elements, sets the size of the buffer in the channel.
1512 If the capacity is zero or absent, the channel is unbuffered and communication
1513 succeeds only when both a sender and receiver are ready. Otherwise, the channel
1514 is buffered and communication succeeds without blocking if the buffer
1515 is not full (sends) or not empty (receives).
1516 A <code>nil</code> channel is never ready for communication.
1517 </p>
1518
1519 <p>
1520 A channel may be closed with the built-in function
1521 <a href="#Close"><code>close</code></a>.
1522 The multi-valued assignment form of the
1523 <a href="#Receive_operator">receive operator</a>
1524 reports whether a received value was sent before
1525 the channel was closed.
1526 </p>
1527
1528 <p>
1529 A single channel may be used in
1530 <a href="#Send_statements">send statements</a>,
1531 <a href="#Receive_operator">receive operations</a>,
1532 and calls to the built-in functions
1533 <a href="#Length_and_capacity"><code>cap</code></a> and
1534 <a href="#Length_and_capacity"><code>len</code></a>
1535 by any number of goroutines without further synchronization.
1536 Channels act as first-in-first-out queues.
1537 For example, if one goroutine sends values on a channel
1538 and a second goroutine receives them, the values are
1539 received in the order sent.
1540 </p>
1541
1542 <h2 id="Properties_of_types_and_values">Properties of types and values</h2>
1543
1544 <h3 id="Type_identity">Type identity</h3>
1545
1546 <p>
1547 Two types are either <i>identical</i> or <i>different</i>.
1548 </p>
1549
1550 <p>
1551 A <a href="#Type_definitions">defined type</a> is always different from any other type.
1552 Otherwise, two types are identical if their <a href="#Types">underlying</a> type literals are
1553 structurally equivalent; that is, they have the same literal structure and corresponding
1554 components have identical types. In detail:
1555 </p>
1556
1557 <ul>
1558         <li>Two array types are identical if they have identical element types and
1559             the same array length.</li>
1560
1561         <li>Two slice types are identical if they have identical element types.</li>
1562
1563         <li>Two struct types are identical if they have the same sequence of fields,
1564             and if corresponding fields have the same names, and identical types,
1565             and identical tags.
1566             <a href="#Exported_identifiers">Non-exported</a> field names from different
1567             packages are always different.</li>
1568
1569         <li>Two pointer types are identical if they have identical base types.</li>
1570
1571         <li>Two function types are identical if they have the same number of parameters
1572             and result values, corresponding parameter and result types are
1573             identical, and either both functions are variadic or neither is.
1574             Parameter and result names are not required to match.</li>
1575
1576         <li>Two interface types are identical if they have the same set of methods
1577             with the same names and identical function types.
1578             <a href="#Exported_identifiers">Non-exported</a> method names from different
1579             packages are always different. The order of the methods is irrelevant.</li>
1580
1581         <li>Two map types are identical if they have identical key and element types.</li>
1582
1583         <li>Two channel types are identical if they have identical element types and
1584             the same direction.</li>
1585 </ul>
1586
1587 <p>
1588 Given the declarations
1589 </p>
1590
1591 <pre>
1592 type (
1593         A0 = []string
1594         A1 = A0
1595         A2 = struct{ a, b int }
1596         A3 = int
1597         A4 = func(A3, float64) *A0
1598         A5 = func(x int, _ float64) *[]string
1599 )
1600
1601 type (
1602         B0 A0
1603         B1 []string
1604         B2 struct{ a, b int }
1605         B3 struct{ a, c int }
1606         B4 func(int, float64) *B0
1607         B5 func(x int, y float64) *A1
1608 )
1609
1610 type    C0 = B0
1611 </pre>
1612
1613 <p>
1614 these types are identical:
1615 </p>
1616
1617 <pre>
1618 A0, A1, and []string
1619 A2 and struct{ a, b int }
1620 A3 and int
1621 A4, func(int, float64) *[]string, and A5
1622
1623 B0 and C0
1624 []int and []int
1625 struct{ a, b *T5 } and struct{ a, b *T5 }
1626 func(x int, y float64) *[]string, func(int, float64) (result *[]string), and A5
1627 </pre>
1628
1629 <p>
1630 <code>B0</code> and <code>B1</code> are different because they are new types
1631 created by distinct <a href="#Type_definitions">type definitions</a>;
1632 <code>func(int, float64) *B0</code> and <code>func(x int, y float64) *[]string</code>
1633 are different because <code>B0</code> is different from <code>[]string</code>.
1634 </p>
1635
1636
1637 <h3 id="Assignability">Assignability</h3>
1638
1639 <p>
1640 A value <code>x</code> is <i>assignable</i> to a <a href="#Variables">variable</a> of type <code>T</code>
1641 ("<code>x</code> is assignable to <code>T</code>") if one of the following conditions applies:
1642 </p>
1643
1644 <ul>
1645 <li>
1646 <code>x</code>'s type is identical to <code>T</code>.
1647 </li>
1648 <li>
1649 <code>x</code>'s type <code>V</code> and <code>T</code> have identical
1650 <a href="#Types">underlying types</a> and at least one of <code>V</code>
1651 or <code>T</code> is not a <a href="#Type_definitions">defined</a> type.
1652 </li>
1653 <li>
1654 <code>T</code> is an interface type and
1655 <code>x</code> <a href="#Interface_types">implements</a> <code>T</code>.
1656 </li>
1657 <li>
1658 <code>x</code> is a bidirectional channel value, <code>T</code> is a channel type,
1659 <code>x</code>'s type <code>V</code> and <code>T</code> have identical element types,
1660 and at least one of <code>V</code> or <code>T</code> is not a defined type.
1661 </li>
1662 <li>
1663 <code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code>
1664 is a pointer, function, slice, map, channel, or interface type.
1665 </li>
1666 <li>
1667 <code>x</code> is an untyped <a href="#Constants">constant</a>
1668 <a href="#Representability">representable</a>
1669 by a value of type <code>T</code>.
1670 </li>
1671 </ul>
1672
1673
1674 <h3 id="Representability">Representability</h3>
1675
1676 <p>
1677 A <a href="#Constants">constant</a> <code>x</code> is <i>representable</i>
1678 by a value of type <code>T</code> if one of the following conditions applies:
1679 </p>
1680
1681 <ul>
1682 <li>
1683 <code>x</code> is in the set of values <a href="#Types">determined</a> by <code>T</code>.
1684 </li>
1685
1686 <li>
1687 <code>T</code> is a floating-point type and <code>x</code> can be rounded to <code>T</code>'s
1688 precision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEE
1689 negative zero further simplified to an unsigned zero. Note that constant values never result
1690 in an IEEE negative zero, NaN, or infinity.
1691 </li>
1692
1693 <li>
1694 <code>T</code> is a complex type, and <code>x</code>'s
1695 <a href="#Complex_numbers">components</a> <code>real(x)</code> and <code>imag(x)</code>
1696 are representable by values of <code>T</code>'s component type (<code>float32</code> or
1697 <code>float64</code>).
1698 </li>
1699 </ul>
1700
1701 <pre>
1702 x                   T           x is representable by a value of T because
1703
1704 'a'                 byte        97 is in the set of byte values
1705 97                  rune        rune is an alias for int32, and 97 is in the set of 32-bit integers
1706 "foo"               string      "foo" is in the set of string values
1707 1024                int16       1024 is in the set of 16-bit integers
1708 42.0                byte        42 is in the set of unsigned 8-bit integers
1709 1e10                uint64      10000000000 is in the set of unsigned 64-bit integers
1710 2.718281828459045   float32     2.718281828459045 rounds to 2.7182817 which is in the set of float32 values
1711 -1e-1000            float64     -1e-1000 rounds to IEEE -0.0 which is further simplified to 0.0
1712 0i                  int         0 is an integer value
1713 (42 + 0i)           float32     42.0 (with zero imaginary part) is in the set of float32 values
1714 </pre>
1715
1716 <pre>
1717 x                   T           x is not representable by a value of T because
1718
1719 0                   bool        0 is not in the set of boolean values
1720 'a'                 string      'a' is a rune, it is not in the set of string values
1721 1024                byte        1024 is not in the set of unsigned 8-bit integers
1722 -1                  uint16      -1 is not in the set of unsigned 16-bit integers
1723 1.1                 int         1.1 is not an integer value
1724 42i                 float32     (0 + 42i) is not in the set of float32 values
1725 1e1000              float64     1e1000 overflows to IEEE +Inf after rounding
1726 </pre>
1727
1728
1729 <h2 id="Blocks">Blocks</h2>
1730
1731 <p>
1732 A <i>block</i> is a possibly empty sequence of declarations and statements
1733 within matching brace brackets.
1734 </p>
1735
1736 <pre class="ebnf">
1737 Block = "{" StatementList "}" .
1738 StatementList = { Statement ";" } .
1739 </pre>
1740
1741 <p>
1742 In addition to explicit blocks in the source code, there are implicit blocks:
1743 </p>
1744
1745 <ol>
1746         <li>The <i>universe block</i> encompasses all Go source text.</li>
1747
1748         <li>Each <a href="#Packages">package</a> has a <i>package block</i> containing all
1749             Go source text for that package.</li>
1750
1751         <li>Each file has a <i>file block</i> containing all Go source text
1752             in that file.</li>
1753
1754         <li>Each <a href="#If_statements">"if"</a>,
1755             <a href="#For_statements">"for"</a>, and
1756             <a href="#Switch_statements">"switch"</a>
1757             statement is considered to be in its own implicit block.</li>
1758
1759         <li>Each clause in a <a href="#Switch_statements">"switch"</a>
1760             or <a href="#Select_statements">"select"</a> statement
1761             acts as an implicit block.</li>
1762 </ol>
1763
1764 <p>
1765 Blocks nest and influence <a href="#Declarations_and_scope">scoping</a>.
1766 </p>
1767
1768
1769 <h2 id="Declarations_and_scope">Declarations and scope</h2>
1770
1771 <p>
1772 A <i>declaration</i> binds a non-<a href="#Blank_identifier">blank</a> identifier to a
1773 <a href="#Constant_declarations">constant</a>,
1774 <a href="#Type_declarations">type</a>,
1775 <a href="#Variable_declarations">variable</a>,
1776 <a href="#Function_declarations">function</a>,
1777 <a href="#Labeled_statements">label</a>, or
1778 <a href="#Import_declarations">package</a>.
1779 Every identifier in a program must be declared.
1780 No identifier may be declared twice in the same block, and
1781 no identifier may be declared in both the file and package block.
1782 </p>
1783
1784 <p>
1785 The <a href="#Blank_identifier">blank identifier</a> may be used like any other identifier
1786 in a declaration, but it does not introduce a binding and thus is not declared.
1787 In the package block, the identifier <code>init</code> may only be used for
1788 <a href="#Package_initialization"><code>init</code> function</a> declarations,
1789 and like the blank identifier it does not introduce a new binding.
1790 </p>
1791
1792 <pre class="ebnf">
1793 Declaration   = ConstDecl | TypeDecl | VarDecl .
1794 TopLevelDecl  = Declaration | FunctionDecl | MethodDecl .
1795 </pre>
1796
1797 <p>
1798 The <i>scope</i> of a declared identifier is the extent of source text in which
1799 the identifier denotes the specified constant, type, variable, function, label, or package.
1800 </p>
1801
1802 <p>
1803 Go is lexically scoped using <a href="#Blocks">blocks</a>:
1804 </p>
1805
1806 <ol>
1807         <li>The scope of a <a href="#Predeclared_identifiers">predeclared identifier</a> is the universe block.</li>
1808
1809         <li>The scope of an identifier denoting a constant, type, variable,
1810             or function (but not method) declared at top level (outside any
1811             function) is the package block.</li>
1812
1813         <li>The scope of the package name of an imported package is the file block
1814             of the file containing the import declaration.</li>
1815
1816         <li>The scope of an identifier denoting a method receiver, function parameter,
1817             or result variable is the function body.</li>
1818
1819         <li>The scope of a constant or variable identifier declared
1820             inside a function begins at the end of the ConstSpec or VarSpec
1821             (ShortVarDecl for short variable declarations)
1822             and ends at the end of the innermost containing block.</li>
1823
1824         <li>The scope of a type identifier declared inside a function
1825             begins at the identifier in the TypeSpec
1826             and ends at the end of the innermost containing block.</li>
1827 </ol>
1828
1829 <p>
1830 An identifier declared in a block may be redeclared in an inner block.
1831 While the identifier of the inner declaration is in scope, it denotes
1832 the entity declared by the inner declaration.
1833 </p>
1834
1835 <p>
1836 The <a href="#Package_clause">package clause</a> is not a declaration; the package name
1837 does not appear in any scope. Its purpose is to identify the files belonging
1838 to the same <a href="#Packages">package</a> and to specify the default package name for import
1839 declarations.
1840 </p>
1841
1842
1843 <h3 id="Label_scopes">Label scopes</h3>
1844
1845 <p>
1846 Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are
1847 used in the <a href="#Break_statements">"break"</a>,
1848 <a href="#Continue_statements">"continue"</a>, and
1849 <a href="#Goto_statements">"goto"</a> statements.
1850 It is illegal to define a label that is never used.
1851 In contrast to other identifiers, labels are not block scoped and do
1852 not conflict with identifiers that are not labels. The scope of a label
1853 is the body of the function in which it is declared and excludes
1854 the body of any nested function.
1855 </p>
1856
1857
1858 <h3 id="Blank_identifier">Blank identifier</h3>
1859
1860 <p>
1861 The <i>blank identifier</i> is represented by the underscore character <code>_</code>.
1862 It serves as an anonymous placeholder instead of a regular (non-blank)
1863 identifier and has special meaning in <a href="#Declarations_and_scope">declarations</a>,
1864 as an <a href="#Operands">operand</a>, and in <a href="#Assignments">assignments</a>.
1865 </p>
1866
1867
1868 <h3 id="Predeclared_identifiers">Predeclared identifiers</h3>
1869
1870 <p>
1871 The following identifiers are implicitly declared in the
1872 <a href="#Blocks">universe block</a>:
1873 </p>
1874 <pre class="grammar">
1875 Types:
1876         bool byte complex64 complex128 error float32 float64
1877         int int8 int16 int32 int64 rune string
1878         uint uint8 uint16 uint32 uint64 uintptr
1879
1880 Constants:
1881         true false iota
1882
1883 Zero value:
1884         nil
1885
1886 Functions:
1887         append cap close complex copy delete imag len
1888         make new panic print println real recover
1889 </pre>
1890
1891
1892 <h3 id="Exported_identifiers">Exported identifiers</h3>
1893
1894 <p>
1895 An identifier may be <i>exported</i> to permit access to it from another package.
1896 An identifier is exported if both:
1897 </p>
1898 <ol>
1899         <li>the first character of the identifier's name is a Unicode upper case
1900         letter (Unicode class "Lu"); and</li>
1901         <li>the identifier is declared in the <a href="#Blocks">package block</a>
1902         or it is a <a href="#Struct_types">field name</a> or
1903         <a href="#MethodName">method name</a>.</li>
1904 </ol>
1905 <p>
1906 All other identifiers are not exported.
1907 </p>
1908
1909
1910 <h3 id="Uniqueness_of_identifiers">Uniqueness of identifiers</h3>
1911
1912 <p>
1913 Given a set of identifiers, an identifier is called <i>unique</i> if it is
1914 <i>different</i> from every other in the set.
1915 Two identifiers are different if they are spelled differently, or if they
1916 appear in different <a href="#Packages">packages</a> and are not
1917 <a href="#Exported_identifiers">exported</a>. Otherwise, they are the same.
1918 </p>
1919
1920 <h3 id="Constant_declarations">Constant declarations</h3>
1921
1922 <p>
1923 A constant declaration binds a list of identifiers (the names of
1924 the constants) to the values of a list of <a href="#Constant_expressions">constant expressions</a>.
1925 The number of identifiers must be equal
1926 to the number of expressions, and the <i>n</i>th identifier on
1927 the left is bound to the value of the <i>n</i>th expression on the
1928 right.
1929 </p>
1930
1931 <pre class="ebnf">
1932 ConstDecl      = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1933 ConstSpec      = IdentifierList [ [ Type ] "=" ExpressionList ] .
1934
1935 IdentifierList = identifier { "," identifier } .
1936 ExpressionList = Expression { "," Expression } .
1937 </pre>
1938
1939 <p>
1940 If the type is present, all constants take the type specified, and
1941 the expressions must be <a href="#Assignability">assignable</a> to that type.
1942 If the type is omitted, the constants take the
1943 individual types of the corresponding expressions.
1944 If the expression values are untyped <a href="#Constants">constants</a>,
1945 the declared constants remain untyped and the constant identifiers
1946 denote the constant values. For instance, if the expression is a
1947 floating-point literal, the constant identifier denotes a floating-point
1948 constant, even if the literal's fractional part is zero.
1949 </p>
1950
1951 <pre>
1952 const Pi float64 = 3.14159265358979323846
1953 const zero = 0.0         // untyped floating-point constant
1954 const (
1955         size int64 = 1024
1956         eof        = -1  // untyped integer constant
1957 )
1958 const a, b, c = 3, 4, "foo"  // a = 3, b = 4, c = "foo", untyped integer and string constants
1959 const u, v float32 = 0, 3    // u = 0.0, v = 3.0
1960 </pre>
1961
1962 <p>
1963 Within a parenthesized <code>const</code> declaration list the
1964 expression list may be omitted from any but the first ConstSpec.
1965 Such an empty list is equivalent to the textual substitution of the
1966 first preceding non-empty expression list and its type if any.
1967 Omitting the list of expressions is therefore equivalent to
1968 repeating the previous list.  The number of identifiers must be equal
1969 to the number of expressions in the previous list.
1970 Together with the <a href="#Iota"><code>iota</code> constant generator</a>
1971 this mechanism permits light-weight declaration of sequential values:
1972 </p>
1973
1974 <pre>
1975 const (
1976         Sunday = iota
1977         Monday
1978         Tuesday
1979         Wednesday
1980         Thursday
1981         Friday
1982         Partyday
1983         numberOfDays  // this constant is not exported
1984 )
1985 </pre>
1986
1987
1988 <h3 id="Iota">Iota</h3>
1989
1990 <p>
1991 Within a <a href="#Constant_declarations">constant declaration</a>, the predeclared identifier
1992 <code>iota</code> represents successive untyped integer <a href="#Constants">
1993 constants</a>. Its value is the index of the respective <a href="#ConstSpec">ConstSpec</a>
1994 in that constant declaration, starting at zero.
1995 It can be used to construct a set of related constants:
1996 </p>
1997
1998 <pre>
1999 const (
2000         c0 = iota  // c0 == 0
2001         c1 = iota  // c1 == 1
2002         c2 = iota  // c2 == 2
2003 )
2004
2005 const (
2006         a = 1 &lt;&lt; iota  // a == 1  (iota == 0)
2007         b = 1 &lt;&lt; iota  // b == 2  (iota == 1)
2008         c = 3          // c == 3  (iota == 2, unused)
2009         d = 1 &lt;&lt; iota  // d == 8  (iota == 3)
2010 )
2011
2012 const (
2013         u         = iota * 42  // u == 0     (untyped integer constant)
2014         v float64 = iota * 42  // v == 42.0  (float64 constant)
2015         w         = iota * 42  // w == 84    (untyped integer constant)
2016 )
2017
2018 const x = iota  // x == 0
2019 const y = iota  // y == 0
2020 </pre>
2021
2022 <p>
2023 By definition, multiple uses of <code>iota</code> in the same ConstSpec all have the same value:
2024 </p>
2025
2026 <pre>
2027 const (
2028         bit0, mask0 = 1 &lt;&lt; iota, 1&lt;&lt;iota - 1  // bit0 == 1, mask0 == 0  (iota == 0)
2029         bit1, mask1                           // bit1 == 2, mask1 == 1  (iota == 1)
2030         _, _                                  //                        (iota == 2, unused)
2031         bit3, mask3                           // bit3 == 8, mask3 == 7  (iota == 3)
2032 )
2033 </pre>
2034
2035 <p>
2036 This last example exploits the <a href="#Constant_declarations">implicit repetition</a>
2037 of the last non-empty expression list.
2038 </p>
2039
2040
2041 <h3 id="Type_declarations">Type declarations</h3>
2042
2043 <p>
2044 A type declaration binds an identifier, the <i>type name</i>, to a <a href="#Types">type</a>.
2045 Type declarations come in two forms: alias declarations and type definitions.
2046 </p>
2047
2048 <pre class="ebnf">
2049 TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
2050 TypeSpec = AliasDecl | TypeDef .
2051 </pre>
2052
2053 <h4 id="Alias_declarations">Alias declarations</h4>
2054
2055 <p>
2056 An alias declaration binds an identifier to the given type.
2057 </p>
2058
2059 <pre class="ebnf">
2060 AliasDecl = identifier "=" Type .
2061 </pre>
2062
2063 <p>
2064 Within the <a href="#Declarations_and_scope">scope</a> of
2065 the identifier, it serves as an <i>alias</i> for the type.
2066 </p>
2067
2068 <pre>
2069 type (
2070         nodeList = []*Node  // nodeList and []*Node are identical types
2071         Polar    = polar    // Polar and polar denote identical types
2072 )
2073 </pre>
2074
2075
2076 <h4 id="Type_definitions">Type definitions</h4>
2077
2078 <p>
2079 A type definition creates a new, distinct type with the same
2080 <a href="#Types">underlying type</a> and operations as the given type,
2081 and binds an identifier to it.
2082 </p>
2083
2084 <pre class="ebnf">
2085 TypeDef = identifier Type .
2086 </pre>
2087
2088 <p>
2089 The new type is called a <i>defined type</i>.
2090 It is <a href="#Type_identity">different</a> from any other type,
2091 including the type it is created from.
2092 </p>
2093
2094 <pre>
2095 type (
2096         Point struct{ x, y float64 }  // Point and struct{ x, y float64 } are different types
2097         polar Point                   // polar and Point denote different types
2098 )
2099
2100 type TreeNode struct {
2101         left, right *TreeNode
2102         value *Comparable
2103 }
2104
2105 type Block interface {
2106         BlockSize() int
2107         Encrypt(src, dst []byte)
2108         Decrypt(src, dst []byte)
2109 }
2110 </pre>
2111
2112 <p>
2113 A defined type may have <a href="#Method_declarations">methods</a> associated with it.
2114 It does not inherit any methods bound to the given type,
2115 but the <a href="#Method_sets">method set</a>
2116 of an interface type or of elements of a composite type remains unchanged:
2117 </p>
2118
2119 <pre>
2120 // A Mutex is a data type with two methods, Lock and Unlock.
2121 type Mutex struct         { /* Mutex fields */ }
2122 func (m *Mutex) Lock()    { /* Lock implementation */ }
2123 func (m *Mutex) Unlock()  { /* Unlock implementation */ }
2124
2125 // NewMutex has the same composition as Mutex but its method set is empty.
2126 type NewMutex Mutex
2127
2128 // The method set of PtrMutex's underlying type *Mutex remains unchanged,
2129 // but the method set of PtrMutex is empty.
2130 type PtrMutex *Mutex
2131
2132 // The method set of *PrintableMutex contains the methods
2133 // Lock and Unlock bound to its embedded field Mutex.
2134 type PrintableMutex struct {
2135         Mutex
2136 }
2137
2138 // MyBlock is an interface type that has the same method set as Block.
2139 type MyBlock Block
2140 </pre>
2141
2142 <p>
2143 Type definitions may be used to define different boolean, numeric,
2144 or string types and associate methods with them:
2145 </p>
2146
2147 <pre>
2148 type TimeZone int
2149
2150 const (
2151         EST TimeZone = -(5 + iota)
2152         CST
2153         MST
2154         PST
2155 )
2156
2157 func (tz TimeZone) String() string {
2158         return fmt.Sprintf("GMT%+dh", tz)
2159 }
2160 </pre>
2161
2162
2163 <h3 id="Variable_declarations">Variable declarations</h3>
2164
2165 <p>
2166 A variable declaration creates one or more <a href="#Variables">variables</a>,
2167 binds corresponding identifiers to them, and gives each a type and an initial value.
2168 </p>
2169
2170 <pre class="ebnf">
2171 VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
2172 VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
2173 </pre>
2174
2175 <pre>
2176 var i int
2177 var U, V, W float64
2178 var k = 0
2179 var x, y float32 = -1, -2
2180 var (
2181         i       int
2182         u, v, s = 2.0, 3.0, "bar"
2183 )
2184 var re, im = complexSqrt(-1)
2185 var _, found = entries[name]  // map lookup; only interested in "found"
2186 </pre>
2187
2188 <p>
2189 If a list of expressions is given, the variables are initialized
2190 with the expressions following the rules for <a href="#Assignments">assignments</a>.
2191 Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>.
2192 </p>
2193
2194 <p>
2195 If a type is present, each variable is given that type.
2196 Otherwise, each variable is given the type of the corresponding
2197 initialization value in the assignment.
2198 If that value is an untyped constant, it is first implicitly
2199 <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>;
2200 if it is an untyped boolean value, it is first implicitly converted to type <code>bool</code>.
2201 The predeclared value <code>nil</code> cannot be used to initialize a variable
2202 with no explicit type.
2203 </p>
2204
2205 <pre>
2206 var d = math.Sin(0.5)  // d is float64
2207 var i = 42             // i is int
2208 var t, ok = x.(T)      // t is T, ok is bool
2209 var n = nil            // illegal
2210 </pre>
2211
2212 <p>
2213 Implementation restriction: A compiler may make it illegal to declare a variable
2214 inside a <a href="#Function_declarations">function body</a> if the variable is
2215 never used.
2216 </p>
2217
2218 <h3 id="Short_variable_declarations">Short variable declarations</h3>
2219
2220 <p>
2221 A <i>short variable declaration</i> uses the syntax:
2222 </p>
2223
2224 <pre class="ebnf">
2225 ShortVarDecl = IdentifierList ":=" ExpressionList .
2226 </pre>
2227
2228 <p>
2229 It is shorthand for a regular <a href="#Variable_declarations">variable declaration</a>
2230 with initializer expressions but no types:
2231 </p>
2232
2233 <pre class="grammar">
2234 "var" IdentifierList = ExpressionList .
2235 </pre>
2236
2237 <pre>
2238 i, j := 0, 10
2239 f := func() int { return 7 }
2240 ch := make(chan int)
2241 r, w, _ := os.Pipe()  // os.Pipe() returns a connected pair of Files and an error, if any
2242 _, y, _ := coord(p)   // coord() returns three values; only interested in y coordinate
2243 </pre>
2244
2245 <p>
2246 Unlike regular variable declarations, a short variable declaration may <i>redeclare</i>
2247 variables provided they were originally declared earlier in the same block
2248 (or the parameter lists if the block is the function body) with the same type,
2249 and at least one of the non-<a href="#Blank_identifier">blank</a> variables is new.
2250 As a consequence, redeclaration can only appear in a multi-variable short declaration.
2251 Redeclaration does not introduce a new variable; it just assigns a new value to the original.
2252 </p>
2253
2254 <pre>
2255 field1, offset := nextField(str, 0)
2256 field2, offset := nextField(str, offset)  // redeclares offset
2257 a, a := 1, 2                              // illegal: double declaration of a or no new variable if a was declared elsewhere
2258 </pre>
2259
2260 <p>
2261 Short variable declarations may appear only inside functions.
2262 In some contexts such as the initializers for
2263 <a href="#If_statements">"if"</a>,
2264 <a href="#For_statements">"for"</a>, or
2265 <a href="#Switch_statements">"switch"</a> statements,
2266 they can be used to declare local temporary variables.
2267 </p>
2268
2269 <h3 id="Function_declarations">Function declarations</h3>
2270
2271 <p>
2272 A function declaration binds an identifier, the <i>function name</i>,
2273 to a function.
2274 </p>
2275
2276 <pre class="ebnf">
2277 FunctionDecl = "func" FunctionName Signature [ FunctionBody ] .
2278 FunctionName = identifier .
2279 FunctionBody = Block .
2280 </pre>
2281
2282 <p>
2283 If the function's <a href="#Function_types">signature</a> declares
2284 result parameters, the function body's statement list must end in
2285 a <a href="#Terminating_statements">terminating statement</a>.
2286 </p>
2287
2288 <pre>
2289 func IndexRune(s string, r rune) int {
2290         for i, c := range s {
2291                 if c == r {
2292                         return i
2293                 }
2294         }
2295         // invalid: missing return statement
2296 }
2297 </pre>
2298
2299 <p>
2300 A function declaration may omit the body. Such a declaration provides the
2301 signature for a function implemented outside Go, such as an assembly routine.
2302 </p>
2303
2304 <pre>
2305 func min(x int, y int) int {
2306         if x &lt; y {
2307                 return x
2308         }
2309         return y
2310 }
2311
2312 func flushICache(begin, end uintptr)  // implemented externally
2313 </pre>
2314
2315 <h3 id="Method_declarations">Method declarations</h3>
2316
2317 <p>
2318 A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>.
2319 A method declaration binds an identifier, the <i>method name</i>, to a method,
2320 and associates the method with the receiver's <i>base type</i>.
2321 </p>
2322
2323 <pre class="ebnf">
2324 MethodDecl = "func" Receiver MethodName Signature [ FunctionBody ] .
2325 Receiver   = Parameters .
2326 </pre>
2327
2328 <p>
2329 The receiver is specified via an extra parameter section preceding the method
2330 name. That parameter section must declare a single non-variadic parameter, the receiver.
2331 Its type must be a <a href="#Type_definitions">defined</a> type <code>T</code> or a
2332 pointer to a defined type <code>T</code>. <code>T</code> is called the receiver
2333 <i>base type</i>. A receiver base type cannot be a pointer or interface type and
2334 it must be defined in the same package as the method.
2335 The method is said to be <i>bound</i> to its receiver base type and the method name
2336 is visible only within <a href="#Selectors">selectors</a> for type <code>T</code>
2337 or <code>*T</code>.
2338 </p>
2339
2340 <p>
2341 A non-<a href="#Blank_identifier">blank</a> receiver identifier must be
2342 <a href="#Uniqueness_of_identifiers">unique</a> in the method signature.
2343 If the receiver's value is not referenced inside the body of the method,
2344 its identifier may be omitted in the declaration. The same applies in
2345 general to parameters of functions and methods.
2346 </p>
2347
2348 <p>
2349 For a base type, the non-blank names of methods bound to it must be unique.
2350 If the base type is a <a href="#Struct_types">struct type</a>,
2351 the non-blank method and field names must be distinct.
2352 </p>
2353
2354 <p>
2355 Given defined type <code>Point</code>, the declarations
2356 </p>
2357
2358 <pre>
2359 func (p *Point) Length() float64 {
2360         return math.Sqrt(p.x * p.x + p.y * p.y)
2361 }
2362
2363 func (p *Point) Scale(factor float64) {
2364         p.x *= factor
2365         p.y *= factor
2366 }
2367 </pre>
2368
2369 <p>
2370 bind the methods <code>Length</code> and <code>Scale</code>,
2371 with receiver type <code>*Point</code>,
2372 to the base type <code>Point</code>.
2373 </p>
2374
2375 <p>
2376 The type of a method is the type of a function with the receiver as first
2377 argument.  For instance, the method <code>Scale</code> has type
2378 </p>
2379
2380 <pre>
2381 func(p *Point, factor float64)
2382 </pre>
2383
2384 <p>
2385 However, a function declared this way is not a method.
2386 </p>
2387
2388
2389 <h2 id="Expressions">Expressions</h2>
2390
2391 <p>
2392 An expression specifies the computation of a value by applying
2393 operators and functions to operands.
2394 </p>
2395
2396 <h3 id="Operands">Operands</h3>
2397
2398 <p>
2399 Operands denote the elementary values in an expression. An operand may be a
2400 literal, a (possibly <a href="#Qualified_identifiers">qualified</a>)
2401 non-<a href="#Blank_identifier">blank</a> identifier denoting a
2402 <a href="#Constant_declarations">constant</a>,
2403 <a href="#Variable_declarations">variable</a>, or
2404 <a href="#Function_declarations">function</a>,
2405 or a parenthesized expression.
2406 </p>
2407
2408 <p>
2409 The <a href="#Blank_identifier">blank identifier</a> may appear as an
2410 operand only on the left-hand side of an <a href="#Assignments">assignment</a>.
2411 </p>
2412
2413 <pre class="ebnf">
2414 Operand     = Literal | OperandName | "(" Expression ")" .
2415 Literal     = BasicLit | CompositeLit | FunctionLit .
2416 BasicLit    = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
2417 OperandName = identifier | QualifiedIdent .
2418 </pre>
2419
2420 <h3 id="Qualified_identifiers">Qualified identifiers</h3>
2421
2422 <p>
2423 A qualified identifier is an identifier qualified with a package name prefix.
2424 Both the package name and the identifier must not be
2425 <a href="#Blank_identifier">blank</a>.
2426 </p>
2427
2428 <pre class="ebnf">
2429 QualifiedIdent = PackageName "." identifier .
2430 </pre>
2431
2432 <p>
2433 A qualified identifier accesses an identifier in a different package, which
2434 must be <a href="#Import_declarations">imported</a>.
2435 The identifier must be <a href="#Exported_identifiers">exported</a> and
2436 declared in the <a href="#Blocks">package block</a> of that package.
2437 </p>
2438
2439 <pre>
2440 math.Sin        // denotes the Sin function in package math
2441 </pre>
2442
2443 <h3 id="Composite_literals">Composite literals</h3>
2444
2445 <p>
2446 Composite literals construct values for structs, arrays, slices, and maps
2447 and create a new value each time they are evaluated.
2448 They consist of the type of the literal followed by a brace-bound list of elements.
2449 Each element may optionally be preceded by a corresponding key.
2450 </p>
2451
2452 <pre class="ebnf">
2453 CompositeLit  = LiteralType LiteralValue .
2454 LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
2455                 SliceType | MapType | TypeName .
2456 LiteralValue  = "{" [ ElementList [ "," ] ] "}" .
2457 ElementList   = KeyedElement { "," KeyedElement } .
2458 KeyedElement  = [ Key ":" ] Element .
2459 Key           = FieldName | Expression | LiteralValue .
2460 FieldName     = identifier .
2461 Element       = Expression | LiteralValue .
2462 </pre>
2463
2464 <p>
2465 The LiteralType's underlying type must be a struct, array, slice, or map type
2466 (the grammar enforces this constraint except when the type is given
2467 as a TypeName).
2468 The types of the elements and keys must be <a href="#Assignability">assignable</a>
2469 to the respective field, element, and key types of the literal type;
2470 there is no additional conversion.
2471 The key is interpreted as a field name for struct literals,
2472 an index for array and slice literals, and a key for map literals.
2473 For map literals, all elements must have a key. It is an error
2474 to specify multiple elements with the same field name or
2475 constant key value. For non-constant map keys, see the section on
2476 <a href="#Order_of_evaluation">evaluation order</a>.
2477 </p>
2478
2479 <p>
2480 For struct literals the following rules apply:
2481 </p>
2482 <ul>
2483         <li>A key must be a field name declared in the struct type.
2484         </li>
2485         <li>An element list that does not contain any keys must
2486             list an element for each struct field in the
2487             order in which the fields are declared.
2488         </li>
2489         <li>If any element has a key, every element must have a key.
2490         </li>
2491         <li>An element list that contains keys does not need to
2492             have an element for each struct field. Omitted fields
2493             get the zero value for that field.
2494         </li>
2495         <li>A literal may omit the element list; such a literal evaluates
2496             to the zero value for its type.
2497         </li>
2498         <li>It is an error to specify an element for a non-exported
2499             field of a struct belonging to a different package.
2500         </li>
2501 </ul>
2502
2503 <p>
2504 Given the declarations
2505 </p>
2506 <pre>
2507 type Point3D struct { x, y, z float64 }
2508 type Line struct { p, q Point3D }
2509 </pre>
2510
2511 <p>
2512 one may write
2513 </p>
2514
2515 <pre>
2516 origin := Point3D{}                            // zero value for Point3D
2517 line := Line{origin, Point3D{y: -4, z: 12.3}}  // zero value for line.q.x
2518 </pre>
2519
2520 <p>
2521 For array and slice literals the following rules apply:
2522 </p>
2523 <ul>
2524         <li>Each element has an associated integer index marking
2525             its position in the array.
2526         </li>
2527         <li>An element with a key uses the key as its index. The
2528             key must be a non-negative constant
2529             <a href="#Representability">representable</a> by
2530             a value of type <code>int</code>; and if it is typed
2531             it must be of integer type.
2532         </li>
2533         <li>An element without a key uses the previous element's index plus one.
2534             If the first element has no key, its index is zero.
2535         </li>
2536 </ul>
2537
2538 <p>
2539 <a href="#Address_operators">Taking the address</a> of a composite literal
2540 generates a pointer to a unique <a href="#Variables">variable</a> initialized
2541 with the literal's value.
2542 </p>
2543
2544 <pre>
2545 var pointer *Point3D = &amp;Point3D{y: 1000}
2546 </pre>
2547
2548 <p>
2549 Note that the <a href="#The_zero_value">zero value</a> for a slice or map
2550 type is not the same as an initialized but empty value of the same type.
2551 Consequently, taking the address of an empty slice or map composite literal
2552 does not have the same effect as allocating a new slice or map value with
2553 <a href="#Allocation">new</a>.
2554 </p>
2555
2556 <pre>
2557 p1 := &amp;[]int{}    // p1 points to an initialized, empty slice with value []int{} and length 0
2558 p2 := new([]int)  // p2 points to an uninitialized slice with value nil and length 0
2559 </pre>
2560
2561 <p>
2562 The length of an array literal is the length specified in the literal type.
2563 If fewer elements than the length are provided in the literal, the missing
2564 elements are set to the zero value for the array element type.
2565 It is an error to provide elements with index values outside the index range
2566 of the array. The notation <code>...</code> specifies an array length equal
2567 to the maximum element index plus one.
2568 </p>
2569
2570 <pre>
2571 buffer := [10]string{}             // len(buffer) == 10
2572 intSet := [6]int{1, 2, 3, 5}       // len(intSet) == 6
2573 days := [...]string{"Sat", "Sun"}  // len(days) == 2
2574 </pre>
2575
2576 <p>
2577 A slice literal describes the entire underlying array literal.
2578 Thus the length and capacity of a slice literal are the maximum
2579 element index plus one. A slice literal has the form
2580 </p>
2581
2582 <pre>
2583 []T{x1, x2, … xn}
2584 </pre>
2585
2586 <p>
2587 and is shorthand for a slice operation applied to an array:
2588 </p>
2589
2590 <pre>
2591 tmp := [n]T{x1, x2, … xn}
2592 tmp[0 : n]
2593 </pre>
2594
2595 <p>
2596 Within a composite literal of array, slice, or map type <code>T</code>,
2597 elements or map keys that are themselves composite literals may elide the respective
2598 literal type if it is identical to the element or key type of <code>T</code>.
2599 Similarly, elements or keys that are addresses of composite literals may elide
2600 the <code>&amp;T</code> when the element or key type is <code>*T</code>.
2601 </p>
2602
2603 <pre>
2604 [...]Point{{1.5, -3.5}, {0, 0}}     // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}}
2605 [][]int{{1, 2, 3}, {4, 5}}          // same as [][]int{[]int{1, 2, 3}, []int{4, 5}}
2606 [][]Point{{{0, 1}, {1, 2}}}         // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}}
2607 map[string]Point{"orig": {0, 0}}    // same as map[string]Point{"orig": Point{0, 0}}
2608 map[Point]string{{0, 0}: "orig"}    // same as map[Point]string{Point{0, 0}: "orig"}
2609
2610 type PPoint *Point
2611 [2]*Point{{1.5, -3.5}, {}}          // same as [2]*Point{&amp;Point{1.5, -3.5}, &amp;Point{}}
2612 [2]PPoint{{1.5, -3.5}, {}}          // same as [2]PPoint{PPoint(&amp;Point{1.5, -3.5}), PPoint(&amp;Point{})}
2613 </pre>
2614
2615 <p>
2616 A parsing ambiguity arises when a composite literal using the
2617 TypeName form of the LiteralType appears as an operand between the
2618 <a href="#Keywords">keyword</a> and the opening brace of the block
2619 of an "if", "for", or "switch" statement, and the composite literal
2620 is not enclosed in parentheses, square brackets, or curly braces.
2621 In this rare case, the opening brace of the literal is erroneously parsed
2622 as the one introducing the block of statements. To resolve the ambiguity,
2623 the composite literal must appear within parentheses.
2624 </p>
2625
2626 <pre>
2627 if x == (T{a,b,c}[i]) { … }
2628 if (x == T{a,b,c}[i]) { … }
2629 </pre>
2630
2631 <p>
2632 Examples of valid array, slice, and map literals:
2633 </p>
2634
2635 <pre>
2636 // list of prime numbers
2637 primes := []int{2, 3, 5, 7, 9, 2147483647}
2638
2639 // vowels[ch] is true if ch is a vowel
2640 vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}
2641
2642 // the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1}
2643 filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1}
2644
2645 // frequencies in Hz for equal-tempered scale (A4 = 440Hz)
2646 noteFrequency := map[string]float32{
2647         "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83,
2648         "G0": 24.50, "A0": 27.50, "B0": 30.87,
2649 }
2650 </pre>
2651
2652
2653 <h3 id="Function_literals">Function literals</h3>
2654
2655 <p>
2656 A function literal represents an anonymous <a href="#Function_declarations">function</a>.
2657 </p>
2658
2659 <pre class="ebnf">
2660 FunctionLit = "func" Signature FunctionBody .
2661 </pre>
2662
2663 <pre>
2664 func(a, b int, z float64) bool { return a*b &lt; int(z) }
2665 </pre>
2666
2667 <p>
2668 A function literal can be assigned to a variable or invoked directly.
2669 </p>
2670
2671 <pre>
2672 f := func(x, y int) int { return x + y }
2673 func(ch chan int) { ch &lt;- ACK }(replyChan)
2674 </pre>
2675
2676 <p>
2677 Function literals are <i>closures</i>: they may refer to variables
2678 defined in a surrounding function. Those variables are then shared between
2679 the surrounding function and the function literal, and they survive as long
2680 as they are accessible.
2681 </p>
2682
2683
2684 <h3 id="Primary_expressions">Primary expressions</h3>
2685
2686 <p>
2687 Primary expressions are the operands for unary and binary expressions.
2688 </p>
2689
2690 <pre class="ebnf">
2691 PrimaryExpr =
2692         Operand |
2693         Conversion |
2694         MethodExpr |
2695         PrimaryExpr Selector |
2696         PrimaryExpr Index |
2697         PrimaryExpr Slice |
2698         PrimaryExpr TypeAssertion |
2699         PrimaryExpr Arguments .
2700
2701 Selector       = "." identifier .
2702 Index          = "[" Expression "]" .
2703 Slice          = "[" [ Expression ] ":" [ Expression ] "]" |
2704                  "[" [ Expression ] ":" Expression ":" Expression "]" .
2705 TypeAssertion  = "." "(" Type ")" .
2706 Arguments      = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
2707 </pre>
2708
2709
2710 <pre>
2711 x
2712 2
2713 (s + ".txt")
2714 f(3.1415, true)
2715 Point{1, 2}
2716 m["foo"]
2717 s[i : j + 1]
2718 obj.color
2719 f.p[i].x()
2720 </pre>
2721
2722
2723 <h3 id="Selectors">Selectors</h3>
2724
2725 <p>
2726 For a <a href="#Primary_expressions">primary expression</a> <code>x</code>
2727 that is not a <a href="#Package_clause">package name</a>, the
2728 <i>selector expression</i>
2729 </p>
2730
2731 <pre>
2732 x.f
2733 </pre>
2734
2735 <p>
2736 denotes the field or method <code>f</code> of the value <code>x</code>
2737 (or sometimes <code>*x</code>; see below).
2738 The identifier <code>f</code> is called the (field or method) <i>selector</i>;
2739 it must not be the <a href="#Blank_identifier">blank identifier</a>.
2740 The type of the selector expression is the type of <code>f</code>.
2741 If <code>x</code> is a package name, see the section on
2742 <a href="#Qualified_identifiers">qualified identifiers</a>.
2743 </p>
2744
2745 <p>
2746 A selector <code>f</code> may denote a field or method <code>f</code> of
2747 a type <code>T</code>, or it may refer
2748 to a field or method <code>f</code> of a nested
2749 <a href="#Struct_types">embedded field</a> of <code>T</code>.
2750 The number of embedded fields traversed
2751 to reach <code>f</code> is called its <i>depth</i> in <code>T</code>.
2752 The depth of a field or method <code>f</code>
2753 declared in <code>T</code> is zero.
2754 The depth of a field or method <code>f</code> declared in
2755 an embedded field <code>A</code> in <code>T</code> is the
2756 depth of <code>f</code> in <code>A</code> plus one.
2757 </p>
2758
2759 <p>
2760 The following rules apply to selectors:
2761 </p>
2762
2763 <ol>
2764 <li>
2765 For a value <code>x</code> of type <code>T</code> or <code>*T</code>
2766 where <code>T</code> is not a pointer or interface type,
2767 <code>x.f</code> denotes the field or method at the shallowest depth
2768 in <code>T</code> where there
2769 is such an <code>f</code>.
2770 If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a>
2771 with shallowest depth, the selector expression is illegal.
2772 </li>
2773
2774 <li>
2775 For a value <code>x</code> of type <code>I</code> where <code>I</code>
2776 is an interface type, <code>x.f</code> denotes the actual method with name
2777 <code>f</code> of the dynamic value of <code>x</code>.
2778 If there is no method with name <code>f</code> in the
2779 <a href="#Method_sets">method set</a> of <code>I</code>, the selector
2780 expression is illegal.
2781 </li>
2782
2783 <li>
2784 As an exception, if the type of <code>x</code> is a <a href="#Type_definitions">defined</a>
2785 pointer type and <code>(*x).f</code> is a valid selector expression denoting a field
2786 (but not a method), <code>x.f</code> is shorthand for <code>(*x).f</code>.
2787 </li>
2788
2789 <li>
2790 In all other cases, <code>x.f</code> is illegal.
2791 </li>
2792
2793 <li>
2794 If <code>x</code> is of pointer type and has the value
2795 <code>nil</code> and <code>x.f</code> denotes a struct field,
2796 assigning to or evaluating <code>x.f</code>
2797 causes a <a href="#Run_time_panics">run-time panic</a>.
2798 </li>
2799
2800 <li>
2801 If <code>x</code> is of interface type and has the value
2802 <code>nil</code>, <a href="#Calls">calling</a> or
2803 <a href="#Method_values">evaluating</a> the method <code>x.f</code>
2804 causes a <a href="#Run_time_panics">run-time panic</a>.
2805 </li>
2806 </ol>
2807
2808 <p>
2809 For example, given the declarations:
2810 </p>
2811
2812 <pre>
2813 type T0 struct {
2814         x int
2815 }
2816
2817 func (*T0) M0()
2818
2819 type T1 struct {
2820         y int
2821 }
2822
2823 func (T1) M1()
2824
2825 type T2 struct {
2826         z int
2827         T1
2828         *T0
2829 }
2830
2831 func (*T2) M2()
2832
2833 type Q *T2
2834
2835 var t T2     // with t.T0 != nil
2836 var p *T2    // with p != nil and (*p).T0 != nil
2837 var q Q = p
2838 </pre>
2839
2840 <p>
2841 one may write:
2842 </p>
2843
2844 <pre>
2845 t.z          // t.z
2846 t.y          // t.T1.y
2847 t.x          // (*t.T0).x
2848
2849 p.z          // (*p).z
2850 p.y          // (*p).T1.y
2851 p.x          // (*(*p).T0).x
2852
2853 q.x          // (*(*q).T0).x        (*q).x is a valid field selector
2854
2855 p.M0()       // ((*p).T0).M0()      M0 expects *T0 receiver
2856 p.M1()       // ((*p).T1).M1()      M1 expects T1 receiver
2857 p.M2()       // p.M2()              M2 expects *T2 receiver
2858 t.M2()       // (&amp;t).M2()           M2 expects *T2 receiver, see section on Calls
2859 </pre>
2860
2861 <p>
2862 but the following is invalid:
2863 </p>
2864
2865 <pre>
2866 q.M0()       // (*q).M0 is valid but not a field selector
2867 </pre>
2868
2869
2870 <h3 id="Method_expressions">Method expressions</h3>
2871
2872 <p>
2873 If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
2874 <code>T.M</code> is a function that is callable as a regular function
2875 with the same arguments as <code>M</code> prefixed by an additional
2876 argument that is the receiver of the method.
2877 </p>
2878
2879 <pre class="ebnf">
2880 MethodExpr    = ReceiverType "." MethodName .
2881 ReceiverType  = Type .
2882 </pre>
2883
2884 <p>
2885 Consider a struct type <code>T</code> with two methods,
2886 <code>Mv</code>, whose receiver is of type <code>T</code>, and
2887 <code>Mp</code>, whose receiver is of type <code>*T</code>.
2888 </p>
2889
2890 <pre>
2891 type T struct {
2892         a int
2893 }
2894 func (tv  T) Mv(a int) int         { return 0 }  // value receiver
2895 func (tp *T) Mp(f float32) float32 { return 1 }  // pointer receiver
2896
2897 var t T
2898 </pre>
2899
2900 <p>
2901 The expression
2902 </p>
2903
2904 <pre>
2905 T.Mv
2906 </pre>
2907
2908 <p>
2909 yields a function equivalent to <code>Mv</code> but
2910 with an explicit receiver as its first argument; it has signature
2911 </p>
2912
2913 <pre>
2914 func(tv T, a int) int
2915 </pre>
2916
2917 <p>
2918 That function may be called normally with an explicit receiver, so
2919 these five invocations are equivalent:
2920 </p>
2921
2922 <pre>
2923 t.Mv(7)
2924 T.Mv(t, 7)
2925 (T).Mv(t, 7)
2926 f1 := T.Mv; f1(t, 7)
2927 f2 := (T).Mv; f2(t, 7)
2928 </pre>
2929
2930 <p>
2931 Similarly, the expression
2932 </p>
2933
2934 <pre>
2935 (*T).Mp
2936 </pre>
2937
2938 <p>
2939 yields a function value representing <code>Mp</code> with signature
2940 </p>
2941
2942 <pre>
2943 func(tp *T, f float32) float32
2944 </pre>
2945
2946 <p>
2947 For a method with a value receiver, one can derive a function
2948 with an explicit pointer receiver, so
2949 </p>
2950
2951 <pre>
2952 (*T).Mv
2953 </pre>
2954
2955 <p>
2956 yields a function value representing <code>Mv</code> with signature
2957 </p>
2958
2959 <pre>
2960 func(tv *T, a int) int
2961 </pre>
2962
2963 <p>
2964 Such a function indirects through the receiver to create a value
2965 to pass as the receiver to the underlying method;
2966 the method does not overwrite the value whose address is passed in
2967 the function call.
2968 </p>
2969
2970 <p>
2971 The final case, a value-receiver function for a pointer-receiver method,
2972 is illegal because pointer-receiver methods are not in the method set
2973 of the value type.
2974 </p>
2975
2976 <p>
2977 Function values derived from methods are called with function call syntax;
2978 the receiver is provided as the first argument to the call.
2979 That is, given <code>f := T.Mv</code>, <code>f</code> is invoked
2980 as <code>f(t, 7)</code> not <code>t.f(7)</code>.
2981 To construct a function that binds the receiver, use a
2982 <a href="#Function_literals">function literal</a> or
2983 <a href="#Method_values">method value</a>.
2984 </p>
2985
2986 <p>
2987 It is legal to derive a function value from a method of an interface type.
2988 The resulting function takes an explicit receiver of that interface type.
2989 </p>
2990
2991 <h3 id="Method_values">Method values</h3>
2992
2993 <p>
2994 If the expression <code>x</code> has static type <code>T</code> and
2995 <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
2996 <code>x.M</code> is called a <i>method value</i>.
2997 The method value <code>x.M</code> is a function value that is callable
2998 with the same arguments as a method call of <code>x.M</code>.
2999 The expression <code>x</code> is evaluated and saved during the evaluation of the
3000 method value; the saved copy is then used as the receiver in any calls,
3001 which may be executed later.
3002 </p>
3003
3004 <pre>
3005 type S struct { *T }
3006 type T int
3007 func (t T) M() { print(t) }
3008
3009 t := new(T)
3010 s := S{T: t}
3011 f := t.M                    // receiver *t is evaluated and stored in f
3012 g := s.M                    // receiver *(s.T) is evaluated and stored in g
3013 *t = 42                     // does not affect stored receivers in f and g
3014 </pre>
3015
3016 <p>
3017 The type <code>T</code> may be an interface or non-interface type.
3018 </p>
3019
3020 <p>
3021 As in the discussion of <a href="#Method_expressions">method expressions</a> above,
3022 consider a struct type <code>T</code> with two methods,
3023 <code>Mv</code>, whose receiver is of type <code>T</code>, and
3024 <code>Mp</code>, whose receiver is of type <code>*T</code>.
3025 </p>
3026
3027 <pre>
3028 type T struct {
3029         a int
3030 }
3031 func (tv  T) Mv(a int) int         { return 0 }  // value receiver
3032 func (tp *T) Mp(f float32) float32 { return 1 }  // pointer receiver
3033
3034 var t T
3035 var pt *T
3036 func makeT() T
3037 </pre>
3038
3039 <p>
3040 The expression
3041 </p>
3042
3043 <pre>
3044 t.Mv
3045 </pre>
3046
3047 <p>
3048 yields a function value of type
3049 </p>
3050
3051 <pre>
3052 func(int) int
3053 </pre>
3054
3055 <p>
3056 These two invocations are equivalent:
3057 </p>
3058
3059 <pre>
3060 t.Mv(7)
3061 f := t.Mv; f(7)
3062 </pre>
3063
3064 <p>
3065 Similarly, the expression
3066 </p>
3067
3068 <pre>
3069 pt.Mp
3070 </pre>
3071
3072 <p>
3073 yields a function value of type
3074 </p>
3075
3076 <pre>
3077 func(float32) float32
3078 </pre>
3079
3080 <p>
3081 As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver
3082 using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>.
3083 </p>
3084
3085 <p>
3086 As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver
3087 using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&amp;t).Mp</code>.
3088 </p>
3089
3090 <pre>
3091 f := t.Mv; f(7)   // like t.Mv(7)
3092 f := pt.Mp; f(7)  // like pt.Mp(7)
3093 f := pt.Mv; f(7)  // like (*pt).Mv(7)
3094 f := t.Mp; f(7)   // like (&amp;t).Mp(7)
3095 f := makeT().Mp   // invalid: result of makeT() is not addressable
3096 </pre>
3097
3098 <p>
3099 Although the examples above use non-interface types, it is also legal to create a method value
3100 from a value of interface type.
3101 </p>
3102
3103 <pre>
3104 var i interface { M(int) } = myVal
3105 f := i.M; f(7)  // like i.M(7)
3106 </pre>
3107
3108
3109 <h3 id="Index_expressions">Index expressions</h3>
3110
3111 <p>
3112 A primary expression of the form
3113 </p>
3114
3115 <pre>
3116 a[x]
3117 </pre>
3118
3119 <p>
3120 denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>.
3121 The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively.
3122 The following rules apply:
3123 </p>
3124
3125 <p>
3126 If <code>a</code> is not a map:
3127 </p>
3128 <ul>
3129         <li>the index <code>x</code> must be of integer type or an untyped constant</li>
3130         <li>a constant index must be non-negative and
3131             <a href="#Representability">representable</a> by a value of type <code>int</code></li>
3132         <li>a constant index that is untyped is given type <code>int</code></li>
3133         <li>the index <code>x</code> is <i>in range</i> if <code>0 &lt;= x &lt; len(a)</code>,
3134             otherwise it is <i>out of range</i></li>
3135 </ul>
3136
3137 <p>
3138 For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>:
3139 </p>
3140 <ul>
3141         <li>a <a href="#Constants">constant</a> index must be in range</li>
3142         <li>if <code>x</code> is out of range at run time,
3143             a <a href="#Run_time_panics">run-time panic</a> occurs</li>
3144         <li><code>a[x]</code> is the array element at index <code>x</code> and the type of
3145             <code>a[x]</code> is the element type of <code>A</code></li>
3146 </ul>
3147
3148 <p>
3149 For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type:
3150 </p>
3151 <ul>
3152         <li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li>
3153 </ul>
3154
3155 <p>
3156 For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>:
3157 </p>
3158 <ul>
3159         <li>if <code>x</code> is out of range at run time,
3160             a <a href="#Run_time_panics">run-time panic</a> occurs</li>
3161         <li><code>a[x]</code> is the slice element at index <code>x</code> and the type of
3162             <code>a[x]</code> is the element type of <code>S</code></li>
3163 </ul>
3164
3165 <p>
3166 For <code>a</code> of <a href="#String_types">string type</a>:
3167 </p>
3168 <ul>
3169         <li>a <a href="#Constants">constant</a> index must be in range
3170             if the string <code>a</code> is also constant</li>
3171         <li>if <code>x</code> is out of range at run time,
3172             a <a href="#Run_time_panics">run-time panic</a> occurs</li>
3173         <li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of
3174             <code>a[x]</code> is <code>byte</code></li>
3175         <li><code>a[x]</code> may not be assigned to</li>
3176 </ul>
3177
3178 <p>
3179 For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>:
3180 </p>
3181 <ul>
3182         <li><code>x</code>'s type must be
3183             <a href="#Assignability">assignable</a>
3184             to the key type of <code>M</code></li>
3185         <li>if the map contains an entry with key <code>x</code>,
3186             <code>a[x]</code> is the map element with key <code>x</code>
3187             and the type of <code>a[x]</code> is the element type of <code>M</code></li>
3188         <li>if the map is <code>nil</code> or does not contain such an entry,
3189             <code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
3190             for the element type of <code>M</code></li>
3191 </ul>
3192
3193 <p>
3194 Otherwise <code>a[x]</code> is illegal.
3195 </p>
3196
3197 <p>
3198 An index expression on a map <code>a</code> of type <code>map[K]V</code>
3199 used in an <a href="#Assignments">assignment</a> or initialization of the special form
3200 </p>
3201
3202 <pre>
3203 v, ok = a[x]
3204 v, ok := a[x]
3205 var v, ok = a[x]
3206 </pre>
3207
3208 <p>
3209 yields an additional untyped boolean value. The value of <code>ok</code> is
3210 <code>true</code> if the key <code>x</code> is present in the map, and
3211 <code>false</code> otherwise.
3212 </p>
3213
3214 <p>
3215 Assigning to an element of a <code>nil</code> map causes a
3216 <a href="#Run_time_panics">run-time panic</a>.
3217 </p>
3218
3219
3220 <h3 id="Slice_expressions">Slice expressions</h3>
3221
3222 <p>
3223 Slice expressions construct a substring or slice from a string, array, pointer
3224 to array, or slice. There are two variants: a simple form that specifies a low
3225 and high bound, and a full form that also specifies a bound on the capacity.
3226 </p>
3227
3228 <h4>Simple slice expressions</h4>
3229
3230 <p>
3231 For a string, array, pointer to array, or slice <code>a</code>, the primary expression
3232 </p>
3233
3234 <pre>
3235 a[low : high]
3236 </pre>
3237
3238 <p>
3239 constructs a substring or slice. The <i>indices</i> <code>low</code> and
3240 <code>high</code> select which elements of operand <code>a</code> appear
3241 in the result. The result has indices starting at 0 and length equal to
3242 <code>high</code>&nbsp;-&nbsp;<code>low</code>.
3243 After slicing the array <code>a</code>
3244 </p>
3245
3246 <pre>
3247 a := [5]int{1, 2, 3, 4, 5}
3248 s := a[1:4]
3249 </pre>
3250
3251 <p>
3252 the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements
3253 </p>
3254
3255 <pre>
3256 s[0] == 2
3257 s[1] == 3
3258 s[2] == 4
3259 </pre>
3260
3261 <p>
3262 For convenience, any of the indices may be omitted. A missing <code>low</code>
3263 index defaults to zero; a missing <code>high</code> index defaults to the length of the
3264 sliced operand:
3265 </p>
3266
3267 <pre>
3268 a[2:]  // same as a[2 : len(a)]
3269 a[:3]  // same as a[0 : 3]
3270 a[:]   // same as a[0 : len(a)]
3271 </pre>
3272
3273 <p>
3274 If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for
3275 <code>(*a)[low : high]</code>.
3276 </p>
3277
3278 <p>
3279 For arrays or strings, the indices are <i>in range</i> if
3280 <code>0</code> &lt;= <code>low</code> &lt;= <code>high</code> &lt;= <code>len(a)</code>,
3281 otherwise they are <i>out of range</i>.
3282 For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length.
3283 A <a href="#Constants">constant</a> index must be non-negative and
3284 <a href="#Representability">representable</a> by a value of type
3285 <code>int</code>; for arrays or constant strings, constant indices must also be in range.
3286 If both indices are constant, they must satisfy <code>low &lt;= high</code>.
3287 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3288 </p>
3289
3290 <p>
3291 Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice,
3292 the result of the slice operation is a non-constant value of the same type as the operand.
3293 For untyped string operands the result is a non-constant value of type <code>string</code>.
3294 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>
3295 and the result of the slice operation is a slice with the same element type as the array.
3296 </p>
3297
3298 <p>
3299 If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result
3300 is a <code>nil</code> slice. Otherwise, if the result is a slice, it shares its underlying
3301 array with the operand.
3302 </p>
3303
3304 <pre>
3305 var a [10]int
3306 s1 := a[3:7]   // underlying array of s1 is array a; &amp;s1[2] == &amp;a[5]
3307 s2 := s1[1:4]  // underlying array of s2 is underlying array of s1 which is array a; &amp;s2[1] == &amp;a[5]
3308 s2[1] = 42     // s2[1] == s1[2] == a[5] == 42; they all refer to the same underlying array element
3309 </pre>
3310
3311
3312 <h4>Full slice expressions</h4>
3313
3314 <p>
3315 For an array, pointer to array, or slice <code>a</code> (but not a string), the primary expression
3316 </p>
3317
3318 <pre>
3319 a[low : high : max]
3320 </pre>
3321
3322 <p>
3323 constructs a slice of the same type, and with the same length and elements as the simple slice
3324 expression <code>a[low : high]</code>. Additionally, it controls the resulting slice's capacity
3325 by setting it to <code>max - low</code>. Only the first index may be omitted; it defaults to 0.
3326 After slicing the array <code>a</code>
3327 </p>
3328
3329 <pre>
3330 a := [5]int{1, 2, 3, 4, 5}
3331 t := a[1:3:5]
3332 </pre>
3333
3334 <p>
3335 the slice <code>t</code> has type <code>[]int</code>, length 2, capacity 4, and elements
3336 </p>
3337
3338 <pre>
3339 t[0] == 2
3340 t[1] == 3
3341 </pre>
3342
3343 <p>
3344 As for simple slice expressions, if <code>a</code> is a pointer to an array,
3345 <code>a[low : high : max]</code> is shorthand for <code>(*a)[low : high : max]</code>.
3346 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>.
3347 </p>
3348
3349 <p>
3350 The indices are <i>in range</i> if <code>0 &lt;= low &lt;= high &lt;= max &lt;= cap(a)</code>,
3351 otherwise they are <i>out of range</i>.
3352 A <a href="#Constants">constant</a> index must be non-negative and
3353 <a href="#Representability">representable</a> by a value of type
3354 <code>int</code>; for arrays, constant indices must also be in range.
3355 If multiple indices are constant, the constants that are present must be in range relative to each
3356 other.
3357 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3358 </p>
3359
3360 <h3 id="Type_assertions">Type assertions</h3>
3361
3362 <p>
3363 For an expression <code>x</code> of <a href="#Interface_types">interface type</a>
3364 and a type <code>T</code>, the primary expression
3365 </p>
3366
3367 <pre>
3368 x.(T)
3369 </pre>
3370
3371 <p>
3372 asserts that <code>x</code> is not <code>nil</code>
3373 and that the value stored in <code>x</code> is of type <code>T</code>.
3374 The notation <code>x.(T)</code> is called a <i>type assertion</i>.
3375 </p>
3376 <p>
3377 More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
3378 that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a>
3379 to the type <code>T</code>.
3380 In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>;
3381 otherwise the type assertion is invalid since it is not possible for <code>x</code>
3382 to store a value of type <code>T</code>.
3383 If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
3384 of <code>x</code> implements the interface <code>T</code>.
3385 </p>
3386 <p>
3387 If the type assertion holds, the value of the expression is the value
3388 stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false,
3389 a <a href="#Run_time_panics">run-time panic</a> occurs.
3390 In other words, even though the dynamic type of <code>x</code>
3391 is known only at run time, the type of <code>x.(T)</code> is
3392 known to be <code>T</code> in a correct program.
3393 </p>
3394
3395 <pre>
3396 var x interface{} = 7          // x has dynamic type int and value 7
3397 i := x.(int)                   // i has type int and value 7
3398
3399 type I interface { m() }
3400
3401 func f(y I) {
3402         s := y.(string)        // illegal: string does not implement I (missing method m)
3403         r := y.(io.Reader)     // r has type io.Reader and the dynamic type of y must implement both I and io.Reader
3404         …
3405 }
3406 </pre>
3407
3408 <p>
3409 A type assertion used in an <a href="#Assignments">assignment</a> or initialization of the special form
3410 </p>
3411
3412 <pre>
3413 v, ok = x.(T)
3414 v, ok := x.(T)
3415 var v, ok = x.(T)
3416 var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool
3417 </pre>
3418
3419 <p>
3420 yields an additional untyped boolean value. The value of <code>ok</code> is <code>true</code>
3421 if the assertion holds. Otherwise it is <code>false</code> and the value of <code>v</code> is
3422 the <a href="#The_zero_value">zero value</a> for type <code>T</code>.
3423 No <a href="#Run_time_panics">run-time panic</a> occurs in this case.
3424 </p>
3425
3426
3427 <h3 id="Calls">Calls</h3>
3428
3429 <p>
3430 Given an expression <code>f</code> of function type
3431 <code>F</code>,
3432 </p>
3433
3434 <pre>
3435 f(a1, a2, … an)
3436 </pre>
3437
3438 <p>
3439 calls <code>f</code> with arguments <code>a1, a2, … an</code>.
3440 Except for one special case, arguments must be single-valued expressions
3441 <a href="#Assignability">assignable</a> to the parameter types of
3442 <code>F</code> and are evaluated before the function is called.
3443 The type of the expression is the result type
3444 of <code>F</code>.
3445 A method invocation is similar but the method itself
3446 is specified as a selector upon a value of the receiver type for
3447 the method.
3448 </p>
3449
3450 <pre>
3451 math.Atan2(x, y)  // function call
3452 var pt *Point
3453 pt.Scale(3.5)     // method call with receiver pt
3454 </pre>
3455
3456 <p>
3457 In a function call, the function value and arguments are evaluated in
3458 <a href="#Order_of_evaluation">the usual order</a>.
3459 After they are evaluated, the parameters of the call are passed by value to the function
3460 and the called function begins execution.
3461 The return parameters of the function are passed by value
3462 back to the caller when the function returns.
3463 </p>
3464
3465 <p>
3466 Calling a <code>nil</code> function value
3467 causes a <a href="#Run_time_panics">run-time panic</a>.
3468 </p>
3469
3470 <p>
3471 As a special case, if the return values of a function or method
3472 <code>g</code> are equal in number and individually
3473 assignable to the parameters of another function or method
3474 <code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code>
3475 will invoke <code>f</code> after binding the return values of
3476 <code>g</code> to the parameters of <code>f</code> in order.  The call
3477 of <code>f</code> must contain no parameters other than the call of <code>g</code>,
3478 and <code>g</code> must have at least one return value.
3479 If <code>f</code> has a final <code>...</code> parameter, it is
3480 assigned the return values of <code>g</code> that remain after
3481 assignment of regular parameters.
3482 </p>
3483
3484 <pre>
3485 func Split(s string, pos int) (string, string) {
3486         return s[0:pos], s[pos:]
3487 }
3488
3489 func Join(s, t string) string {
3490         return s + t
3491 }
3492
3493 if Join(Split(value, len(value)/2)) != value {
3494         log.Panic("test fails")
3495 }
3496 </pre>
3497
3498 <p>
3499 A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a>
3500 of (the type of) <code>x</code> contains <code>m</code> and the
3501 argument list can be assigned to the parameter list of <code>m</code>.
3502 If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&amp;x</code>'s method
3503 set contains <code>m</code>, <code>x.m()</code> is shorthand
3504 for <code>(&amp;x).m()</code>:
3505 </p>
3506
3507 <pre>
3508 var p Point
3509 p.Scale(3.5)
3510 </pre>
3511
3512 <p>
3513 There is no distinct method type and there are no method literals.
3514 </p>
3515
3516 <h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3>
3517
3518 <p>
3519 If <code>f</code> is <a href="#Function_types">variadic</a> with a final
3520 parameter <code>p</code> of type <code>...T</code>, then within <code>f</code>
3521 the type of <code>p</code> is equivalent to type <code>[]T</code>.
3522 If <code>f</code> is invoked with no actual arguments for <code>p</code>,
3523 the value passed to <code>p</code> is <code>nil</code>.
3524 Otherwise, the value passed is a new slice
3525 of type <code>[]T</code> with a new underlying array whose successive elements
3526 are the actual arguments, which all must be <a href="#Assignability">assignable</a>
3527 to <code>T</code>. The length and capacity of the slice is therefore
3528 the number of arguments bound to <code>p</code> and may differ for each
3529 call site.
3530 </p>
3531
3532 <p>
3533 Given the function and calls
3534 </p>
3535 <pre>
3536 func Greeting(prefix string, who ...string)
3537 Greeting("nobody")
3538 Greeting("hello:", "Joe", "Anna", "Eileen")
3539 </pre>
3540
3541 <p>
3542 within <code>Greeting</code>, <code>who</code> will have the value
3543 <code>nil</code> in the first call, and
3544 <code>[]string{"Joe", "Anna", "Eileen"}</code> in the second.
3545 </p>
3546
3547 <p>
3548 If the final argument is assignable to a slice type <code>[]T</code> and
3549 is followed by <code>...</code>, it is passed unchanged as the value
3550 for a <code>...T</code> parameter. In this case no new slice is created.
3551 </p>
3552
3553 <p>
3554 Given the slice <code>s</code> and call
3555 </p>
3556
3557 <pre>
3558 s := []string{"James", "Jasmine"}
3559 Greeting("goodbye:", s...)
3560 </pre>
3561
3562 <p>
3563 within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code>
3564 with the same underlying array.
3565 </p>
3566
3567
3568 <h3 id="Operators">Operators</h3>
3569
3570 <p>
3571 Operators combine operands into expressions.
3572 </p>
3573
3574 <pre class="ebnf">
3575 Expression = UnaryExpr | Expression binary_op Expression .
3576 UnaryExpr  = PrimaryExpr | unary_op UnaryExpr .
3577
3578 binary_op  = "||" | "&amp;&amp;" | rel_op | add_op | mul_op .
3579 rel_op     = "==" | "!=" | "&lt;" | "&lt;=" | ">" | ">=" .
3580 add_op     = "+" | "-" | "|" | "^" .
3581 mul_op     = "*" | "/" | "%" | "&lt;&lt;" | "&gt;&gt;" | "&amp;" | "&amp;^" .
3582
3583 unary_op   = "+" | "-" | "!" | "^" | "*" | "&amp;" | "&lt;-" .
3584 </pre>
3585
3586 <p>
3587 Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>.
3588 For other binary operators, the operand types must be <a href="#Type_identity">identical</a>
3589 unless the operation involves shifts or untyped <a href="#Constants">constants</a>.
3590 For operations involving constants only, see the section on
3591 <a href="#Constant_expressions">constant expressions</a>.
3592 </p>
3593
3594 <p>
3595 Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a>
3596 and the other operand is not, the constant is implicitly <a href="#Conversions">converted</a>
3597 to the type of the other operand.
3598 </p>
3599
3600 <p>
3601 The right operand in a shift expression must have integer type
3602 or be an untyped constant <a href="#Representability">representable</a> by a
3603 value of type <code>uint</code>.
3604 If the left operand of a non-constant shift expression is an untyped constant,
3605 it is first implicitly converted to the type it would assume if the shift expression were
3606 replaced by its left operand alone.
3607 </p>
3608
3609 <pre>
3610 var a [1024]byte
3611 var s uint = 33
3612
3613 // The results of the following examples are given for 64-bit ints.
3614 var i = 1&lt;&lt;s                   // 1 has type int
3615 var j int32 = 1&lt;&lt;s             // 1 has type int32; j == 0
3616 var k = uint64(1&lt;&lt;s)           // 1 has type uint64; k == 1&lt;&lt;33
3617 var m int = 1.0&lt;&lt;s             // 1.0 has type int; m == 1&lt;&lt;33
3618 var n = 1.0&lt;&lt;s == j            // 1.0 has type int32; n == true
3619 var o = 1&lt;&lt;s == 2&lt;&lt;s           // 1 and 2 have type int; o == false
3620 var p = 1&lt;&lt;s == 1&lt;&lt;33          // 1 has type int; p == true
3621 var u = 1.0&lt;&lt;s                 // illegal: 1.0 has type float64, cannot shift
3622 var u1 = 1.0&lt;&lt;s != 0           // illegal: 1.0 has type float64, cannot shift
3623 var u2 = 1&lt;&lt;s != 1.0           // illegal: 1 has type float64, cannot shift
3624 var v float32 = 1&lt;&lt;s           // illegal: 1 has type float32, cannot shift
3625 var w int64 = 1.0&lt;&lt;33          // 1.0&lt;&lt;33 is a constant shift expression; w == 1&lt;&lt;33
3626 var x = a[1.0&lt;&lt;s]              // panics: 1.0 has type int, but 1&lt;&lt;33 overflows array bounds
3627 var b = make([]byte, 1.0&lt;&lt;s)   // 1.0 has type int; len(b) == 1&lt;&lt;33
3628
3629 // The results of the following examples are given for 32-bit ints,
3630 // which means the shifts will overflow.
3631 var mm int = 1.0&lt;&lt;s            // 1.0 has type int; mm == 0
3632 var oo = 1&lt;&lt;s == 2&lt;&lt;s          // 1 and 2 have type int; oo == true
3633 var pp = 1&lt;&lt;s == 1&lt;&lt;33         // illegal: 1 has type int, but 1&lt;&lt;33 overflows int
3634 var xx = a[1.0&lt;&lt;s]             // 1.0 has type int; xx == a[0]
3635 var bb = make([]byte, 1.0&lt;&lt;s)  // 1.0 has type int; len(bb) == 0
3636 </pre>
3637
3638 <h4 id="Operator_precedence">Operator precedence</h4>
3639 <p>
3640 Unary operators have the highest precedence.
3641 As the  <code>++</code> and <code>--</code> operators form
3642 statements, not expressions, they fall
3643 outside the operator hierarchy.
3644 As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>.
3645 </p>
3646
3647 <p>
3648 There are five precedence levels for binary operators.
3649 Multiplication operators bind strongest, followed by addition
3650 operators, comparison operators, <code>&amp;&amp;</code> (logical AND),
3651 and finally <code>||</code> (logical OR):
3652 </p>
3653
3654 <pre class="grammar">
3655 Precedence    Operator
3656     5             *  /  %  &lt;&lt;  &gt;&gt;  &amp;  &amp;^
3657     4             +  -  |  ^
3658     3             ==  !=  &lt;  &lt;=  &gt;  &gt;=
3659     2             &amp;&amp;
3660     1             ||
3661 </pre>
3662
3663 <p>
3664 Binary operators of the same precedence associate from left to right.
3665 For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>.
3666 </p>
3667
3668 <pre>
3669 +x
3670 23 + 3*x[i]
3671 x &lt;= f()
3672 ^a &gt;&gt; b
3673 f() || g()
3674 x == y+1 &amp;&amp; &lt;-chanInt &gt; 0
3675 </pre>
3676
3677
3678 <h3 id="Arithmetic_operators">Arithmetic operators</h3>
3679 <p>
3680 Arithmetic operators apply to numeric values and yield a result of the same
3681 type as the first operand. The four standard arithmetic operators (<code>+</code>,
3682 <code>-</code>, <code>*</code>, <code>/</code>) apply to integer,
3683 floating-point, and complex types; <code>+</code> also applies to strings.
3684 The bitwise logical and shift operators apply to integers only.
3685 </p>
3686
3687 <pre class="grammar">
3688 +    sum                    integers, floats, complex values, strings
3689 -    difference             integers, floats, complex values
3690 *    product                integers, floats, complex values
3691 /    quotient               integers, floats, complex values
3692 %    remainder              integers
3693
3694 &amp;    bitwise AND            integers
3695 |    bitwise OR             integers
3696 ^    bitwise XOR            integers
3697 &amp;^   bit clear (AND NOT)    integers
3698
3699 &lt;&lt;   left shift             integer &lt;&lt; integer &gt;= 0
3700 &gt;&gt;   right shift            integer &gt;&gt; integer &gt;= 0
3701 </pre>
3702
3703
3704 <h4 id="Integer_operators">Integer operators</h4>
3705
3706 <p>
3707 For two integer values <code>x</code> and <code>y</code>, the integer quotient
3708 <code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following
3709 relationships:
3710 </p>
3711
3712 <pre>
3713 x = q*y + r  and  |r| &lt; |y|
3714 </pre>
3715
3716 <p>
3717 with <code>x / y</code> truncated towards zero
3718 (<a href="https://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>).
3719 </p>
3720
3721 <pre>
3722  x     y     x / y     x % y
3723  5     3       1         2
3724 -5     3      -1        -2
3725  5    -3      -1         2
3726 -5    -3       1        -2
3727 </pre>
3728
3729 <p>
3730 The one exception to this rule is that if the dividend <code>x</code> is
3731 the most negative value for the int type of <code>x</code>, the quotient
3732 <code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>)
3733 due to two's-complement <a href="#Integer_overflow">integer overflow</a>:
3734 </p>
3735
3736 <pre>
3737                          x, q
3738 int8                     -128
3739 int16                  -32768
3740 int32             -2147483648
3741 int64    -9223372036854775808
3742 </pre>
3743
3744 <p>
3745 If the divisor is a <a href="#Constants">constant</a>, it must not be zero.
3746 If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3747 If the dividend is non-negative and the divisor is a constant power of 2,
3748 the division may be replaced by a right shift, and computing the remainder may
3749 be replaced by a bitwise AND operation:
3750 </p>
3751
3752 <pre>
3753  x     x / 4     x % 4     x &gt;&gt; 2     x &amp; 3
3754  11      2         3         2          3
3755 -11     -2        -3        -3          1
3756 </pre>
3757
3758 <p>
3759 The shift operators shift the left operand by the shift count specified by the
3760 right operand, which must be non-negative. If the shift count is negative at run time,
3761 a <a href="#Run_time_panics">run-time panic</a> occurs.
3762 The shift operators implement arithmetic shifts if the left operand is a signed
3763 integer and logical shifts if it is an unsigned integer.
3764 There is no upper limit on the shift count. Shifts behave
3765 as if the left operand is shifted <code>n</code> times by 1 for a shift
3766 count of <code>n</code>.
3767 As a result, <code>x &lt;&lt; 1</code> is the same as <code>x*2</code>
3768 and <code>x &gt;&gt; 1</code> is the same as
3769 <code>x/2</code> but truncated towards negative infinity.
3770 </p>
3771
3772 <p>
3773 For integer operands, the unary operators
3774 <code>+</code>, <code>-</code>, and <code>^</code> are defined as
3775 follows:
3776 </p>
3777
3778 <pre class="grammar">
3779 +x                          is 0 + x
3780 -x    negation              is 0 - x
3781 ^x    bitwise complement    is m ^ x  with m = "all bits set to 1" for unsigned x
3782                                       and  m = -1 for signed x
3783 </pre>
3784
3785
3786 <h4 id="Integer_overflow">Integer overflow</h4>
3787
3788 <p>
3789 For unsigned integer values, the operations <code>+</code>,
3790 <code>-</code>, <code>*</code>, and <code>&lt;&lt;</code> are
3791 computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of
3792 the <a href="#Numeric_types">unsigned integer</a>'s type.
3793 Loosely speaking, these unsigned integer operations
3794 discard high bits upon overflow, and programs may rely on "wrap around".
3795 </p>
3796 <p>
3797 For signed integers, the operations <code>+</code>,
3798 <code>-</code>, <code>*</code>, <code>/</code>, and <code>&lt;&lt;</code> may legally
3799 overflow and the resulting value exists and is deterministically defined
3800 by the signed integer representation, the operation, and its operands.
3801 Overflow does not cause a <a href="#Run_time_panics">run-time panic</a>.
3802 A compiler may not optimize code under the assumption that overflow does
3803 not occur. For instance, it may not assume that <code>x &lt; x + 1</code> is always true.
3804 </p>
3805
3806
3807 <h4 id="Floating_point_operators">Floating-point operators</h4>
3808
3809 <p>
3810 For floating-point and complex numbers,
3811 <code>+x</code> is the same as <code>x</code>,
3812 while <code>-x</code> is the negation of <code>x</code>.
3813 The result of a floating-point or complex division by zero is not specified beyond the
3814 IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a>
3815 occurs is implementation-specific.
3816 </p>
3817
3818 <p>
3819 An implementation may combine multiple floating-point operations into a single
3820 fused operation, possibly across statements, and produce a result that differs
3821 from the value obtained by executing and rounding the instructions individually.
3822 An explicit floating-point type <a href="#Conversions">conversion</a> rounds to
3823 the precision of the target type, preventing fusion that would discard that rounding.
3824 </p>
3825
3826 <p>
3827 For instance, some architectures provide a "fused multiply and add" (FMA) instruction
3828 that computes <code>x*y + z</code> without rounding the intermediate result <code>x*y</code>.
3829 These examples show when a Go implementation can use that instruction:
3830 </p>
3831
3832 <pre>
3833 // FMA allowed for computing r, because x*y is not explicitly rounded:
3834 r  = x*y + z
3835 r  = z;   r += x*y
3836 t  = x*y; r = t + z
3837 *p = x*y; r = *p + z
3838 r  = x*y + float64(z)
3839
3840 // FMA disallowed for computing r, because it would omit rounding of x*y:
3841 r  = float64(x*y) + z
3842 r  = z; r += float64(x*y)
3843 t  = float64(x*y); r = t + z
3844 </pre>
3845
3846 <h4 id="String_concatenation">String concatenation</h4>
3847
3848 <p>
3849 Strings can be concatenated using the <code>+</code> operator
3850 or the <code>+=</code> assignment operator:
3851 </p>
3852
3853 <pre>
3854 s := "hi" + string(c)
3855 s += " and good bye"
3856 </pre>
3857
3858 <p>
3859 String addition creates a new string by concatenating the operands.
3860 </p>
3861
3862
3863 <h3 id="Comparison_operators">Comparison operators</h3>
3864
3865 <p>
3866 Comparison operators compare two operands and yield an untyped boolean value.
3867 </p>
3868
3869 <pre class="grammar">
3870 ==    equal
3871 !=    not equal
3872 &lt;     less
3873 &lt;=    less or equal
3874 &gt;     greater
3875 &gt;=    greater or equal
3876 </pre>
3877
3878 <p>
3879 In any comparison, the first operand
3880 must be <a href="#Assignability">assignable</a>
3881 to the type of the second operand, or vice versa.
3882 </p>
3883 <p>
3884 The equality operators <code>==</code> and <code>!=</code> apply
3885 to operands that are <i>comparable</i>.
3886 The ordering operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code>
3887 apply to operands that are <i>ordered</i>.
3888 These terms and the result of the comparisons are defined as follows:
3889 </p>
3890
3891 <ul>
3892         <li>
3893         Boolean values are comparable.
3894         Two boolean values are equal if they are either both
3895         <code>true</code> or both <code>false</code>.
3896         </li>
3897
3898         <li>
3899         Integer values are comparable and ordered, in the usual way.
3900         </li>
3901
3902         <li>
3903         Floating-point values are comparable and ordered,
3904         as defined by the IEEE-754 standard.
3905         </li>
3906
3907         <li>
3908         Complex values are comparable.
3909         Two complex values <code>u</code> and <code>v</code> are
3910         equal if both <code>real(u) == real(v)</code> and
3911         <code>imag(u) == imag(v)</code>.
3912         </li>
3913
3914         <li>
3915         String values are comparable and ordered, lexically byte-wise.
3916         </li>
3917
3918         <li>
3919         Pointer values are comparable.
3920         Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>.
3921         Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal.
3922         </li>
3923
3924         <li>
3925         Channel values are comparable.
3926         Two channel values are equal if they were created by the same call to
3927         <a href="#Making_slices_maps_and_channels"><code>make</code></a>
3928         or if both have value <code>nil</code>.
3929         </li>
3930
3931         <li>
3932         Interface values are comparable.
3933         Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types
3934         and equal dynamic values or if both have value <code>nil</code>.
3935         </li>
3936
3937         <li>
3938         A value <code>x</code> of non-interface type <code>X</code> and
3939         a value <code>t</code> of interface type <code>T</code> are comparable when values
3940         of type <code>X</code> are comparable and
3941         <code>X</code> implements <code>T</code>.
3942         They are equal if <code>t</code>'s dynamic type is identical to <code>X</code>
3943         and <code>t</code>'s dynamic value is equal to <code>x</code>.
3944         </li>
3945
3946         <li>
3947         Struct values are comparable if all their fields are comparable.
3948         Two struct values are equal if their corresponding
3949         non-<a href="#Blank_identifier">blank</a> fields are equal.
3950         </li>
3951
3952         <li>
3953         Array values are comparable if values of the array element type are comparable.
3954         Two array values are equal if their corresponding elements are equal.
3955         </li>
3956 </ul>
3957
3958 <p>
3959 A comparison of two interface values with identical dynamic types
3960 causes a <a href="#Run_time_panics">run-time panic</a> if values
3961 of that type are not comparable.  This behavior applies not only to direct interface
3962 value comparisons but also when comparing arrays of interface values
3963 or structs with interface-valued fields.
3964 </p>
3965
3966 <p>
3967 Slice, map, and function values are not comparable.
3968 However, as a special case, a slice, map, or function value may
3969 be compared to the predeclared identifier <code>nil</code>.
3970 Comparison of pointer, channel, and interface values to <code>nil</code>
3971 is also allowed and follows from the general rules above.
3972 </p>
3973
3974 <pre>
3975 const c = 3 &lt; 4            // c is the untyped boolean constant true
3976
3977 type MyBool bool
3978 var x, y int
3979 var (
3980         // The result of a comparison is an untyped boolean.
3981         // The usual assignment rules apply.
3982         b3        = x == y // b3 has type bool
3983         b4 bool   = x == y // b4 has type bool
3984         b5 MyBool = x == y // b5 has type MyBool
3985 )
3986 </pre>
3987
3988 <h3 id="Logical_operators">Logical operators</h3>
3989
3990 <p>
3991 Logical operators apply to <a href="#Boolean_types">boolean</a> values
3992 and yield a result of the same type as the operands.
3993 The right operand is evaluated conditionally.
3994 </p>
3995
3996 <pre class="grammar">
3997 &amp;&amp;    conditional AND    p &amp;&amp; q  is  "if p then q else false"
3998 ||    conditional OR     p || q  is  "if p then true else q"
3999 !     NOT                !p      is  "not p"
4000 </pre>
4001
4002
4003 <h3 id="Address_operators">Address operators</h3>
4004
4005 <p>
4006 For an operand <code>x</code> of type <code>T</code>, the address operation
4007 <code>&amp;x</code> generates a pointer of type <code>*T</code> to <code>x</code>.
4008 The operand must be <i>addressable</i>,
4009 that is, either a variable, pointer indirection, or slice indexing
4010 operation; or a field selector of an addressable struct operand;
4011 or an array indexing operation of an addressable array.
4012 As an exception to the addressability requirement, <code>x</code> may also be a
4013 (possibly parenthesized)
4014 <a href="#Composite_literals">composite literal</a>.
4015 If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>,
4016 then the evaluation of <code>&amp;x</code> does too.
4017 </p>
4018
4019 <p>
4020 For an operand <code>x</code> of pointer type <code>*T</code>, the pointer
4021 indirection <code>*x</code> denotes the <a href="#Variables">variable</a> of type <code>T</code> pointed
4022 to by <code>x</code>.
4023 If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code>
4024 will cause a <a href="#Run_time_panics">run-time panic</a>.
4025 </p>
4026
4027 <pre>
4028 &amp;x
4029 &amp;a[f(2)]
4030 &amp;Point{2, 3}
4031 *p
4032 *pf(x)
4033
4034 var x *int = nil
4035 *x   // causes a run-time panic
4036 &amp;*x  // causes a run-time panic
4037 </pre>
4038
4039
4040 <h3 id="Receive_operator">Receive operator</h3>
4041
4042 <p>
4043 For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>,
4044 the value of the receive operation <code>&lt;-ch</code> is the value received
4045 from the channel <code>ch</code>. The channel direction must permit receive operations,
4046 and the type of the receive operation is the element type of the channel.
4047 The expression blocks until a value is available.
4048 Receiving from a <code>nil</code> channel blocks forever.
4049 A receive operation on a <a href="#Close">closed</a> channel can always proceed
4050 immediately, yielding the element type's <a href="#The_zero_value">zero value</a>
4051 after any previously sent values have been received.
4052 </p>
4053
4054 <pre>
4055 v1 := &lt;-ch
4056 v2 = &lt;-ch
4057 f(&lt;-ch)
4058 &lt;-strobe  // wait until clock pulse and discard received value
4059 </pre>
4060
4061 <p>
4062 A receive expression used in an <a href="#Assignments">assignment</a> or initialization of the special form
4063 </p>
4064
4065 <pre>
4066 x, ok = &lt;-ch
4067 x, ok := &lt;-ch
4068 var x, ok = &lt;-ch
4069 var x, ok T = &lt;-ch
4070 </pre>
4071
4072 <p>
4073 yields an additional untyped boolean result reporting whether the
4074 communication succeeded. The value of <code>ok</code> is <code>true</code>
4075 if the value received was delivered by a successful send operation to the
4076 channel, or <code>false</code> if it is a zero value generated because the
4077 channel is closed and empty.
4078 </p>
4079
4080
4081 <h3 id="Conversions">Conversions</h3>
4082
4083 <p>
4084 A conversion changes the <a href="#Types">type</a> of an expression
4085 to the type specified by the conversion.
4086 A conversion may appear literally in the source, or it may be <i>implied</i>
4087 by the context in which an expression appears.
4088 </p>
4089
4090 <p>
4091 An <i>explicit</i> conversion is an expression of the form <code>T(x)</code>
4092 where <code>T</code> is a type and <code>x</code> is an expression
4093 that can be converted to type <code>T</code>.
4094 </p>
4095
4096 <pre class="ebnf">
4097 Conversion = Type "(" Expression [ "," ] ")" .
4098 </pre>
4099
4100 <p>
4101 If the type starts with the operator <code>*</code> or <code>&lt;-</code>,
4102 or if the type starts with the keyword <code>func</code>
4103 and has no result list, it must be parenthesized when
4104 necessary to avoid ambiguity:
4105 </p>
4106
4107 <pre>
4108 *Point(p)        // same as *(Point(p))
4109 (*Point)(p)      // p is converted to *Point
4110 &lt;-chan int(c)    // same as &lt;-(chan int(c))
4111 (&lt;-chan int)(c)  // c is converted to &lt;-chan int
4112 func()(x)        // function signature func() x
4113 (func())(x)      // x is converted to func()
4114 (func() int)(x)  // x is converted to func() int
4115 func() int(x)    // x is converted to func() int (unambiguous)
4116 </pre>
4117
4118 <p>
4119 A <a href="#Constants">constant</a> value <code>x</code> can be converted to
4120 type <code>T</code> if <code>x</code> is <a href="#Representability">representable</a>
4121 by a value of <code>T</code>.
4122 As a special case, an integer constant <code>x</code> can be explicitly converted to a
4123 <a href="#String_types">string type</a> using the
4124 <a href="#Conversions_to_and_from_a_string_type">same rule</a>
4125 as for non-constant <code>x</code>.
4126 </p>
4127
4128 <p>
4129 Converting a constant yields a typed constant as result.
4130 </p>
4131
4132 <pre>
4133 uint(iota)               // iota value of type uint
4134 float32(2.718281828)     // 2.718281828 of type float32
4135 complex128(1)            // 1.0 + 0.0i of type complex128
4136 float32(0.49999999)      // 0.5 of type float32
4137 float64(-1e-1000)        // 0.0 of type float64
4138 string('x')              // "x" of type string
4139 string(0x266c)           // "♬" of type string
4140 MyString("foo" + "bar")  // "foobar" of type MyString
4141 string([]byte{'a'})      // not a constant: []byte{'a'} is not a constant
4142 (*int)(nil)              // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
4143 int(1.2)                 // illegal: 1.2 cannot be represented as an int
4144 string(65.0)             // illegal: 65.0 is not an integer constant
4145 </pre>
4146
4147 <p>
4148 A non-constant value <code>x</code> can be converted to type <code>T</code>
4149 in any of these cases:
4150 </p>
4151
4152 <ul>
4153         <li>
4154         <code>x</code> is <a href="#Assignability">assignable</a>
4155         to <code>T</code>.
4156         </li>
4157         <li>
4158         ignoring struct tags (see below),
4159         <code>x</code>'s type and <code>T</code> have <a href="#Type_identity">identical</a>
4160         <a href="#Types">underlying types</a>.
4161         </li>
4162         <li>
4163         ignoring struct tags (see below),
4164         <code>x</code>'s type and <code>T</code> are pointer types
4165         that are not <a href="#Type_definitions">defined types</a>,
4166         and their pointer base types have identical underlying types.
4167         </li>
4168         <li>
4169         <code>x</code>'s type and <code>T</code> are both integer or floating
4170         point types.
4171         </li>
4172         <li>
4173         <code>x</code>'s type and <code>T</code> are both complex types.
4174         </li>
4175         <li>
4176         <code>x</code> is an integer or a slice of bytes or runes
4177         and <code>T</code> is a string type.
4178         </li>
4179         <li>
4180         <code>x</code> is a string and <code>T</code> is a slice of bytes or runes.
4181         </li>
4182         <li>
4183         <code>x</code> is a slice, <code>T</code> is a pointer to an array,
4184         and the slice and array types have <a href="#Type_identity">identical</a> element types.
4185         </li>
4186 </ul>
4187
4188 <p>
4189 <a href="#Struct_types">Struct tags</a> are ignored when comparing struct types
4190 for identity for the purpose of conversion:
4191 </p>
4192
4193 <pre>
4194 type Person struct {
4195         Name    string
4196         Address *struct {
4197                 Street string
4198                 City   string
4199         }
4200 }
4201
4202 var data *struct {
4203         Name    string `json:"name"`
4204         Address *struct {
4205                 Street string `json:"street"`
4206                 City   string `json:"city"`
4207         } `json:"address"`
4208 }
4209
4210 var person = (*Person)(data)  // ignoring tags, the underlying types are identical
4211 </pre>
4212
4213 <p>
4214 Specific rules apply to (non-constant) conversions between numeric types or
4215 to and from a string type.
4216 These conversions may change the representation of <code>x</code>
4217 and incur a run-time cost.
4218 All other conversions only change the type but not the representation
4219 of <code>x</code>.
4220 </p>
4221
4222 <p>
4223 There is no linguistic mechanism to convert between pointers and integers.
4224 The package <a href="#Package_unsafe"><code>unsafe</code></a>
4225 implements this functionality under
4226 restricted circumstances.
4227 </p>
4228
4229 <h4>Conversions between numeric types</h4>
4230
4231 <p>
4232 For the conversion of non-constant numeric values, the following rules apply:
4233 </p>
4234
4235 <ol>
4236 <li>
4237 When converting between integer types, if the value is a signed integer, it is
4238 sign extended to implicit infinite precision; otherwise it is zero extended.
4239 It is then truncated to fit in the result type's size.
4240 For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>.
4241 The conversion always yields a valid value; there is no indication of overflow.
4242 </li>
4243 <li>
4244 When converting a floating-point number to an integer, the fraction is discarded
4245 (truncation towards zero).
4246 </li>
4247 <li>
4248 When converting an integer or floating-point number to a floating-point type,
4249 or a complex number to another complex type, the result value is rounded
4250 to the precision specified by the destination type.
4251 For instance, the value of a variable <code>x</code> of type <code>float32</code>
4252 may be stored using additional precision beyond that of an IEEE-754 32-bit number,
4253 but float32(x) represents the result of rounding <code>x</code>'s value to
4254 32-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits
4255 of precision, but <code>float32(x + 0.1)</code> does not.
4256 </li>
4257 </ol>
4258
4259 <p>
4260 In all non-constant conversions involving floating-point or complex values,
4261 if the result type cannot represent the value the conversion
4262 succeeds but the result value is implementation-dependent.
4263 </p>
4264
4265 <h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4>
4266
4267 <ol>
4268 <li>
4269 Converting a signed or unsigned integer value to a string type yields a
4270 string containing the UTF-8 representation of the integer. Values outside
4271 the range of valid Unicode code points are converted to <code>"\uFFFD"</code>.
4272
4273 <pre>
4274 string('a')       // "a"
4275 string(-1)        // "\ufffd" == "\xef\xbf\xbd"
4276 string(0xf8)      // "\u00f8" == "ø" == "\xc3\xb8"
4277 type MyString string
4278 MyString(0x65e5)  // "\u65e5" == "日" == "\xe6\x97\xa5"
4279 </pre>
4280 </li>
4281
4282 <li>
4283 Converting a slice of bytes to a string type yields
4284 a string whose successive bytes are the elements of the slice.
4285
4286 <pre>
4287 string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'})   // "hellø"
4288 string([]byte{})                                     // ""
4289 string([]byte(nil))                                  // ""
4290
4291 type MyBytes []byte
4292 string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'})  // "hellø"
4293 </pre>
4294 </li>
4295
4296 <li>
4297 Converting a slice of runes to a string type yields
4298 a string that is the concatenation of the individual rune values
4299 converted to strings.
4300
4301 <pre>
4302 string([]rune{0x767d, 0x9d6c, 0x7fd4})   // "\u767d\u9d6c\u7fd4" == "白鵬翔"
4303 string([]rune{})                         // ""
4304 string([]rune(nil))                      // ""
4305
4306 type MyRunes []rune
4307 string(MyRunes{0x767d, 0x9d6c, 0x7fd4})  // "\u767d\u9d6c\u7fd4" == "白鵬翔"
4308 </pre>
4309 </li>
4310
4311 <li>
4312 Converting a value of a string type to a slice of bytes type
4313 yields a slice whose successive elements are the bytes of the string.
4314
4315 <pre>
4316 []byte("hellø")   // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
4317 []byte("")        // []byte{}
4318
4319 MyBytes("hellø")  // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
4320 </pre>
4321 </li>
4322
4323 <li>
4324 Converting a value of a string type to a slice of runes type
4325 yields a slice containing the individual Unicode code points of the string.
4326
4327 <pre>
4328 []rune(MyString("白鵬翔"))  // []rune{0x767d, 0x9d6c, 0x7fd4}
4329 []rune("")                 // []rune{}
4330
4331 MyRunes("白鵬翔")           // []rune{0x767d, 0x9d6c, 0x7fd4}
4332 </pre>
4333 </li>
4334 </ol>
4335
4336 <h4 id="Conversions_from_slice_to_array_pointer">Conversions from slice to array pointer</h4>
4337
4338 <p>
4339 Converting a slice to an array pointer yields a pointer to the underlying array of the slice.
4340 If the <a href="#Length_and_capacity">length</a> of the slice is less than the length of the array,
4341 a <a href="#Run_time_panics">run-time panic</a> occurs.
4342 </p>
4343
4344 <pre>
4345 s := make([]byte, 2, 4)
4346 s0 := (*[0]byte)(s)      // s0 != nil
4347 s1 := (*[1]byte)(s[1:])  // &amp;s1[0] == &amp;s[1]
4348 s2 := (*[2]byte)(s)      // &amp;s2[0] == &amp;s[0]
4349 s4 := (*[4]byte)(s)      // panics: len([4]byte) > len(s)
4350
4351 var t []string
4352 t0 := (*[0]string)(t)    // t0 == nil
4353 t1 := (*[1]string)(t)    // panics: len([1]string) > len(t)
4354
4355 u := make([]byte, 0)
4356 u0 := (*[0]byte)(u)      // u0 != nil
4357 </pre>
4358
4359 <h3 id="Constant_expressions">Constant expressions</h3>
4360
4361 <p>
4362 Constant expressions may contain only <a href="#Constants">constant</a>
4363 operands and are evaluated at compile time.
4364 </p>
4365
4366 <p>
4367 Untyped boolean, numeric, and string constants may be used as operands
4368 wherever it is legal to use an operand of boolean, numeric, or string type,
4369 respectively.
4370 </p>
4371
4372 <p>
4373 A constant <a href="#Comparison_operators">comparison</a> always yields
4374 an untyped boolean constant.  If the left operand of a constant
4375 <a href="#Operators">shift expression</a> is an untyped constant, the
4376 result is an integer constant; otherwise it is a constant of the same
4377 type as the left operand, which must be of
4378 <a href="#Numeric_types">integer type</a>.
4379 </p>
4380
4381 <p>
4382 Any other operation on untyped constants results in an untyped constant of the
4383 same kind; that is, a boolean, integer, floating-point, complex, or string
4384 constant.
4385 If the untyped operands of a binary operation (other than a shift) are of
4386 different kinds, the result is of the operand's kind that appears later in this
4387 list: integer, rune, floating-point, complex.
4388 For example, an untyped integer constant divided by an
4389 untyped complex constant yields an untyped complex constant.
4390 </p>
4391
4392 <pre>
4393 const a = 2 + 3.0          // a == 5.0   (untyped floating-point constant)
4394 const b = 15 / 4           // b == 3     (untyped integer constant)
4395 const c = 15 / 4.0         // c == 3.75  (untyped floating-point constant)
4396 const Θ float64 = 3/2      // Θ == 1.0   (type float64, 3/2 is integer division)
4397 const Π float64 = 3/2.     // Π == 1.5   (type float64, 3/2. is float division)
4398 const d = 1 &lt;&lt; 3.0         // d == 8     (untyped integer constant)
4399 const e = 1.0 &lt;&lt; 3         // e == 8     (untyped integer constant)
4400 const f = int32(1) &lt;&lt; 33   // illegal    (constant 8589934592 overflows int32)
4401 const g = float64(2) &gt;&gt; 1  // illegal    (float64(2) is a typed floating-point constant)
4402 const h = "foo" &gt; "bar"    // h == true  (untyped boolean constant)
4403 const j = true             // j == true  (untyped boolean constant)
4404 const k = 'w' + 1          // k == 'x'   (untyped rune constant)
4405 const l = "hi"             // l == "hi"  (untyped string constant)
4406 const m = string(k)        // m == "x"   (type string)
4407 const Σ = 1 - 0.707i       //            (untyped complex constant)
4408 const Δ = Σ + 2.0e-4       //            (untyped complex constant)
4409 const Φ = iota*1i - 1/1i   //            (untyped complex constant)
4410 </pre>
4411
4412 <p>
4413 Applying the built-in function <code>complex</code> to untyped
4414 integer, rune, or floating-point constants yields
4415 an untyped complex constant.
4416 </p>
4417
4418 <pre>
4419 const ic = complex(0, c)   // ic == 3.75i  (untyped complex constant)
4420 const iΘ = complex(0, Θ)   // iΘ == 1i     (type complex128)
4421 </pre>
4422
4423 <p>
4424 Constant expressions are always evaluated exactly; intermediate values and the
4425 constants themselves may require precision significantly larger than supported
4426 by any predeclared type in the language. The following are legal declarations:
4427 </p>
4428
4429 <pre>
4430 const Huge = 1 &lt;&lt; 100         // Huge == 1267650600228229401496703205376  (untyped integer constant)
4431 const Four int8 = Huge &gt;&gt; 98  // Four == 4                                (type int8)
4432 </pre>
4433
4434 <p>
4435 The divisor of a constant division or remainder operation must not be zero:
4436 </p>
4437
4438 <pre>
4439 3.14 / 0.0   // illegal: division by zero
4440 </pre>
4441
4442 <p>
4443 The values of <i>typed</i> constants must always be accurately
4444 <a href="#Representability">representable</a> by values
4445 of the constant type. The following constant expressions are illegal:
4446 </p>
4447
4448 <pre>
4449 uint(-1)     // -1 cannot be represented as a uint
4450 int(3.14)    // 3.14 cannot be represented as an int
4451 int64(Huge)  // 1267650600228229401496703205376 cannot be represented as an int64
4452 Four * 300   // operand 300 cannot be represented as an int8 (type of Four)
4453 Four * 100   // product 400 cannot be represented as an int8 (type of Four)
4454 </pre>
4455
4456 <p>
4457 The mask used by the unary bitwise complement operator <code>^</code> matches
4458 the rule for non-constants: the mask is all 1s for unsigned constants
4459 and -1 for signed and untyped constants.
4460 </p>
4461
4462 <pre>
4463 ^1         // untyped integer constant, equal to -2
4464 uint8(^1)  // illegal: same as uint8(-2), -2 cannot be represented as a uint8
4465 ^uint8(1)  // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)
4466 int8(^1)   // same as int8(-2)
4467 ^int8(1)   // same as -1 ^ int8(1) = -2
4468 </pre>
4469
4470 <p>
4471 Implementation restriction: A compiler may use rounding while
4472 computing untyped floating-point or complex constant expressions; see
4473 the implementation restriction in the section
4474 on <a href="#Constants">constants</a>.  This rounding may cause a
4475 floating-point constant expression to be invalid in an integer
4476 context, even if it would be integral when calculated using infinite
4477 precision, and vice versa.
4478 </p>
4479
4480
4481 <h3 id="Order_of_evaluation">Order of evaluation</h3>
4482
4483 <p>
4484 At package level, <a href="#Package_initialization">initialization dependencies</a>
4485 determine the evaluation order of individual initialization expressions in
4486 <a href="#Variable_declarations">variable declarations</a>.
4487 Otherwise, when evaluating the <a href="#Operands">operands</a> of an
4488 expression, assignment, or
4489 <a href="#Return_statements">return statement</a>,
4490 all function calls, method calls, and
4491 communication operations are evaluated in lexical left-to-right
4492 order.
4493 </p>
4494
4495 <p>
4496 For example, in the (function-local) assignment
4497 </p>
4498 <pre>
4499 y[f()], ok = g(h(), i()+x[j()], &lt;-c), k()
4500 </pre>
4501 <p>
4502 the function calls and communication happen in the order
4503 <code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>,
4504 <code>&lt;-c</code>, <code>g()</code>, and <code>k()</code>.
4505 However, the order of those events compared to the evaluation
4506 and indexing of <code>x</code> and the evaluation
4507 of <code>y</code> is not specified.
4508 </p>
4509
4510 <pre>
4511 a := 1
4512 f := func() int { a++; return a }
4513 x := []int{a, f()}            // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified
4514 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
4515 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
4516 </pre>
4517
4518 <p>
4519 At package level, initialization dependencies override the left-to-right rule
4520 for individual initialization expressions, but not for operands within each
4521 expression:
4522 </p>
4523
4524 <pre>
4525 var a, b, c = f() + v(), g(), sqr(u()) + v()
4526
4527 func f() int        { return c }
4528 func g() int        { return a }
4529 func sqr(x int) int { return x*x }
4530
4531 // functions u and v are independent of all other variables and functions
4532 </pre>
4533
4534 <p>
4535 The function calls happen in the order
4536 <code>u()</code>, <code>sqr()</code>, <code>v()</code>,
4537 <code>f()</code>, <code>v()</code>, and <code>g()</code>.
4538 </p>
4539
4540 <p>
4541 Floating-point operations within a single expression are evaluated according to
4542 the associativity of the operators.  Explicit parentheses affect the evaluation
4543 by overriding the default associativity.
4544 In the expression <code>x + (y + z)</code> the addition <code>y + z</code>
4545 is performed before adding <code>x</code>.
4546 </p>
4547
4548 <h2 id="Statements">Statements</h2>
4549
4550 <p>
4551 Statements control execution.
4552 </p>
4553
4554 <pre class="ebnf">
4555 Statement =
4556         Declaration | LabeledStmt | SimpleStmt |
4557         GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
4558         FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
4559         DeferStmt .
4560
4561 SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
4562 </pre>
4563
4564 <h3 id="Terminating_statements">Terminating statements</h3>
4565
4566 <p>
4567 A <i>terminating statement</i> interrupts the regular flow of control in
4568 a <a href="#Blocks">block</a>. The following statements are terminating:
4569 </p>
4570
4571 <ol>
4572 <li>
4573         A <a href="#Return_statements">"return"</a> or
4574         <a href="#Goto_statements">"goto"</a> statement.
4575         <!-- ul below only for regular layout -->
4576         <ul> </ul>
4577 </li>
4578
4579 <li>
4580         A call to the built-in function
4581         <a href="#Handling_panics"><code>panic</code></a>.
4582         <!-- ul below only for regular layout -->
4583         <ul> </ul>
4584 </li>
4585
4586 <li>
4587         A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement.
4588         <!-- ul below only for regular layout -->
4589         <ul> </ul>
4590 </li>
4591
4592 <li>
4593         An <a href="#If_statements">"if" statement</a> in which:
4594         <ul>
4595         <li>the "else" branch is present, and</li>
4596         <li>both branches are terminating statements.</li>
4597         </ul>
4598 </li>
4599
4600 <li>
4601         A <a href="#For_statements">"for" statement</a> in which:
4602         <ul>
4603         <li>there are no "break" statements referring to the "for" statement, and</li>
4604         <li>the loop condition is absent, and</li>
4605         <li>the "for" statement does not use a range clause.</li>
4606         </ul>
4607 </li>
4608
4609 <li>
4610         A <a href="#Switch_statements">"switch" statement</a> in which:
4611         <ul>
4612         <li>there are no "break" statements referring to the "switch" statement,</li>
4613         <li>there is a default case, and</li>
4614         <li>the statement lists in each case, including the default, end in a terminating
4615             statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough"
4616             statement</a>.</li>
4617         </ul>
4618 </li>
4619
4620 <li>
4621         A <a href="#Select_statements">"select" statement</a> in which:
4622         <ul>
4623         <li>there are no "break" statements referring to the "select" statement, and</li>
4624         <li>the statement lists in each case, including the default if present,
4625             end in a terminating statement.</li>
4626         </ul>
4627 </li>
4628
4629 <li>
4630         A <a href="#Labeled_statements">labeled statement</a> labeling
4631         a terminating statement.
4632 </li>
4633 </ol>
4634
4635 <p>
4636 All other statements are not terminating.
4637 </p>
4638
4639 <p>
4640 A <a href="#Blocks">statement list</a> ends in a terminating statement if the list
4641 is not empty and its final non-empty statement is terminating.
4642 </p>
4643
4644
4645 <h3 id="Empty_statements">Empty statements</h3>
4646
4647 <p>
4648 The empty statement does nothing.
4649 </p>
4650
4651 <pre class="ebnf">
4652 EmptyStmt = .
4653 </pre>
4654
4655
4656 <h3 id="Labeled_statements">Labeled statements</h3>
4657
4658 <p>
4659 A labeled statement may be the target of a <code>goto</code>,
4660 <code>break</code> or <code>continue</code> statement.
4661 </p>
4662
4663 <pre class="ebnf">
4664 LabeledStmt = Label ":" Statement .
4665 Label       = identifier .
4666 </pre>
4667
4668 <pre>
4669 Error: log.Panic("error encountered")
4670 </pre>
4671
4672
4673 <h3 id="Expression_statements">Expression statements</h3>
4674
4675 <p>
4676 With the exception of specific built-in functions,
4677 function and method <a href="#Calls">calls</a> and
4678 <a href="#Receive_operator">receive operations</a>
4679 can appear in statement context. Such statements may be parenthesized.
4680 </p>
4681
4682 <pre class="ebnf">
4683 ExpressionStmt = Expression .
4684 </pre>
4685
4686 <p>
4687 The following built-in functions are not permitted in statement context:
4688 </p>
4689
4690 <pre>
4691 append cap complex imag len make new real
4692 unsafe.Add unsafe.Alignof unsafe.Offsetof unsafe.Sizeof unsafe.Slice
4693 </pre>
4694
4695 <pre>
4696 h(x+y)
4697 f.Close()
4698 &lt;-ch
4699 (&lt;-ch)
4700 len("foo")  // illegal if len is the built-in function
4701 </pre>
4702
4703
4704 <h3 id="Send_statements">Send statements</h3>
4705
4706 <p>
4707 A send statement sends a value on a channel.
4708 The channel expression must be of <a href="#Channel_types">channel type</a>,
4709 the channel direction must permit send operations,
4710 and the type of the value to be sent must be <a href="#Assignability">assignable</a>
4711 to the channel's element type.
4712 </p>
4713
4714 <pre class="ebnf">
4715 SendStmt = Channel "&lt;-" Expression .
4716 Channel  = Expression .
4717 </pre>
4718
4719 <p>
4720 Both the channel and the value expression are evaluated before communication
4721 begins. Communication blocks until the send can proceed.
4722 A send on an unbuffered channel can proceed if a receiver is ready.
4723 A send on a buffered channel can proceed if there is room in the buffer.
4724 A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>.
4725 A send on a <code>nil</code> channel blocks forever.
4726 </p>
4727
4728 <pre>
4729 ch &lt;- 3  // send value 3 to channel ch
4730 </pre>
4731
4732
4733 <h3 id="IncDec_statements">IncDec statements</h3>
4734
4735 <p>
4736 The "++" and "--" statements increment or decrement their operands
4737 by the untyped <a href="#Constants">constant</a> <code>1</code>.
4738 As with an assignment, the operand must be <a href="#Address_operators">addressable</a>
4739 or a map index expression.
4740 </p>
4741
4742 <pre class="ebnf">
4743 IncDecStmt = Expression ( "++" | "--" ) .
4744 </pre>
4745
4746 <p>
4747 The following <a href="#Assignments">assignment statements</a> are semantically
4748 equivalent:
4749 </p>
4750
4751 <pre class="grammar">
4752 IncDec statement    Assignment
4753 x++                 x += 1
4754 x--                 x -= 1
4755 </pre>
4756
4757
4758 <h3 id="Assignments">Assignments</h3>
4759
4760 <pre class="ebnf">
4761 Assignment = ExpressionList assign_op ExpressionList .
4762
4763 assign_op = [ add_op | mul_op ] "=" .
4764 </pre>
4765
4766 <p>
4767 Each left-hand side operand must be <a href="#Address_operators">addressable</a>,
4768 a map index expression, or (for <code>=</code> assignments only) the
4769 <a href="#Blank_identifier">blank identifier</a>.
4770 Operands may be parenthesized.
4771 </p>
4772
4773 <pre>
4774 x = 1
4775 *p = f()
4776 a[i] = 23
4777 (k) = &lt;-ch  // same as: k = &lt;-ch
4778 </pre>
4779
4780 <p>
4781 An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code>
4782 <code>y</code> where <i>op</i> is a binary <a href="#Arithmetic_operators">arithmetic operator</a>
4783 is equivalent to <code>x</code> <code>=</code> <code>x</code> <i>op</i>
4784 <code>(y)</code> but evaluates <code>x</code>
4785 only once.  The <i>op</i><code>=</code> construct is a single token.
4786 In assignment operations, both the left- and right-hand expression lists
4787 must contain exactly one single-valued expression, and the left-hand
4788 expression must not be the blank identifier.
4789 </p>
4790
4791 <pre>
4792 a[i] &lt;&lt;= 2
4793 i &amp;^= 1&lt;&lt;n
4794 </pre>
4795
4796 <p>
4797 A tuple assignment assigns the individual elements of a multi-valued
4798 operation to a list of variables.  There are two forms.  In the
4799 first, the right hand operand is a single multi-valued expression
4800 such as a function call, a <a href="#Channel_types">channel</a> or
4801 <a href="#Map_types">map</a> operation, or a <a href="#Type_assertions">type assertion</a>.
4802 The number of operands on the left
4803 hand side must match the number of values.  For instance, if
4804 <code>f</code> is a function returning two values,
4805 </p>
4806
4807 <pre>
4808 x, y = f()
4809 </pre>
4810
4811 <p>
4812 assigns the first value to <code>x</code> and the second to <code>y</code>.
4813 In the second form, the number of operands on the left must equal the number
4814 of expressions on the right, each of which must be single-valued, and the
4815 <i>n</i>th expression on the right is assigned to the <i>n</i>th
4816 operand on the left:
4817 </p>
4818
4819 <pre>
4820 one, two, three = '一', '二', '三'
4821 </pre>
4822
4823 <p>
4824 The <a href="#Blank_identifier">blank identifier</a> provides a way to
4825 ignore right-hand side values in an assignment:
4826 </p>
4827
4828 <pre>
4829 _ = x       // evaluate x but ignore it
4830 x, _ = f()  // evaluate f() but ignore second result value
4831 </pre>
4832
4833 <p>
4834 The assignment proceeds in two phases.
4835 First, the operands of <a href="#Index_expressions">index expressions</a>
4836 and <a href="#Address_operators">pointer indirections</a>
4837 (including implicit pointer indirections in <a href="#Selectors">selectors</a>)
4838 on the left and the expressions on the right are all
4839 <a href="#Order_of_evaluation">evaluated in the usual order</a>.
4840 Second, the assignments are carried out in left-to-right order.
4841 </p>
4842
4843 <pre>
4844 a, b = b, a  // exchange a and b
4845
4846 x := []int{1, 2, 3}
4847 i := 0
4848 i, x[i] = 1, 2  // set i = 1, x[0] = 2
4849
4850 i = 0
4851 x[i], i = 2, 1  // set x[0] = 2, i = 1
4852
4853 x[0], x[0] = 1, 2  // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end)
4854
4855 x[1], x[3] = 4, 5  // set x[1] = 4, then panic setting x[3] = 5.
4856
4857 type Point struct { x, y int }
4858 var p *Point
4859 x[2], p.x = 6, 7  // set x[2] = 6, then panic setting p.x = 7
4860
4861 i = 2
4862 x = []int{3, 5, 7}
4863 for i, x[i] = range x {  // set i, x[2] = 0, x[0]
4864         break
4865 }
4866 // after this loop, i == 0 and x == []int{3, 5, 3}
4867 </pre>
4868
4869 <p>
4870 In assignments, each value must be <a href="#Assignability">assignable</a>
4871 to the type of the operand to which it is assigned, with the following special cases:
4872 </p>
4873
4874 <ol>
4875 <li>
4876         Any typed value may be assigned to the blank identifier.
4877 </li>
4878
4879 <li>
4880         If an untyped constant
4881         is assigned to a variable of interface type or the blank identifier,
4882         the constant is first implicitly <a href="#Conversions">converted</a> to its
4883          <a href="#Constants">default type</a>.
4884 </li>
4885
4886 <li>
4887         If an untyped boolean value is assigned to a variable of interface type or
4888         the blank identifier, it is first implicitly converted to type <code>bool</code>.
4889 </li>
4890 </ol>
4891
4892 <h3 id="If_statements">If statements</h3>
4893
4894 <p>
4895 "If" statements specify the conditional execution of two branches
4896 according to the value of a boolean expression.  If the expression
4897 evaluates to true, the "if" branch is executed, otherwise, if
4898 present, the "else" branch is executed.
4899 </p>
4900
4901 <pre class="ebnf">
4902 IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
4903 </pre>
4904
4905 <pre>
4906 if x &gt; max {
4907         x = max
4908 }
4909 </pre>
4910
4911 <p>
4912 The expression may be preceded by a simple statement, which
4913 executes before the expression is evaluated.
4914 </p>
4915
4916 <pre>
4917 if x := f(); x &lt; y {
4918         return x
4919 } else if x &gt; z {
4920         return z
4921 } else {
4922         return y
4923 }
4924 </pre>
4925
4926
4927 <h3 id="Switch_statements">Switch statements</h3>
4928
4929 <p>
4930 "Switch" statements provide multi-way execution.
4931 An expression or type is compared to the "cases"
4932 inside the "switch" to determine which branch
4933 to execute.
4934 </p>
4935
4936 <pre class="ebnf">
4937 SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4938 </pre>
4939
4940 <p>
4941 There are two forms: expression switches and type switches.
4942 In an expression switch, the cases contain expressions that are compared
4943 against the value of the switch expression.
4944 In a type switch, the cases contain types that are compared against the
4945 type of a specially annotated switch expression.
4946 The switch expression is evaluated exactly once in a switch statement.
4947 </p>
4948
4949 <h4 id="Expression_switches">Expression switches</h4>
4950
4951 <p>
4952 In an expression switch,
4953 the switch expression is evaluated and
4954 the case expressions, which need not be constants,
4955 are evaluated left-to-right and top-to-bottom; the first one that equals the
4956 switch expression
4957 triggers execution of the statements of the associated case;
4958 the other cases are skipped.
4959 If no case matches and there is a "default" case,
4960 its statements are executed.
4961 There can be at most one default case and it may appear anywhere in the
4962 "switch" statement.
4963 A missing switch expression is equivalent to the boolean value
4964 <code>true</code>.
4965 </p>
4966
4967 <pre class="ebnf">
4968 ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
4969 ExprCaseClause = ExprSwitchCase ":" StatementList .
4970 ExprSwitchCase = "case" ExpressionList | "default" .
4971 </pre>
4972
4973 <p>
4974 If the switch expression evaluates to an untyped constant, it is first implicitly
4975 <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>.
4976 The predeclared untyped value <code>nil</code> cannot be used as a switch expression.
4977 The switch expression type must be <a href="#Comparison_operators">comparable</a>.
4978 </p>
4979
4980 <p>
4981 If a case expression is untyped, it is first implicitly <a href="#Conversions">converted</a>
4982 to the type of the switch expression.
4983 For each (possibly converted) case expression <code>x</code> and the value <code>t</code>
4984 of the switch expression, <code>x == t</code> must be a valid <a href="#Comparison_operators">comparison</a>.
4985 </p>
4986
4987 <p>
4988 In other words, the switch expression is treated as if it were used to declare and
4989 initialize a temporary variable <code>t</code> without explicit type; it is that
4990 value of <code>t</code> against which each case expression <code>x</code> is tested
4991 for equality.
4992 </p>
4993
4994 <p>
4995 In a case or default clause, the last non-empty statement
4996 may be a (possibly <a href="#Labeled_statements">labeled</a>)
4997 <a href="#Fallthrough_statements">"fallthrough" statement</a> to
4998 indicate that control should flow from the end of this clause to
4999 the first statement of the next clause.
5000 Otherwise control flows to the end of the "switch" statement.
5001 A "fallthrough" statement may appear as the last statement of all
5002 but the last clause of an expression switch.
5003 </p>
5004
5005 <p>
5006 The switch expression may be preceded by a simple statement, which
5007 executes before the expression is evaluated.
5008 </p>
5009
5010 <pre>
5011 switch tag {
5012 default: s3()
5013 case 0, 1, 2, 3: s1()
5014 case 4, 5, 6, 7: s2()
5015 }
5016
5017 switch x := f(); {  // missing switch expression means "true"
5018 case x &lt; 0: return -x
5019 default: return x
5020 }
5021
5022 switch {
5023 case x &lt; y: f1()
5024 case x &lt; z: f2()
5025 case x == 4: f3()
5026 }
5027 </pre>
5028
5029 <p>
5030 Implementation restriction: A compiler may disallow multiple case
5031 expressions evaluating to the same constant.
5032 For instance, the current compilers disallow duplicate integer,
5033 floating point, or string constants in case expressions.
5034 </p>
5035
5036 <h4 id="Type_switches">Type switches</h4>
5037
5038 <p>
5039 A type switch compares types rather than values. It is otherwise similar
5040 to an expression switch. It is marked by a special switch expression that
5041 has the form of a <a href="#Type_assertions">type assertion</a>
5042 using the keyword <code>type</code> rather than an actual type:
5043 </p>
5044
5045 <pre>
5046 switch x.(type) {
5047 // cases
5048 }
5049 </pre>
5050
5051 <p>
5052 Cases then match actual types <code>T</code> against the dynamic type of the
5053 expression <code>x</code>. As with type assertions, <code>x</code> must be of
5054 <a href="#Interface_types">interface type</a>, and each non-interface type
5055 <code>T</code> listed in a case must implement the type of <code>x</code>.
5056 The types listed in the cases of a type switch must all be
5057 <a href="#Type_identity">different</a>.
5058 </p>
5059
5060 <pre class="ebnf">
5061 TypeSwitchStmt  = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
5062 TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
5063 TypeCaseClause  = TypeSwitchCase ":" StatementList .
5064 TypeSwitchCase  = "case" TypeList | "default" .
5065 TypeList        = Type { "," Type } .
5066 </pre>
5067
5068 <p>
5069 The TypeSwitchGuard may include a
5070 <a href="#Short_variable_declarations">short variable declaration</a>.
5071 When that form is used, the variable is declared at the end of the
5072 TypeSwitchCase in the <a href="#Blocks">implicit block</a> of each clause.
5073 In clauses with a case listing exactly one type, the variable
5074 has that type; otherwise, the variable has the type of the expression
5075 in the TypeSwitchGuard.
5076 </p>
5077
5078 <p>
5079 Instead of a type, a case may use the predeclared identifier
5080 <a href="#Predeclared_identifiers"><code>nil</code></a>;
5081 that case is selected when the expression in the TypeSwitchGuard
5082 is a <code>nil</code> interface value.
5083 There may be at most one <code>nil</code> case.
5084 </p>
5085
5086 <p>
5087 Given an expression <code>x</code> of type <code>interface{}</code>,
5088 the following type switch:
5089 </p>
5090
5091 <pre>
5092 switch i := x.(type) {
5093 case nil:
5094         printString("x is nil")                // type of i is type of x (interface{})
5095 case int:
5096         printInt(i)                            // type of i is int
5097 case float64:
5098         printFloat64(i)                        // type of i is float64
5099 case func(int) float64:
5100         printFunction(i)                       // type of i is func(int) float64
5101 case bool, string:
5102         printString("type is bool or string")  // type of i is type of x (interface{})
5103 default:
5104         printString("don't know the type")     // type of i is type of x (interface{})
5105 }
5106 </pre>
5107
5108 <p>
5109 could be rewritten:
5110 </p>
5111
5112 <pre>
5113 v := x  // x is evaluated exactly once
5114 if v == nil {
5115         i := v                                 // type of i is type of x (interface{})
5116         printString("x is nil")
5117 } else if i, isInt := v.(int); isInt {
5118         printInt(i)                            // type of i is int
5119 } else if i, isFloat64 := v.(float64); isFloat64 {
5120         printFloat64(i)                        // type of i is float64
5121 } else if i, isFunc := v.(func(int) float64); isFunc {
5122         printFunction(i)                       // type of i is func(int) float64
5123 } else {
5124         _, isBool := v.(bool)
5125         _, isString := v.(string)
5126         if isBool || isString {
5127                 i := v                         // type of i is type of x (interface{})
5128                 printString("type is bool or string")
5129         } else {
5130                 i := v                         // type of i is type of x (interface{})
5131                 printString("don't know the type")
5132         }
5133 }
5134 </pre>
5135
5136 <p>
5137 The type switch guard may be preceded by a simple statement, which
5138 executes before the guard is evaluated.
5139 </p>
5140
5141 <p>
5142 The "fallthrough" statement is not permitted in a type switch.
5143 </p>
5144
5145 <h3 id="For_statements">For statements</h3>
5146
5147 <p>
5148 A "for" statement specifies repeated execution of a block. There are three forms:
5149 The iteration may be controlled by a single condition, a "for" clause, or a "range" clause.
5150 </p>
5151
5152 <pre class="ebnf">
5153 ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
5154 Condition = Expression .
5155 </pre>
5156
5157 <h4 id="For_condition">For statements with single condition</h4>
5158
5159 <p>
5160 In its simplest form, a "for" statement specifies the repeated execution of
5161 a block as long as a boolean condition evaluates to true.
5162 The condition is evaluated before each iteration.
5163 If the condition is absent, it is equivalent to the boolean value
5164 <code>true</code>.
5165 </p>
5166
5167 <pre>
5168 for a &lt; b {
5169         a *= 2
5170 }
5171 </pre>
5172
5173 <h4 id="For_clause">For statements with <code>for</code> clause</h4>
5174
5175 <p>
5176 A "for" statement with a ForClause is also controlled by its condition, but
5177 additionally it may specify an <i>init</i>
5178 and a <i>post</i> statement, such as an assignment,
5179 an increment or decrement statement. The init statement may be a
5180 <a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not.
5181 Variables declared by the init statement are re-used in each iteration.
5182 </p>
5183
5184 <pre class="ebnf">
5185 ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
5186 InitStmt = SimpleStmt .
5187 PostStmt = SimpleStmt .
5188 </pre>
5189
5190 <pre>
5191 for i := 0; i &lt; 10; i++ {
5192         f(i)
5193 }
5194 </pre>
5195
5196 <p>
5197 If non-empty, the init statement is executed once before evaluating the
5198 condition for the first iteration;
5199 the post statement is executed after each execution of the block (and
5200 only if the block was executed).
5201 Any element of the ForClause may be empty but the
5202 <a href="#Semicolons">semicolons</a> are
5203 required unless there is only a condition.
5204 If the condition is absent, it is equivalent to the boolean value
5205 <code>true</code>.
5206 </p>
5207
5208 <pre>
5209 for cond { S() }    is the same as    for ; cond ; { S() }
5210 for      { S() }    is the same as    for true     { S() }
5211 </pre>
5212
5213 <h4 id="For_range">For statements with <code>range</code> clause</h4>
5214
5215 <p>
5216 A "for" statement with a "range" clause
5217 iterates through all entries of an array, slice, string or map,
5218 or values received on a channel. For each entry it assigns <i>iteration values</i>
5219 to corresponding <i>iteration variables</i> if present and then executes the block.
5220 </p>
5221
5222 <pre class="ebnf">
5223 RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .
5224 </pre>
5225
5226 <p>
5227 The expression on the right in the "range" clause is called the <i>range expression</i>,
5228 which may be an array, pointer to an array, slice, string, map, or channel permitting
5229 <a href="#Receive_operator">receive operations</a>.
5230 As with an assignment, if present the operands on the left must be
5231 <a href="#Address_operators">addressable</a> or map index expressions; they
5232 denote the iteration variables. If the range expression is a channel, at most
5233 one iteration variable is permitted, otherwise there may be up to two.
5234 If the last iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
5235 the range clause is equivalent to the same clause without that identifier.
5236 </p>
5237
5238 <p>
5239 The range expression <code>x</code> is evaluated once before beginning the loop,
5240 with one exception: if at most one iteration variable is present and
5241 <code>len(x)</code> is <a href="#Length_and_capacity">constant</a>,
5242 the range expression is not evaluated.
5243 </p>
5244
5245 <p>
5246 Function calls on the left are evaluated once per iteration.
5247 For each iteration, iteration values are produced as follows
5248 if the respective iteration variables are present:
5249 </p>
5250
5251 <pre class="grammar">
5252 Range expression                          1st value          2nd value
5253
5254 array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
5255 string          s  string type            index    i  int    see below  rune
5256 map             m  map[K]V                key      k  K      m[k]       V
5257 channel         c  chan E, &lt;-chan E       element  e  E
5258 </pre>
5259
5260 <ol>
5261 <li>
5262 For an array, pointer to array, or slice value <code>a</code>, the index iteration
5263 values are produced in increasing order, starting at element index 0.
5264 If at most one iteration variable is present, the range loop produces
5265 iteration values from 0 up to <code>len(a)-1</code> and does not index into the array
5266 or slice itself. For a <code>nil</code> slice, the number of iterations is 0.
5267 </li>
5268
5269 <li>
5270 For a string value, the "range" clause iterates over the Unicode code points
5271 in the string starting at byte index 0.  On successive iterations, the index value will be the
5272 index of the first byte of successive UTF-8-encoded code points in the string,
5273 and the second value, of type <code>rune</code>, will be the value of
5274 the corresponding code point.  If the iteration encounters an invalid
5275 UTF-8 sequence, the second value will be <code>0xFFFD</code>,
5276 the Unicode replacement character, and the next iteration will advance
5277 a single byte in the string.
5278 </li>
5279
5280 <li>
5281 The iteration order over maps is not specified
5282 and is not guaranteed to be the same from one iteration to the next.
5283 If a map entry that has not yet been reached is removed during iteration,
5284 the corresponding iteration value will not be produced. If a map entry is
5285 created during iteration, that entry may be produced during the iteration or
5286 may be skipped. The choice may vary for each entry created and from one
5287 iteration to the next.
5288 If the map is <code>nil</code>, the number of iterations is 0.
5289 </li>
5290
5291 <li>
5292 For channels, the iteration values produced are the successive values sent on
5293 the channel until the channel is <a href="#Close">closed</a>. If the channel
5294 is <code>nil</code>, the range expression blocks forever.
5295 </li>
5296 </ol>
5297
5298 <p>
5299 The iteration values are assigned to the respective
5300 iteration variables as in an <a href="#Assignments">assignment statement</a>.
5301 </p>
5302
5303 <p>
5304 The iteration variables may be declared by the "range" clause using a form of
5305 <a href="#Short_variable_declarations">short variable declaration</a>
5306 (<code>:=</code>).
5307 In this case their types are set to the types of the respective iteration values
5308 and their <a href="#Declarations_and_scope">scope</a> is the block of the "for"
5309 statement; they are re-used in each iteration.
5310 If the iteration variables are declared outside the "for" statement,
5311 after execution their values will be those of the last iteration.
5312 </p>
5313
5314 <pre>
5315 var testdata *struct {
5316         a *[7]int
5317 }
5318 for i, _ := range testdata.a {
5319         // testdata.a is never evaluated; len(testdata.a) is constant
5320         // i ranges from 0 to 6
5321         f(i)
5322 }
5323
5324 var a [10]string
5325 for i, s := range a {
5326         // type of i is int
5327         // type of s is string
5328         // s == a[i]
5329         g(i, s)
5330 }
5331
5332 var key string
5333 var val interface{}  // element type of m is assignable to val
5334 m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}
5335 for key, val = range m {
5336         h(key, val)
5337 }
5338 // key == last map key encountered in iteration
5339 // val == map[key]
5340
5341 var ch chan Work = producer()
5342 for w := range ch {
5343         doWork(w)
5344 }
5345
5346 // empty a channel
5347 for range ch {}
5348 </pre>
5349
5350
5351 <h3 id="Go_statements">Go statements</h3>
5352
5353 <p>
5354 A "go" statement starts the execution of a function call
5355 as an independent concurrent thread of control, or <i>goroutine</i>,
5356 within the same address space.
5357 </p>
5358
5359 <pre class="ebnf">
5360 GoStmt = "go" Expression .
5361 </pre>
5362
5363 <p>
5364 The expression must be a function or method call; it cannot be parenthesized.
5365 Calls of built-in functions are restricted as for
5366 <a href="#Expression_statements">expression statements</a>.
5367 </p>
5368
5369 <p>
5370 The function value and parameters are
5371 <a href="#Calls">evaluated as usual</a>
5372 in the calling goroutine, but
5373 unlike with a regular call, program execution does not wait
5374 for the invoked function to complete.
5375 Instead, the function begins executing independently
5376 in a new goroutine.
5377 When the function terminates, its goroutine also terminates.
5378 If the function has any return values, they are discarded when the
5379 function completes.
5380 </p>
5381
5382 <pre>
5383 go Server()
5384 go func(ch chan&lt;- bool) { for { sleep(10); ch &lt;- true }} (c)
5385 </pre>
5386
5387
5388 <h3 id="Select_statements">Select statements</h3>
5389
5390 <p>
5391 A "select" statement chooses which of a set of possible
5392 <a href="#Send_statements">send</a> or
5393 <a href="#Receive_operator">receive</a>
5394 operations will proceed.
5395 It looks similar to a
5396 <a href="#Switch_statements">"switch"</a> statement but with the
5397 cases all referring to communication operations.
5398 </p>
5399
5400 <pre class="ebnf">
5401 SelectStmt = "select" "{" { CommClause } "}" .
5402 CommClause = CommCase ":" StatementList .
5403 CommCase   = "case" ( SendStmt | RecvStmt ) | "default" .
5404 RecvStmt   = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
5405 RecvExpr   = Expression .
5406 </pre>
5407
5408 <p>
5409 A case with a RecvStmt may assign the result of a RecvExpr to one or
5410 two variables, which may be declared using a
5411 <a href="#Short_variable_declarations">short variable declaration</a>.
5412 The RecvExpr must be a (possibly parenthesized) receive operation.
5413 There can be at most one default case and it may appear anywhere
5414 in the list of cases.
5415 </p>
5416
5417 <p>
5418 Execution of a "select" statement proceeds in several steps:
5419 </p>
5420
5421 <ol>
5422 <li>
5423 For all the cases in the statement, the channel operands of receive operations
5424 and the channel and right-hand-side expressions of send statements are
5425 evaluated exactly once, in source order, upon entering the "select" statement.
5426 The result is a set of channels to receive from or send to,
5427 and the corresponding values to send.
5428 Any side effects in that evaluation will occur irrespective of which (if any)
5429 communication operation is selected to proceed.
5430 Expressions on the left-hand side of a RecvStmt with a short variable declaration
5431 or assignment are not yet evaluated.
5432 </li>
5433
5434 <li>
5435 If one or more of the communications can proceed,
5436 a single one that can proceed is chosen via a uniform pseudo-random selection.
5437 Otherwise, if there is a default case, that case is chosen.
5438 If there is no default case, the "select" statement blocks until
5439 at least one of the communications can proceed.
5440 </li>
5441
5442 <li>
5443 Unless the selected case is the default case, the respective communication
5444 operation is executed.
5445 </li>
5446
5447 <li>
5448 If the selected case is a RecvStmt with a short variable declaration or
5449 an assignment, the left-hand side expressions are evaluated and the
5450 received value (or values) are assigned.
5451 </li>
5452
5453 <li>
5454 The statement list of the selected case is executed.
5455 </li>
5456 </ol>
5457
5458 <p>
5459 Since communication on <code>nil</code> channels can never proceed,
5460 a select with only <code>nil</code> channels and no default case blocks forever.
5461 </p>
5462
5463 <pre>
5464 var a []int
5465 var c, c1, c2, c3, c4 chan int
5466 var i1, i2 int
5467 select {
5468 case i1 = &lt;-c1:
5469         print("received ", i1, " from c1\n")
5470 case c2 &lt;- i2:
5471         print("sent ", i2, " to c2\n")
5472 case i3, ok := (&lt;-c3):  // same as: i3, ok := &lt;-c3
5473         if ok {
5474                 print("received ", i3, " from c3\n")
5475         } else {
5476                 print("c3 is closed\n")
5477         }
5478 case a[f()] = &lt;-c4:
5479         // same as:
5480         // case t := &lt;-c4
5481         //      a[f()] = t
5482 default:
5483         print("no communication\n")
5484 }
5485
5486 for {  // send random sequence of bits to c
5487         select {
5488         case c &lt;- 0:  // note: no statement, no fallthrough, no folding of cases
5489         case c &lt;- 1:
5490         }
5491 }
5492
5493 select {}  // block forever
5494 </pre>
5495
5496
5497 <h3 id="Return_statements">Return statements</h3>
5498
5499 <p>
5500 A "return" statement in a function <code>F</code> terminates the execution
5501 of <code>F</code>, and optionally provides one or more result values.
5502 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
5503 are executed before <code>F</code> returns to its caller.
5504 </p>
5505
5506 <pre class="ebnf">
5507 ReturnStmt = "return" [ ExpressionList ] .
5508 </pre>
5509
5510 <p>
5511 In a function without a result type, a "return" statement must not
5512 specify any result values.
5513 </p>
5514 <pre>
5515 func noResult() {
5516         return
5517 }
5518 </pre>
5519
5520 <p>
5521 There are three ways to return values from a function with a result
5522 type:
5523 </p>
5524
5525 <ol>
5526         <li>The return value or values may be explicitly listed
5527                 in the "return" statement. Each expression must be single-valued
5528                 and <a href="#Assignability">assignable</a>
5529                 to the corresponding element of the function's result type.
5530 <pre>
5531 func simpleF() int {
5532         return 2
5533 }
5534
5535 func complexF1() (re float64, im float64) {
5536         return -7.0, -4.0
5537 }
5538 </pre>
5539         </li>
5540         <li>The expression list in the "return" statement may be a single
5541                 call to a multi-valued function. The effect is as if each value
5542                 returned from that function were assigned to a temporary
5543                 variable with the type of the respective value, followed by a
5544                 "return" statement listing these variables, at which point the
5545                 rules of the previous case apply.
5546 <pre>
5547 func complexF2() (re float64, im float64) {
5548         return complexF1()
5549 }
5550 </pre>
5551         </li>
5552         <li>The expression list may be empty if the function's result
5553                 type specifies names for its <a href="#Function_types">result parameters</a>.
5554                 The result parameters act as ordinary local variables
5555                 and the function may assign values to them as necessary.
5556                 The "return" statement returns the values of these variables.
5557 <pre>
5558 func complexF3() (re float64, im float64) {
5559         re = 7.0
5560         im = 4.0
5561         return
5562 }
5563
5564 func (devnull) Write(p []byte) (n int, _ error) {
5565         n = len(p)
5566         return
5567 }
5568 </pre>
5569         </li>
5570 </ol>
5571
5572 <p>
5573 Regardless of how they are declared, all the result values are initialized to
5574 the <a href="#The_zero_value">zero values</a> for their type upon entry to the
5575 function. A "return" statement that specifies results sets the result parameters before
5576 any deferred functions are executed.
5577 </p>
5578
5579 <p>
5580 Implementation restriction: A compiler may disallow an empty expression list
5581 in a "return" statement if a different entity (constant, type, or variable)
5582 with the same name as a result parameter is in
5583 <a href="#Declarations_and_scope">scope</a> at the place of the return.
5584 </p>
5585
5586 <pre>
5587 func f(n int) (res int, err error) {
5588         if _, err := f(n-1); err != nil {
5589                 return  // invalid return statement: err is shadowed
5590         }
5591         return
5592 }
5593 </pre>
5594
5595 <h3 id="Break_statements">Break statements</h3>
5596
5597 <p>
5598 A "break" statement terminates execution of the innermost
5599 <a href="#For_statements">"for"</a>,
5600 <a href="#Switch_statements">"switch"</a>, or
5601 <a href="#Select_statements">"select"</a> statement
5602 within the same function.
5603 </p>
5604
5605 <pre class="ebnf">
5606 BreakStmt = "break" [ Label ] .
5607 </pre>
5608
5609 <p>
5610 If there is a label, it must be that of an enclosing
5611 "for", "switch", or "select" statement,
5612 and that is the one whose execution terminates.
5613 </p>
5614
5615 <pre>
5616 OuterLoop:
5617         for i = 0; i &lt; n; i++ {
5618                 for j = 0; j &lt; m; j++ {
5619                         switch a[i][j] {
5620                         case nil:
5621                                 state = Error
5622                                 break OuterLoop
5623                         case item:
5624                                 state = Found
5625                                 break OuterLoop
5626                         }
5627                 }
5628         }
5629 </pre>
5630
5631 <h3 id="Continue_statements">Continue statements</h3>
5632
5633 <p>
5634 A "continue" statement begins the next iteration of the
5635 innermost <a href="#For_statements">"for" loop</a> at its post statement.
5636 The "for" loop must be within the same function.
5637 </p>
5638
5639 <pre class="ebnf">
5640 ContinueStmt = "continue" [ Label ] .
5641 </pre>
5642
5643 <p>
5644 If there is a label, it must be that of an enclosing
5645 "for" statement, and that is the one whose execution
5646 advances.
5647 </p>
5648
5649 <pre>
5650 RowLoop:
5651         for y, row := range rows {
5652                 for x, data := range row {
5653                         if data == endOfRow {
5654                                 continue RowLoop
5655                         }
5656                         row[x] = data + bias(x, y)
5657                 }
5658         }
5659 </pre>
5660
5661 <h3 id="Goto_statements">Goto statements</h3>
5662
5663 <p>
5664 A "goto" statement transfers control to the statement with the corresponding label
5665 within the same function.
5666 </p>
5667
5668 <pre class="ebnf">
5669 GotoStmt = "goto" Label .
5670 </pre>
5671
5672 <pre>
5673 goto Error
5674 </pre>
5675
5676 <p>
5677 Executing the "goto" statement must not cause any variables to come into
5678 <a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto.
5679 For instance, this example:
5680 </p>
5681
5682 <pre>
5683         goto L  // BAD
5684         v := 3
5685 L:
5686 </pre>
5687
5688 <p>
5689 is erroneous because the jump to label <code>L</code> skips
5690 the creation of <code>v</code>.
5691 </p>
5692
5693 <p>
5694 A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block.
5695 For instance, this example:
5696 </p>
5697
5698 <pre>
5699 if n%2 == 1 {
5700         goto L1
5701 }
5702 for n &gt; 0 {
5703         f()
5704         n--
5705 L1:
5706         f()
5707         n--
5708 }
5709 </pre>
5710
5711 <p>
5712 is erroneous because the label <code>L1</code> is inside
5713 the "for" statement's block but the <code>goto</code> is not.
5714 </p>
5715
5716 <h3 id="Fallthrough_statements">Fallthrough statements</h3>
5717
5718 <p>
5719 A "fallthrough" statement transfers control to the first statement of the
5720 next case clause in an <a href="#Expression_switches">expression "switch" statement</a>.
5721 It may be used only as the final non-empty statement in such a clause.
5722 </p>
5723
5724 <pre class="ebnf">
5725 FallthroughStmt = "fallthrough" .
5726 </pre>
5727
5728
5729 <h3 id="Defer_statements">Defer statements</h3>
5730
5731 <p>
5732 A "defer" statement invokes a function whose execution is deferred
5733 to the moment the surrounding function returns, either because the
5734 surrounding function executed a <a href="#Return_statements">return statement</a>,
5735 reached the end of its <a href="#Function_declarations">function body</a>,
5736 or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>.
5737 </p>
5738
5739 <pre class="ebnf">
5740 DeferStmt = "defer" Expression .
5741 </pre>
5742
5743 <p>
5744 The expression must be a function or method call; it cannot be parenthesized.
5745 Calls of built-in functions are restricted as for
5746 <a href="#Expression_statements">expression statements</a>.
5747 </p>
5748
5749 <p>
5750 Each time a "defer" statement
5751 executes, the function value and parameters to the call are
5752 <a href="#Calls">evaluated as usual</a>
5753 and saved anew but the actual function is not invoked.
5754 Instead, deferred functions are invoked immediately before
5755 the surrounding function returns, in the reverse order
5756 they were deferred. That is, if the surrounding function
5757 returns through an explicit <a href="#Return_statements">return statement</a>,
5758 deferred functions are executed <i>after</i> any result parameters are set
5759 by that return statement but <i>before</i> the function returns to its caller.
5760 If a deferred function value evaluates
5761 to <code>nil</code>, execution <a href="#Handling_panics">panics</a>
5762 when the function is invoked, not when the "defer" statement is executed.
5763 </p>
5764
5765 <p>
5766 For instance, if the deferred function is
5767 a <a href="#Function_literals">function literal</a> and the surrounding
5768 function has <a href="#Function_types">named result parameters</a> that
5769 are in scope within the literal, the deferred function may access and modify
5770 the result parameters before they are returned.
5771 If the deferred function has any return values, they are discarded when
5772 the function completes.
5773 (See also the section on <a href="#Handling_panics">handling panics</a>.)
5774 </p>
5775
5776 <pre>
5777 lock(l)
5778 defer unlock(l)  // unlocking happens before surrounding function returns
5779
5780 // prints 3 2 1 0 before surrounding function returns
5781 for i := 0; i &lt;= 3; i++ {
5782         defer fmt.Print(i)
5783 }
5784
5785 // f returns 42
5786 func f() (result int) {
5787         defer func() {
5788                 // result is accessed after it was set to 6 by the return statement
5789                 result *= 7
5790         }()
5791         return 6
5792 }
5793 </pre>
5794
5795 <h2 id="Built-in_functions">Built-in functions</h2>
5796
5797 <p>
5798 Built-in functions are
5799 <a href="#Predeclared_identifiers">predeclared</a>.
5800 They are called like any other function but some of them
5801 accept a type instead of an expression as the first argument.
5802 </p>
5803
5804 <p>
5805 The built-in functions do not have standard Go types,
5806 so they can only appear in <a href="#Calls">call expressions</a>;
5807 they cannot be used as function values.
5808 </p>
5809
5810 <h3 id="Close">Close</h3>
5811
5812 <p>
5813 For a channel <code>c</code>, the built-in function <code>close(c)</code>
5814 records that no more values will be sent on the channel.
5815 It is an error if <code>c</code> is a receive-only channel.
5816 Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>.
5817 Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>.
5818 After calling <code>close</code>, and after any previously
5819 sent values have been received, receive operations will return
5820 the zero value for the channel's type without blocking.
5821 The multi-valued <a href="#Receive_operator">receive operation</a>
5822 returns a received value along with an indication of whether the channel is closed.
5823 </p>
5824
5825
5826 <h3 id="Length_and_capacity">Length and capacity</h3>
5827
5828 <p>
5829 The built-in functions <code>len</code> and <code>cap</code> take arguments
5830 of various types and return a result of type <code>int</code>.
5831 The implementation guarantees that the result always fits into an <code>int</code>.
5832 </p>
5833
5834 <pre class="grammar">
5835 Call      Argument type    Result
5836
5837 len(s)    string type      string length in bytes
5838           [n]T, *[n]T      array length (== n)
5839           []T              slice length
5840           map[K]T          map length (number of defined keys)
5841           chan T           number of elements queued in channel buffer
5842
5843 cap(s)    [n]T, *[n]T      array length (== n)
5844           []T              slice capacity
5845           chan T           channel buffer capacity
5846 </pre>
5847
5848 <p>
5849 The capacity of a slice is the number of elements for which there is
5850 space allocated in the underlying array.
5851 At any time the following relationship holds:
5852 </p>
5853
5854 <pre>
5855 0 &lt;= len(s) &lt;= cap(s)
5856 </pre>
5857
5858 <p>
5859 The length of a <code>nil</code> slice, map or channel is 0.
5860 The capacity of a <code>nil</code> slice or channel is 0.
5861 </p>
5862
5863 <p>
5864 The expression <code>len(s)</code> is <a href="#Constants">constant</a> if
5865 <code>s</code> is a string constant. The expressions <code>len(s)</code> and
5866 <code>cap(s)</code> are constants if the type of <code>s</code> is an array
5867 or pointer to an array and the expression <code>s</code> does not contain
5868 <a href="#Receive_operator">channel receives</a> or (non-constant)
5869 <a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated.
5870 Otherwise, invocations of <code>len</code> and <code>cap</code> are not
5871 constant and <code>s</code> is evaluated.
5872 </p>
5873
5874 <pre>
5875 const (
5876         c1 = imag(2i)                    // imag(2i) = 2.0 is a constant
5877         c2 = len([10]float64{2})         // [10]float64{2} contains no function calls
5878         c3 = len([10]float64{c1})        // [10]float64{c1} contains no function calls
5879         c4 = len([10]float64{imag(2i)})  // imag(2i) is a constant and no function call is issued
5880         c5 = len([10]float64{imag(z)})   // invalid: imag(z) is a (non-constant) function call
5881 )
5882 var z complex128
5883 </pre>
5884
5885 <h3 id="Allocation">Allocation</h3>
5886
5887 <p>
5888 The built-in function <code>new</code> takes a type <code>T</code>,
5889 allocates storage for a <a href="#Variables">variable</a> of that type
5890 at run time, and returns a value of type <code>*T</code>
5891 <a href="#Pointer_types">pointing</a> to it.
5892 The variable is initialized as described in the section on
5893 <a href="#The_zero_value">initial values</a>.
5894 </p>
5895
5896 <pre class="grammar">
5897 new(T)
5898 </pre>
5899
5900 <p>
5901 For instance
5902 </p>
5903
5904 <pre>
5905 type S struct { a int; b float64 }
5906 new(S)
5907 </pre>
5908
5909 <p>
5910 allocates storage for a variable of type <code>S</code>,
5911 initializes it (<code>a=0</code>, <code>b=0.0</code>),
5912 and returns a value of type <code>*S</code> containing the address
5913 of the location.
5914 </p>
5915
5916 <h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3>
5917
5918 <p>
5919 The built-in function <code>make</code> takes a type <code>T</code>,
5920 which must be a slice, map or channel type,
5921 optionally followed by a type-specific list of expressions.
5922 It returns a value of type <code>T</code> (not <code>*T</code>).
5923 The memory is initialized as described in the section on
5924 <a href="#The_zero_value">initial values</a>.
5925 </p>
5926
5927 <pre class="grammar">
5928 Call             Type T     Result
5929
5930 make(T, n)       slice      slice of type T with length n and capacity n
5931 make(T, n, m)    slice      slice of type T with length n and capacity m
5932
5933 make(T)          map        map of type T
5934 make(T, n)       map        map of type T with initial space for approximately n elements
5935
5936 make(T)          channel    unbuffered channel of type T
5937 make(T, n)       channel    buffered channel of type T, buffer size n
5938 </pre>
5939
5940
5941 <p>
5942 Each of the size arguments <code>n</code> and <code>m</code> must be of integer type
5943 or an untyped <a href="#Constants">constant</a>.
5944 A constant size argument must be non-negative and <a href="#Representability">representable</a>
5945 by a value of type <code>int</code>; if it is an untyped constant it is given type <code>int</code>.
5946 If both <code>n</code> and <code>m</code> are provided and are constant, then
5947 <code>n</code> must be no larger than <code>m</code>.
5948 If <code>n</code> is negative or larger than <code>m</code> at run time,
5949 a <a href="#Run_time_panics">run-time panic</a> occurs.
5950 </p>
5951
5952 <pre>
5953 s := make([]int, 10, 100)       // slice with len(s) == 10, cap(s) == 100
5954 s := make([]int, 1e3)           // slice with len(s) == cap(s) == 1000
5955 s := make([]int, 1&lt;&lt;63)         // illegal: len(s) is not representable by a value of type int
5956 s := make([]int, 10, 0)         // illegal: len(s) > cap(s)
5957 c := make(chan int, 10)         // channel with a buffer size of 10
5958 m := make(map[string]int, 100)  // map with initial space for approximately 100 elements
5959 </pre>
5960
5961 <p>
5962 Calling <code>make</code> with a map type and size hint <code>n</code> will
5963 create a map with initial space to hold <code>n</code> map elements.
5964 The precise behavior is implementation-dependent.
5965 </p>
5966
5967
5968 <h3 id="Appending_and_copying_slices">Appending to and copying slices</h3>
5969
5970 <p>
5971 The built-in functions <code>append</code> and <code>copy</code> assist in
5972 common slice operations.
5973 For both functions, the result is independent of whether the memory referenced
5974 by the arguments overlaps.
5975 </p>
5976
5977 <p>
5978 The <a href="#Function_types">variadic</a> function <code>append</code>
5979 appends zero or more values <code>x</code>
5980 to <code>s</code> of type <code>S</code>, which must be a slice type, and
5981 returns the resulting slice, also of type <code>S</code>.
5982 The values <code>x</code> are passed to a parameter of type <code>...T</code>
5983 where <code>T</code> is the <a href="#Slice_types">element type</a> of
5984 <code>S</code> and the respective
5985 <a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply.
5986 As a special case, <code>append</code> also accepts a first argument
5987 assignable to type <code>[]byte</code> with a second argument of
5988 string type followed by <code>...</code>. This form appends the
5989 bytes of the string.
5990 </p>
5991
5992 <pre class="grammar">
5993 append(s S, x ...T) S  // T is the element type of S
5994 </pre>
5995
5996 <p>
5997 If the capacity of <code>s</code> is not large enough to fit the additional
5998 values, <code>append</code> allocates a new, sufficiently large underlying
5999 array that fits both the existing slice elements and the additional values.
6000 Otherwise, <code>append</code> re-uses the underlying array.
6001 </p>
6002
6003 <pre>
6004 s0 := []int{0, 0}
6005 s1 := append(s0, 2)                // append a single element     s1 == []int{0, 0, 2}
6006 s2 := append(s1, 3, 5, 7)          // append multiple elements    s2 == []int{0, 0, 2, 3, 5, 7}
6007 s3 := append(s2, s0...)            // append a slice              s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
6008 s4 := append(s3[3:6], s3[2:]...)   // append overlapping slice    s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
6009
6010 var t []interface{}
6011 t = append(t, 42, 3.1415, "foo")   //                             t == []interface{}{42, 3.1415, "foo"}
6012
6013 var b []byte
6014 b = append(b, "bar"...)            // append string contents      b == []byte{'b', 'a', 'r' }
6015 </pre>
6016
6017 <p>
6018 The function <code>copy</code> copies slice elements from
6019 a source <code>src</code> to a destination <code>dst</code> and returns the
6020 number of elements copied.
6021 Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be
6022 <a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>.
6023 The number of elements copied is the minimum of
6024 <code>len(src)</code> and <code>len(dst)</code>.
6025 As a special case, <code>copy</code> also accepts a destination argument assignable
6026 to type <code>[]byte</code> with a source argument of a string type.
6027 This form copies the bytes from the string into the byte slice.
6028 </p>
6029
6030 <pre class="grammar">
6031 copy(dst, src []T) int
6032 copy(dst []byte, src string) int
6033 </pre>
6034
6035 <p>
6036 Examples:
6037 </p>
6038
6039 <pre>
6040 var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7}
6041 var s = make([]int, 6)
6042 var b = make([]byte, 5)
6043 n1 := copy(s, a[0:])            // n1 == 6, s == []int{0, 1, 2, 3, 4, 5}
6044 n2 := copy(s, s[2:])            // n2 == 4, s == []int{2, 3, 4, 5, 4, 5}
6045 n3 := copy(b, "Hello, World!")  // n3 == 5, b == []byte("Hello")
6046 </pre>
6047
6048
6049 <h3 id="Deletion_of_map_elements">Deletion of map elements</h3>
6050
6051 <p>
6052 The built-in function <code>delete</code> removes the element with key
6053 <code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The
6054 type of <code>k</code> must be <a href="#Assignability">assignable</a>
6055 to the key type of <code>m</code>.
6056 </p>
6057
6058 <pre class="grammar">
6059 delete(m, k)  // remove element m[k] from map m
6060 </pre>
6061
6062 <p>
6063 If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code>
6064 does not exist, <code>delete</code> is a no-op.
6065 </p>
6066
6067
6068 <h3 id="Complex_numbers">Manipulating complex numbers</h3>
6069
6070 <p>
6071 Three functions assemble and disassemble complex numbers.
6072 The built-in function <code>complex</code> constructs a complex
6073 value from a floating-point real and imaginary part, while
6074 <code>real</code> and <code>imag</code>
6075 extract the real and imaginary parts of a complex value.
6076 </p>
6077
6078 <pre class="grammar">
6079 complex(realPart, imaginaryPart floatT) complexT
6080 real(complexT) floatT
6081 imag(complexT) floatT
6082 </pre>
6083
6084 <p>
6085 The type of the arguments and return value correspond.
6086 For <code>complex</code>, the two arguments must be of the same
6087 floating-point type and the return type is the complex type
6088 with the corresponding floating-point constituents:
6089 <code>complex64</code> for <code>float32</code> arguments, and
6090 <code>complex128</code> for <code>float64</code> arguments.
6091 If one of the arguments evaluates to an untyped constant, it is first implicitly
6092 <a href="#Conversions">converted</a> to the type of the other argument.
6093 If both arguments evaluate to untyped constants, they must be non-complex
6094 numbers or their imaginary parts must be zero, and the return value of
6095 the function is an untyped complex constant.
6096 </p>
6097
6098 <p>
6099 For <code>real</code> and <code>imag</code>, the argument must be
6100 of complex type, and the return type is the corresponding floating-point
6101 type: <code>float32</code> for a <code>complex64</code> argument, and
6102 <code>float64</code> for a <code>complex128</code> argument.
6103 If the argument evaluates to an untyped constant, it must be a number,
6104 and the return value of the function is an untyped floating-point constant.
6105 </p>
6106
6107 <p>
6108 The <code>real</code> and <code>imag</code> functions together form the inverse of
6109 <code>complex</code>, so for a value <code>z</code> of a complex type <code>Z</code>,
6110 <code>z&nbsp;==&nbsp;Z(complex(real(z),&nbsp;imag(z)))</code>.
6111 </p>
6112
6113 <p>
6114 If the operands of these functions are all constants, the return
6115 value is a constant.
6116 </p>
6117
6118 <pre>
6119 var a = complex(2, -2)             // complex128
6120 const b = complex(1.0, -1.4)       // untyped complex constant 1 - 1.4i
6121 x := float32(math.Cos(math.Pi/2))  // float32
6122 var c64 = complex(5, -x)           // complex64
6123 var s int = complex(1, 0)          // untyped complex constant 1 + 0i can be converted to int
6124 _ = complex(1, 2&lt;&lt;s)               // illegal: 2 assumes floating-point type, cannot shift
6125 var rl = real(c64)                 // float32
6126 var im = imag(a)                   // float64
6127 const c = imag(b)                  // untyped constant -1.4
6128 _ = imag(3 &lt;&lt; s)                   // illegal: 3 assumes complex type, cannot shift
6129 </pre>
6130
6131 <h3 id="Handling_panics">Handling panics</h3>
6132
6133 <p> Two built-in functions, <code>panic</code> and <code>recover</code>,
6134 assist in reporting and handling <a href="#Run_time_panics">run-time panics</a>
6135 and program-defined error conditions.
6136 </p>
6137
6138 <pre class="grammar">
6139 func panic(interface{})
6140 func recover() interface{}
6141 </pre>
6142
6143 <p>
6144 While executing a function <code>F</code>,
6145 an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a>
6146 terminates the execution of <code>F</code>.
6147 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
6148 are then executed as usual.
6149 Next, any deferred functions run by <code>F's</code> caller are run,
6150 and so on up to any deferred by the top-level function in the executing goroutine.
6151 At that point, the program is terminated and the error
6152 condition is reported, including the value of the argument to <code>panic</code>.
6153 This termination sequence is called <i>panicking</i>.
6154 </p>
6155
6156 <pre>
6157 panic(42)
6158 panic("unreachable")
6159 panic(Error("cannot parse"))
6160 </pre>
6161
6162 <p>
6163 The <code>recover</code> function allows a program to manage behavior
6164 of a panicking goroutine.
6165 Suppose a function <code>G</code> defers a function <code>D</code> that calls
6166 <code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code>
6167 is executing.
6168 When the running of deferred functions reaches <code>D</code>,
6169 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>.
6170 If <code>D</code> returns normally, without starting a new
6171 <code>panic</code>, the panicking sequence stops. In that case,
6172 the state of functions called between <code>G</code> and the call to <code>panic</code>
6173 is discarded, and normal execution resumes.
6174 Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s
6175 execution terminates by returning to its caller.
6176 </p>
6177
6178 <p>
6179 The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds:
6180 </p>
6181 <ul>
6182 <li>
6183 <code>panic</code>'s argument was <code>nil</code>;
6184 </li>
6185 <li>
6186 the goroutine is not panicking;
6187 </li>
6188 <li>
6189 <code>recover</code> was not called directly by a deferred function.
6190 </li>
6191 </ul>
6192
6193 <p>
6194 The <code>protect</code> function in the example below invokes
6195 the function argument <code>g</code> and protects callers from
6196 run-time panics raised by <code>g</code>.
6197 </p>
6198
6199 <pre>
6200 func protect(g func()) {
6201         defer func() {
6202                 log.Println("done")  // Println executes normally even if there is a panic
6203                 if x := recover(); x != nil {
6204                         log.Printf("run time panic: %v", x)
6205                 }
6206         }()
6207         log.Println("start")
6208         g()
6209 }
6210 </pre>
6211
6212
6213 <h3 id="Bootstrapping">Bootstrapping</h3>
6214
6215 <p>
6216 Current implementations provide several built-in functions useful during
6217 bootstrapping. These functions are documented for completeness but are not
6218 guaranteed to stay in the language. They do not return a result.
6219 </p>
6220
6221 <pre class="grammar">
6222 Function   Behavior
6223
6224 print      prints all arguments; formatting of arguments is implementation-specific
6225 println    like print but prints spaces between arguments and a newline at the end
6226 </pre>
6227
6228 <p>
6229 Implementation restriction: <code>print</code> and <code>println</code> need not
6230 accept arbitrary argument types, but printing of boolean, numeric, and string
6231 <a href="#Types">types</a> must be supported.
6232 </p>
6233
6234 <h2 id="Packages">Packages</h2>
6235
6236 <p>
6237 Go programs are constructed by linking together <i>packages</i>.
6238 A package in turn is constructed from one or more source files
6239 that together declare constants, types, variables and functions
6240 belonging to the package and which are accessible in all files
6241 of the same package. Those elements may be
6242 <a href="#Exported_identifiers">exported</a> and used in another package.
6243 </p>
6244
6245 <h3 id="Source_file_organization">Source file organization</h3>
6246
6247 <p>
6248 Each source file consists of a package clause defining the package
6249 to which it belongs, followed by a possibly empty set of import
6250 declarations that declare packages whose contents it wishes to use,
6251 followed by a possibly empty set of declarations of functions,
6252 types, variables, and constants.
6253 </p>
6254
6255 <pre class="ebnf">
6256 SourceFile       = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
6257 </pre>
6258
6259 <h3 id="Package_clause">Package clause</h3>
6260
6261 <p>
6262 A package clause begins each source file and defines the package
6263 to which the file belongs.
6264 </p>
6265
6266 <pre class="ebnf">
6267 PackageClause  = "package" PackageName .
6268 PackageName    = identifier .
6269 </pre>
6270
6271 <p>
6272 The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>.
6273 </p>
6274
6275 <pre>
6276 package math
6277 </pre>
6278
6279 <p>
6280 A set of files sharing the same PackageName form the implementation of a package.
6281 An implementation may require that all source files for a package inhabit the same directory.
6282 </p>
6283
6284 <h3 id="Import_declarations">Import declarations</h3>
6285
6286 <p>
6287 An import declaration states that the source file containing the declaration
6288 depends on functionality of the <i>imported</i> package
6289 (<a href="#Program_initialization_and_execution">§Program initialization and execution</a>)
6290 and enables access to <a href="#Exported_identifiers">exported</a> identifiers
6291 of that package.
6292 The import names an identifier (PackageName) to be used for access and an ImportPath
6293 that specifies the package to be imported.
6294 </p>
6295
6296 <pre class="ebnf">
6297 ImportDecl       = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
6298 ImportSpec       = [ "." | PackageName ] ImportPath .
6299 ImportPath       = string_lit .
6300 </pre>
6301
6302 <p>
6303 The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a>
6304 to access exported identifiers of the package within the importing source file.
6305 It is declared in the <a href="#Blocks">file block</a>.
6306 If the PackageName is omitted, it defaults to the identifier specified in the
6307 <a href="#Package_clause">package clause</a> of the imported package.
6308 If an explicit period (<code>.</code>) appears instead of a name, all the
6309 package's exported identifiers declared in that package's
6310 <a href="#Blocks">package block</a> will be declared in the importing source
6311 file's file block and must be accessed without a qualifier.
6312 </p>
6313
6314 <p>
6315 The interpretation of the ImportPath is implementation-dependent but
6316 it is typically a substring of the full file name of the compiled
6317 package and may be relative to a repository of installed packages.
6318 </p>
6319
6320 <p>
6321 Implementation restriction: A compiler may restrict ImportPaths to
6322 non-empty strings using only characters belonging to
6323 <a href="https://www.unicode.org/versions/Unicode6.3.0/">Unicode's</a>
6324 L, M, N, P, and S general categories (the Graphic characters without
6325 spaces) and may also exclude the characters
6326 <code>!"#$%&amp;'()*,:;&lt;=&gt;?[\]^`{|}</code>
6327 and the Unicode replacement character U+FFFD.
6328 </p>
6329
6330 <p>
6331 Assume we have compiled a package containing the package clause
6332 <code>package math</code>, which exports function <code>Sin</code>, and
6333 installed the compiled package in the file identified by
6334 <code>"lib/math"</code>.
6335 This table illustrates how <code>Sin</code> is accessed in files
6336 that import the package after the
6337 various types of import declaration.
6338 </p>
6339
6340 <pre class="grammar">
6341 Import declaration          Local name of Sin
6342
6343 import   "lib/math"         math.Sin
6344 import m "lib/math"         m.Sin
6345 import . "lib/math"         Sin
6346 </pre>
6347
6348 <p>
6349 An import declaration declares a dependency relation between
6350 the importing and imported package.
6351 It is illegal for a package to import itself, directly or indirectly,
6352 or to directly import a package without
6353 referring to any of its exported identifiers. To import a package solely for
6354 its side-effects (initialization), use the <a href="#Blank_identifier">blank</a>
6355 identifier as explicit package name:
6356 </p>
6357
6358 <pre>
6359 import _ "lib/math"
6360 </pre>
6361
6362
6363 <h3 id="An_example_package">An example package</h3>
6364
6365 <p>
6366 Here is a complete Go package that implements a concurrent prime sieve.
6367 </p>
6368
6369 <pre>
6370 package main
6371
6372 import "fmt"
6373
6374 // Send the sequence 2, 3, 4, … to channel 'ch'.
6375 func generate(ch chan&lt;- int) {
6376         for i := 2; ; i++ {
6377                 ch &lt;- i  // Send 'i' to channel 'ch'.
6378         }
6379 }
6380
6381 // Copy the values from channel 'src' to channel 'dst',
6382 // removing those divisible by 'prime'.
6383 func filter(src &lt;-chan int, dst chan&lt;- int, prime int) {
6384         for i := range src {  // Loop over values received from 'src'.
6385                 if i%prime != 0 {
6386                         dst &lt;- i  // Send 'i' to channel 'dst'.
6387                 }
6388         }
6389 }
6390
6391 // The prime sieve: Daisy-chain filter processes together.
6392 func sieve() {
6393         ch := make(chan int)  // Create a new channel.
6394         go generate(ch)       // Start generate() as a subprocess.
6395         for {
6396                 prime := &lt;-ch
6397                 fmt.Print(prime, "\n")
6398                 ch1 := make(chan int)
6399                 go filter(ch, ch1, prime)
6400                 ch = ch1
6401         }
6402 }
6403
6404 func main() {
6405         sieve()
6406 }
6407 </pre>
6408
6409 <h2 id="Program_initialization_and_execution">Program initialization and execution</h2>
6410
6411 <h3 id="The_zero_value">The zero value</h3>
6412 <p>
6413 When storage is allocated for a <a href="#Variables">variable</a>,
6414 either through a declaration or a call of <code>new</code>, or when
6415 a new value is created, either through a composite literal or a call
6416 of <code>make</code>,
6417 and no explicit initialization is provided, the variable or value is
6418 given a default value.  Each element of such a variable or value is
6419 set to the <i>zero value</i> for its type: <code>false</code> for booleans,
6420 <code>0</code> for numeric types, <code>""</code>
6421 for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps.
6422 This initialization is done recursively, so for instance each element of an
6423 array of structs will have its fields zeroed if no value is specified.
6424 </p>
6425 <p>
6426 These two simple declarations are equivalent:
6427 </p>
6428
6429 <pre>
6430 var i int
6431 var i int = 0
6432 </pre>
6433
6434 <p>
6435 After
6436 </p>
6437
6438 <pre>
6439 type T struct { i int; f float64; next *T }
6440 t := new(T)
6441 </pre>
6442
6443 <p>
6444 the following holds:
6445 </p>
6446
6447 <pre>
6448 t.i == 0
6449 t.f == 0.0
6450 t.next == nil
6451 </pre>
6452
6453 <p>
6454 The same would also be true after
6455 </p>
6456
6457 <pre>
6458 var t T
6459 </pre>
6460
6461 <h3 id="Package_initialization">Package initialization</h3>
6462
6463 <p>
6464 Within a package, package-level variable initialization proceeds stepwise,
6465 with each step selecting the variable earliest in <i>declaration order</i>
6466 which has no dependencies on uninitialized variables.
6467 </p>
6468
6469 <p>
6470 More precisely, a package-level variable is considered <i>ready for
6471 initialization</i> if it is not yet initialized and either has
6472 no <a href="#Variable_declarations">initialization expression</a> or
6473 its initialization expression has no <i>dependencies</i> on uninitialized variables.
6474 Initialization proceeds by repeatedly initializing the next package-level
6475 variable that is earliest in declaration order and ready for initialization,
6476 until there are no variables ready for initialization.
6477 </p>
6478
6479 <p>
6480 If any variables are still uninitialized when this
6481 process ends, those variables are part of one or more initialization cycles,
6482 and the program is not valid.
6483 </p>
6484
6485 <p>
6486 Multiple variables on the left-hand side of a variable declaration initialized
6487 by single (multi-valued) expression on the right-hand side are initialized
6488 together: If any of the variables on the left-hand side is initialized, all
6489 those variables are initialized in the same step.
6490 </p>
6491
6492 <pre>
6493 var x = a
6494 var a, b = f() // a and b are initialized together, before x is initialized
6495 </pre>
6496
6497 <p>
6498 For the purpose of package initialization, <a href="#Blank_identifier">blank</a>
6499 variables are treated like any other variables in declarations.
6500 </p>
6501
6502 <p>
6503 The declaration order of variables declared in multiple files is determined
6504 by the order in which the files are presented to the compiler: Variables
6505 declared in the first file are declared before any of the variables declared
6506 in the second file, and so on.
6507 </p>
6508
6509 <p>
6510 Dependency analysis does not rely on the actual values of the
6511 variables, only on lexical <i>references</i> to them in the source,
6512 analyzed transitively. For instance, if a variable <code>x</code>'s
6513 initialization expression refers to a function whose body refers to
6514 variable <code>y</code> then <code>x</code> depends on <code>y</code>.
6515 Specifically:
6516 </p>
6517
6518 <ul>
6519 <li>
6520 A reference to a variable or function is an identifier denoting that
6521 variable or function.
6522 </li>
6523
6524 <li>
6525 A reference to a method <code>m</code> is a
6526 <a href="#Method_values">method value</a> or
6527 <a href="#Method_expressions">method expression</a> of the form
6528 <code>t.m</code>, where the (static) type of <code>t</code> is
6529 not an interface type, and the method <code>m</code> is in the
6530 <a href="#Method_sets">method set</a> of <code>t</code>.
6531 It is immaterial whether the resulting function value
6532 <code>t.m</code> is invoked.
6533 </li>
6534
6535 <li>
6536 A variable, function, or method <code>x</code> depends on a variable
6537 <code>y</code> if <code>x</code>'s initialization expression or body
6538 (for functions and methods) contains a reference to <code>y</code>
6539 or to a function or method that depends on <code>y</code>.
6540 </li>
6541 </ul>
6542
6543 <p>
6544 For example, given the declarations
6545 </p>
6546
6547 <pre>
6548 var (
6549         a = c + b  // == 9
6550         b = f()    // == 4
6551         c = f()    // == 5
6552         d = 3      // == 5 after initialization has finished
6553 )
6554
6555 func f() int {
6556         d++
6557         return d
6558 }
6559 </pre>
6560
6561 <p>
6562 the initialization order is <code>d</code>, <code>b</code>, <code>c</code>, <code>a</code>.
6563 Note that the order of subexpressions in initialization expressions is irrelevant:
6564 <code>a = c + b</code> and <code>a = b + c</code> result in the same initialization
6565 order in this example.
6566 </p>
6567
6568 <p>
6569 Dependency analysis is performed per package; only references referring
6570 to variables, functions, and (non-interface) methods declared in the current
6571 package are considered. If other, hidden, data dependencies exists between
6572 variables, the initialization order between those variables is unspecified.
6573 </p>
6574
6575 <p>
6576 For instance, given the declarations
6577 </p>
6578
6579 <pre>
6580 var x = I(T{}).ab()   // x has an undetected, hidden dependency on a and b
6581 var _ = sideEffect()  // unrelated to x, a, or b
6582 var a = b
6583 var b = 42
6584
6585 type I interface      { ab() []int }
6586 type T struct{}
6587 func (T) ab() []int   { return []int{a, b} }
6588 </pre>
6589
6590 <p>
6591 the variable <code>a</code> will be initialized after <code>b</code> but
6592 whether <code>x</code> is initialized before <code>b</code>, between
6593 <code>b</code> and <code>a</code>, or after <code>a</code>, and
6594 thus also the moment at which <code>sideEffect()</code> is called (before
6595 or after <code>x</code> is initialized) is not specified.
6596 </p>
6597
6598 <p>
6599 Variables may also be initialized using functions named <code>init</code>
6600 declared in the package block, with no arguments and no result parameters.
6601 </p>
6602
6603 <pre>
6604 func init() { … }
6605 </pre>
6606
6607 <p>
6608 Multiple such functions may be defined per package, even within a single
6609 source file. In the package block, the <code>init</code> identifier can
6610 be used only to declare <code>init</code> functions, yet the identifier
6611 itself is not <a href="#Declarations_and_scope">declared</a>. Thus
6612 <code>init</code> functions cannot be referred to from anywhere
6613 in a program.
6614 </p>
6615
6616 <p>
6617 A package with no imports is initialized by assigning initial values
6618 to all its package-level variables followed by calling all <code>init</code>
6619 functions in the order they appear in the source, possibly in multiple files,
6620 as presented to the compiler.
6621 If a package has imports, the imported packages are initialized
6622 before initializing the package itself. If multiple packages import
6623 a package, the imported package will be initialized only once.
6624 The importing of packages, by construction, guarantees that there
6625 can be no cyclic initialization dependencies.
6626 </p>
6627
6628 <p>
6629 Package initialization&mdash;variable initialization and the invocation of
6630 <code>init</code> functions&mdash;happens in a single goroutine,
6631 sequentially, one package at a time.
6632 An <code>init</code> function may launch other goroutines, which can run
6633 concurrently with the initialization code. However, initialization
6634 always sequences
6635 the <code>init</code> functions: it will not invoke the next one
6636 until the previous one has returned.
6637 </p>
6638
6639 <p>
6640 To ensure reproducible initialization behavior, build systems are encouraged
6641 to present multiple files belonging to the same package in lexical file name
6642 order to a compiler.
6643 </p>
6644
6645
6646 <h3 id="Program_execution">Program execution</h3>
6647 <p>
6648 A complete program is created by linking a single, unimported package
6649 called the <i>main package</i> with all the packages it imports, transitively.
6650 The main package must
6651 have package name <code>main</code> and
6652 declare a function <code>main</code> that takes no
6653 arguments and returns no value.
6654 </p>
6655
6656 <pre>
6657 func main() { … }
6658 </pre>
6659
6660 <p>
6661 Program execution begins by initializing the main package and then
6662 invoking the function <code>main</code>.
6663 When that function invocation returns, the program exits.
6664 It does not wait for other (non-<code>main</code>) goroutines to complete.
6665 </p>
6666
6667 <h2 id="Errors">Errors</h2>
6668
6669 <p>
6670 The predeclared type <code>error</code> is defined as
6671 </p>
6672
6673 <pre>
6674 type error interface {
6675         Error() string
6676 }
6677 </pre>
6678
6679 <p>
6680 It is the conventional interface for representing an error condition,
6681 with the nil value representing no error.
6682 For instance, a function to read data from a file might be defined:
6683 </p>
6684
6685 <pre>
6686 func Read(f *File, b []byte) (n int, err error)
6687 </pre>
6688
6689 <h2 id="Run_time_panics">Run-time panics</h2>
6690
6691 <p>
6692 Execution errors such as attempting to index an array out
6693 of bounds trigger a <i>run-time panic</i> equivalent to a call of
6694 the built-in function <a href="#Handling_panics"><code>panic</code></a>
6695 with a value of the implementation-defined interface type <code>runtime.Error</code>.
6696 That type satisfies the predeclared interface type
6697 <a href="#Errors"><code>error</code></a>.
6698 The exact error values that
6699 represent distinct run-time error conditions are unspecified.
6700 </p>
6701
6702 <pre>
6703 package runtime
6704
6705 type Error interface {
6706         error
6707         // and perhaps other methods
6708 }
6709 </pre>
6710
6711 <h2 id="System_considerations">System considerations</h2>
6712
6713 <h3 id="Package_unsafe">Package <code>unsafe</code></h3>
6714
6715 <p>
6716 The built-in package <code>unsafe</code>, known to the compiler
6717 and accessible through the <a href="#Import_declarations">import path</a> <code>"unsafe"</code>,
6718 provides facilities for low-level programming including operations
6719 that violate the type system. A package using <code>unsafe</code>
6720 must be vetted manually for type safety and may not be portable.
6721 The package provides the following interface:
6722 </p>
6723
6724 <pre class="grammar">
6725 package unsafe
6726
6727 type ArbitraryType int  // shorthand for an arbitrary Go type; it is not a real type
6728 type Pointer *ArbitraryType
6729
6730 func Alignof(variable ArbitraryType) uintptr
6731 func Offsetof(selector ArbitraryType) uintptr
6732 func Sizeof(variable ArbitraryType) uintptr
6733
6734 type IntegerType int  // shorthand for an integer type; it is not a real type
6735 func Add(ptr Pointer, len IntegerType) Pointer
6736 func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType
6737 </pre>
6738
6739 <p>
6740 A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code>
6741 value may not be <a href="#Address_operators">dereferenced</a>.
6742 Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to
6743 a type of underlying type <code>Pointer</code> and vice versa.
6744 The effect of converting between <code>Pointer</code> and <code>uintptr</code> is implementation-defined.
6745 </p>
6746
6747 <pre>
6748 var f float64
6749 bits = *(*uint64)(unsafe.Pointer(&amp;f))
6750
6751 type ptr unsafe.Pointer
6752 bits = *(*uint64)(ptr(&amp;f))
6753
6754 var p ptr = nil
6755 </pre>
6756
6757 <p>
6758 The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code>
6759 of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code>
6760 as if <code>v</code> was declared via <code>var v = x</code>.
6761 </p>
6762 <p>
6763 The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a>
6764 <code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code>
6765 or <code>*s</code>, and returns the field offset in bytes relative to the struct's address.
6766 If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable
6767 without pointer indirections through fields of the struct.
6768 For a struct <code>s</code> with field <code>f</code>:
6769 </p>
6770
6771 <pre>
6772 uintptr(unsafe.Pointer(&amp;s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&amp;s.f))
6773 </pre>
6774
6775 <p>
6776 Computer architectures may require memory addresses to be <i>aligned</i>;
6777 that is, for addresses of a variable to be a multiple of a factor,
6778 the variable's type's <i>alignment</i>.  The function <code>Alignof</code>
6779 takes an expression denoting a variable of any type and returns the
6780 alignment of the (type of the) variable in bytes.  For a variable
6781 <code>x</code>:
6782 </p>
6783
6784 <pre>
6785 uintptr(unsafe.Pointer(&amp;x)) % unsafe.Alignof(x) == 0
6786 </pre>
6787
6788 <p>
6789 Calls to <code>Alignof</code>, <code>Offsetof</code>, and
6790 <code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>.
6791 </p>
6792
6793 <p>
6794 The function <code>Add</code> adds <code>len</code> to <code>ptr</code>
6795 and returns the updated pointer <code>unsafe.Pointer(uintptr(ptr) + uintptr(len))</code>.
6796 The <code>len</code> argument must be of integer type or an untyped <a href="#Constants">constant</a>.
6797 A constant <code>len</code> argument must be <a href="#Representability">representable</a> by a value of type <code>int</code>;
6798 if it is an untyped constant it is given type <code>int</code>.
6799 The rules for <a href="/pkg/unsafe#Pointer">valid uses</a> of <code>Pointer</code> still apply.
6800 </p>
6801
6802 <p>
6803 The function <code>Slice</code> returns a slice whose underlying array starts at <code>ptr</code>
6804 and whose length and capacity are <code>len</code>.
6805 <code>Slice(ptr, len)</code> is equivalent to
6806 </p>
6807
6808 <pre>
6809 (*[len]ArbitraryType)(unsafe.Pointer(ptr))[:]
6810 </pre>
6811
6812 <p>
6813 except that, as a special case, if <code>ptr</code>
6814 is <code>nil</code> and <code>len</code> is zero,
6815 <code>Slice</code> returns <code>nil</code>.
6816 </p>
6817
6818 <p>
6819 The <code>len</code> argument must be of integer type or an untyped <a href="#Constants">constant</a>.
6820 A constant <code>len</code> argument must be non-negative and <a href="#Representability">representable</a> by a value of type <code>int</code>;
6821 if it is an untyped constant it is given type <code>int</code>.
6822 At run time, if <code>len</code> is negative,
6823 or if <code>ptr</code> is <code>nil</code> and <code>len</code> is not zero,
6824 a <a href="#Run_time_panics">run-time panic</a> occurs.
6825 </p>
6826
6827 <h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3>
6828
6829 <p>
6830 For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed:
6831 </p>
6832
6833 <pre class="grammar">
6834 type                                 size in bytes
6835
6836 byte, uint8, int8                     1
6837 uint16, int16                         2
6838 uint32, int32, float32                4
6839 uint64, int64, float64, complex64     8
6840 complex128                           16
6841 </pre>
6842
6843 <p>
6844 The following minimal alignment properties are guaranteed:
6845 </p>
6846 <ol>
6847 <li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1.
6848 </li>
6849
6850 <li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of
6851    all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1.
6852 </li>
6853
6854 <li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as
6855         the alignment of a variable of the array's element type.
6856 </li>
6857 </ol>
6858
6859 <p>
6860 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.
6861 </p>