Debian Codegraph @

doc/go_spec.html

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