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