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