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