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