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