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