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