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