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