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