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