2 "Title": "The Go Programming Language Specification",
3 "Subtitle": "Version of May 12, 2022",
7 <h2 id="Introduction">Introduction</h2>
10 This is the reference manual for the Go programming language.
11 The pre-Go1.18 version, without generics, can be found
12 <a href="/doc/go1.17_spec.html">here</a>.
13 For more information and other documents, see <a href="/">golang.org</a>.
17 Go is a general-purpose language designed with systems programming
18 in mind. It is strongly typed and garbage-collected and has explicit
19 support for concurrent programming. Programs are constructed from
20 <i>packages</i>, whose properties allow efficient management of
25 The grammar is compact and simple to parse, allowing for easy analysis
26 by automatic tools such as integrated development environments.
29 <h2 id="Notation">Notation</h2>
31 The syntax is specified using Extended Backus-Naur Form (EBNF):
35 Production = production_name "=" [ Expression ] "." .
36 Expression = Alternative { "|" Alternative } .
37 Alternative = Term { Term } .
38 Term = production_name | token [ "…" token ] | Group | Option | Repetition .
39 Group = "(" Expression ")" .
40 Option = "[" Expression "]" .
41 Repetition = "{" Expression "}" .
45 Productions are expressions constructed from terms and the following
46 operators, in increasing precedence:
51 [] option (0 or 1 times)
52 {} repetition (0 to n times)
56 Lowercase production names are used to identify lexical tokens.
57 Non-terminals are in CamelCase. Lexical tokens are enclosed in
58 double quotes <code>""</code> or back quotes <code>``</code>.
62 The form <code>a … b</code> represents the set of characters from
63 <code>a</code> through <code>b</code> as alternatives. The horizontal
64 ellipsis <code>…</code> is also used elsewhere in the spec to informally denote various
65 enumerations or code snippets that are not further specified. The character <code>…</code>
66 (as opposed to the three characters <code>...</code>) is not a token of the Go
70 <h2 id="Source_code_representation">Source code representation</h2>
73 Source code is Unicode text encoded in
74 <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. The text is not
75 canonicalized, so a single accented code point is distinct from the
76 same character constructed from combining an accent and a letter;
77 those are treated as two code points. For simplicity, this document
78 will use the unqualified term <i>character</i> to refer to a Unicode code point
82 Each code point is distinct; for instance, uppercase and lowercase letters
83 are different characters.
86 Implementation restriction: For compatibility with other tools, a
87 compiler may disallow the NUL character (U+0000) in the source text.
90 Implementation restriction: For compatibility with other tools, a
91 compiler may ignore a UTF-8-encoded byte order mark
92 (U+FEFF) if it is the first Unicode code point in the source text.
93 A byte order mark may be disallowed anywhere else in the source.
96 <h3 id="Characters">Characters</h3>
99 The following terms are used to denote specific Unicode character categories:
102 newline = /* the Unicode code point U+000A */ .
103 unicode_char = /* an arbitrary Unicode code point except newline */ .
104 unicode_letter = /* a Unicode code point categorized as "Letter" */ .
105 unicode_digit = /* a Unicode code point categorized as "Number, decimal digit" */ .
109 In <a href="https://www.unicode.org/versions/Unicode8.0.0/">The Unicode Standard 8.0</a>,
110 Section 4.5 "General Category" defines a set of character categories.
111 Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo
112 as Unicode letters, and those in the Number category Nd as Unicode digits.
115 <h3 id="Letters_and_digits">Letters and digits</h3>
118 The underscore character <code>_</code> (U+005F) is considered a lowercase letter.
121 letter = unicode_letter | "_" .
122 decimal_digit = "0" … "9" .
123 binary_digit = "0" | "1" .
124 octal_digit = "0" … "7" .
125 hex_digit = "0" … "9" | "A" … "F" | "a" … "f" .
128 <h2 id="Lexical_elements">Lexical elements</h2>
130 <h3 id="Comments">Comments</h3>
133 Comments serve as program documentation. There are two forms:
138 <i>Line comments</i> start with the character sequence <code>//</code>
139 and stop at the end of the line.
142 <i>General comments</i> start with the character sequence <code>/*</code>
143 and stop with the first subsequent character sequence <code>*/</code>.
148 A comment cannot start inside a <a href="#Rune_literals">rune</a> or
149 <a href="#String_literals">string literal</a>, or inside a comment.
150 A general comment containing no newlines acts like a space.
151 Any other comment acts like a newline.
154 <h3 id="Tokens">Tokens</h3>
157 Tokens form the vocabulary of the Go language.
158 There are four classes: <i>identifiers</i>, <i>keywords</i>, <i>operators
159 and punctuation</i>, and <i>literals</i>. <i>White space</i>, formed from
160 spaces (U+0020), horizontal tabs (U+0009),
161 carriage returns (U+000D), and newlines (U+000A),
162 is ignored except as it separates tokens
163 that would otherwise combine into a single token. Also, a newline or end of file
164 may trigger the insertion of a <a href="#Semicolons">semicolon</a>.
165 While breaking the input into tokens,
166 the next token is the longest sequence of characters that form a
170 <h3 id="Semicolons">Semicolons</h3>
173 The formal grammar uses semicolons <code>";"</code> as terminators in
174 a number of productions. Go programs may omit most of these semicolons
175 using the following two rules:
180 When the input is broken into tokens, a semicolon is automatically inserted
181 into the token stream immediately after a line's final token if that token is
184 <a href="#Identifiers">identifier</a>
188 <a href="#Integer_literals">integer</a>,
189 <a href="#Floating-point_literals">floating-point</a>,
190 <a href="#Imaginary_literals">imaginary</a>,
191 <a href="#Rune_literals">rune</a>, or
192 <a href="#String_literals">string</a> literal
195 <li>one of the <a href="#Keywords">keywords</a>
197 <code>continue</code>,
198 <code>fallthrough</code>, or
202 <li>one of the <a href="#Operators_and_punctuation">operators and punctuation</a>
213 To allow complex statements to occupy a single line, a semicolon
214 may be omitted before a closing <code>")"</code> or <code>"}"</code>.
219 To reflect idiomatic use, code examples in this document elide semicolons
224 <h3 id="Identifiers">Identifiers</h3>
227 Identifiers name program entities such as variables and types.
228 An identifier is a sequence of one or more letters and digits.
229 The first character in an identifier must be a letter.
232 identifier = letter { letter | unicode_digit } .
237 ThisVariableIsExported
242 Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>.
246 <h3 id="Keywords">Keywords</h3>
249 The following keywords are reserved and may not be used as identifiers.
251 <pre class="grammar">
252 break default func interface select
253 case defer go map struct
254 chan else goto package switch
255 const fallthrough if range type
256 continue for import return var
259 <h3 id="Operators_and_punctuation">Operators and punctuation</h3>
262 The following character sequences represent <a href="#Operators">operators</a>
263 (including <a href="#Assignments">assignment operators</a>) and punctuation:
265 <pre class="grammar">
266 + & += &= && == != ( )
267 - | -= |= || < <= [ ]
268 * ^ *= ^= <- > >= { }
269 / << /= <<= ++ = := , ;
270 % >> %= >>= -- ! ... . :
274 <h3 id="Integer_literals">Integer literals</h3>
277 An integer literal is a sequence of digits representing an
278 <a href="#Constants">integer constant</a>.
279 An optional prefix sets a non-decimal base: <code>0b</code> or <code>0B</code>
280 for binary, <code>0</code>, <code>0o</code>, or <code>0O</code> for octal,
281 and <code>0x</code> or <code>0X</code> for hexadecimal.
282 A single <code>0</code> is considered a decimal zero.
283 In hexadecimal literals, letters <code>a</code> through <code>f</code>
284 and <code>A</code> through <code>F</code> represent values 10 through 15.
288 For readability, an underscore character <code>_</code> may appear after
289 a base prefix or between successive digits; such underscores do not change
293 int_lit = decimal_lit | binary_lit | octal_lit | hex_lit .
294 decimal_lit = "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] .
295 binary_lit = "0" ( "b" | "B" ) [ "_" ] binary_digits .
296 octal_lit = "0" [ "o" | "O" ] [ "_" ] octal_digits .
297 hex_lit = "0" ( "x" | "X" ) [ "_" ] hex_digits .
299 decimal_digits = decimal_digit { [ "_" ] decimal_digit } .
300 binary_digits = binary_digit { [ "_" ] binary_digit } .
301 octal_digits = octal_digit { [ "_" ] octal_digit } .
302 hex_digits = hex_digit { [ "_" ] hex_digit } .
311 0O600 // second character is capital letter 'O'
315 170141183460469231731687303715884105727
316 170_141183_460469_231731_687303_715884_105727
318 _42 // an identifier, not an integer literal
319 42_ // invalid: _ must separate successive digits
320 4__2 // invalid: only one _ at a time
321 0_xBadFace // invalid: _ must separate successive digits
325 <h3 id="Floating-point_literals">Floating-point literals</h3>
328 A floating-point literal is a decimal or hexadecimal representation of a
329 <a href="#Constants">floating-point constant</a>.
333 A decimal floating-point literal consists of an integer part (decimal digits),
334 a decimal point, a fractional part (decimal digits), and an exponent part
335 (<code>e</code> or <code>E</code> followed by an optional sign and decimal digits).
336 One of the integer part or the fractional part may be elided; one of the decimal point
337 or the exponent part may be elided.
338 An exponent value exp scales the mantissa (integer and fractional part) by 10<sup>exp</sup>.
342 A hexadecimal floating-point literal consists of a <code>0x</code> or <code>0X</code>
343 prefix, an integer part (hexadecimal digits), a radix point, a fractional part (hexadecimal digits),
344 and an exponent part (<code>p</code> or <code>P</code> followed by an optional sign and decimal digits).
345 One of the integer part or the fractional part may be elided; the radix point may be elided as well,
346 but the exponent part is required. (This syntax matches the one given in IEEE 754-2008 §5.12.3.)
347 An exponent value exp scales the mantissa (integer and fractional part) by 2<sup>exp</sup>.
351 For readability, an underscore character <code>_</code> may appear after
352 a base prefix or between successive digits; such underscores do not change
357 float_lit = decimal_float_lit | hex_float_lit .
359 decimal_float_lit = decimal_digits "." [ decimal_digits ] [ decimal_exponent ] |
360 decimal_digits decimal_exponent |
361 "." decimal_digits [ decimal_exponent ] .
362 decimal_exponent = ( "e" | "E" ) [ "+" | "-" ] decimal_digits .
364 hex_float_lit = "0" ( "x" | "X" ) hex_mantissa hex_exponent .
365 hex_mantissa = [ "_" ] hex_digits "." [ hex_digits ] |
368 hex_exponent = ( "p" | "P" ) [ "+" | "-" ] decimal_digits .
386 0x1.Fp+0 // == 1.9375
388 0X_1FFFP-16 // == 0.1249847412109375
389 0x15e-2 // == 0x15e - 2 (integer subtraction)
391 0x.p1 // invalid: mantissa has no digits
392 1p-2 // invalid: p exponent requires hexadecimal mantissa
393 0x1.5e-2 // invalid: hexadecimal mantissa requires p exponent
394 1_.5 // invalid: _ must separate successive digits
395 1._5 // invalid: _ must separate successive digits
396 1.5_e1 // invalid: _ must separate successive digits
397 1.5e_1 // invalid: _ must separate successive digits
398 1.5e1_ // invalid: _ must separate successive digits
402 <h3 id="Imaginary_literals">Imaginary literals</h3>
405 An imaginary literal represents the imaginary part of a
406 <a href="#Constants">complex constant</a>.
407 It consists of an <a href="#Integer_literals">integer</a> or
408 <a href="#Floating-point_literals">floating-point</a> literal
409 followed by the lowercase letter <code>i</code>.
410 The value of an imaginary literal is the value of the respective
411 integer or floating-point literal multiplied by the imaginary unit <i>i</i>.
415 imaginary_lit = (decimal_digits | int_lit | float_lit) "i" .
419 For backward compatibility, an imaginary literal's integer part consisting
420 entirely of decimal digits (and possibly underscores) is considered a decimal
421 integer, even if it starts with a leading <code>0</code>.
426 0123i // == 123i for backward-compatibility
427 0o123i // == 0o123 * 1i == 83i
428 0xabci // == 0xabc * 1i == 2748i
436 0x1p-2i // == 0x1p-2 * 1i == 0.25i
440 <h3 id="Rune_literals">Rune literals</h3>
443 A rune literal represents a <a href="#Constants">rune constant</a>,
444 an integer value identifying a Unicode code point.
445 A rune literal is expressed as one or more characters enclosed in single quotes,
446 as in <code>'x'</code> or <code>'\n'</code>.
447 Within the quotes, any character may appear except newline and unescaped single
448 quote. A single quoted character represents the Unicode value
449 of the character itself,
450 while multi-character sequences beginning with a backslash encode
451 values in various formats.
455 The simplest form represents the single character within the quotes;
456 since Go source text is Unicode characters encoded in UTF-8, multiple
457 UTF-8-encoded bytes may represent a single integer value. For
458 instance, the literal <code>'a'</code> holds a single byte representing
459 a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while
460 <code>'ä'</code> holds two bytes (<code>0xc3</code> <code>0xa4</code>) representing
461 a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>.
465 Several backslash escapes allow arbitrary values to be encoded as
466 ASCII text. There are four ways to represent the integer value
467 as a numeric constant: <code>\x</code> followed by exactly two hexadecimal
468 digits; <code>\u</code> followed by exactly four hexadecimal digits;
469 <code>\U</code> followed by exactly eight hexadecimal digits, and a
470 plain backslash <code>\</code> followed by exactly three octal digits.
471 In each case the value of the literal is the value represented by
472 the digits in the corresponding base.
476 Although these representations all result in an integer, they have
477 different valid ranges. Octal escapes must represent a value between
478 0 and 255 inclusive. Hexadecimal escapes satisfy this condition
479 by construction. The escapes <code>\u</code> and <code>\U</code>
480 represent Unicode code points so within them some values are illegal,
481 in particular those above <code>0x10FFFF</code> and surrogate halves.
485 After a backslash, certain single-character escapes represent special values:
488 <pre class="grammar">
489 \a U+0007 alert or bell
492 \n U+000A line feed or newline
493 \r U+000D carriage return
494 \t U+0009 horizontal tab
495 \v U+000B vertical tab
497 \' U+0027 single quote (valid escape only within rune literals)
498 \" U+0022 double quote (valid escape only within string literals)
502 All other sequences starting with a backslash are illegal inside rune literals.
505 rune_lit = "'" ( unicode_value | byte_value ) "'" .
506 unicode_value = unicode_char | little_u_value | big_u_value | escaped_char .
507 byte_value = octal_byte_value | hex_byte_value .
508 octal_byte_value = `\` octal_digit octal_digit octal_digit .
509 hex_byte_value = `\` "x" hex_digit hex_digit .
510 little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit .
511 big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit
512 hex_digit hex_digit hex_digit hex_digit .
513 escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
528 '\'' // rune literal containing single quote character
529 'aa' // illegal: too many characters
530 '\xa' // illegal: too few hexadecimal digits
531 '\0' // illegal: too few octal digits
532 '\400' // illegal: octal value over 255
533 '\uDFFF' // illegal: surrogate half
534 '\U00110000' // illegal: invalid Unicode code point
538 <h3 id="String_literals">String literals</h3>
541 A string literal represents a <a href="#Constants">string constant</a>
542 obtained from concatenating a sequence of characters. There are two forms:
543 raw string literals and interpreted string literals.
547 Raw string literals are character sequences between back quotes, as in
548 <code>`foo`</code>. Within the quotes, any character may appear except
549 back quote. The value of a raw string literal is the
550 string composed of the uninterpreted (implicitly UTF-8-encoded) characters
552 in particular, backslashes have no special meaning and the string may
554 Carriage return characters ('\r') inside raw string literals
555 are discarded from the raw string value.
559 Interpreted string literals are character sequences between double
560 quotes, as in <code>"bar"</code>.
561 Within the quotes, any character may appear except newline and unescaped double quote.
562 The text between the quotes forms the
563 value of the literal, with backslash escapes interpreted as they
564 are in <a href="#Rune_literals">rune literals</a> (except that <code>\'</code> is illegal and
565 <code>\"</code> is legal), with the same restrictions.
566 The three-digit octal (<code>\</code><i>nnn</i>)
567 and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual
568 <i>bytes</i> of the resulting string; all other escapes represent
569 the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
570 Thus inside a string literal <code>\377</code> and <code>\xFF</code> represent
571 a single byte of value <code>0xFF</code>=255, while <code>ÿ</code>,
572 <code>\u00FF</code>, <code>\U000000FF</code> and <code>\xc3\xbf</code> represent
573 the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character
578 string_lit = raw_string_lit | interpreted_string_lit .
579 raw_string_lit = "`" { unicode_char | newline } "`" .
580 interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
584 `abc` // same as "abc"
586 \n` // same as "\\n\n\\n"
593 "\uD800" // illegal: surrogate half
594 "\U00110000" // illegal: invalid Unicode code point
598 These examples all represent the same string:
602 "日本語" // UTF-8 input text
603 `日本語` // UTF-8 input text as a raw literal
604 "\u65e5\u672c\u8a9e" // the explicit Unicode code points
605 "\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points
606 "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes
610 If the source code represents a character as two code points, such as
611 a combining form involving an accent and a letter, the result will be
612 an error if placed in a rune literal (it is not a single code
613 point), and will appear as two code points if placed in a string
618 <h2 id="Constants">Constants</h2>
620 <p>There are <i>boolean constants</i>,
621 <i>rune constants</i>,
622 <i>integer constants</i>,
623 <i>floating-point constants</i>, <i>complex constants</i>,
624 and <i>string constants</i>. Rune, integer, floating-point,
625 and complex constants are
626 collectively called <i>numeric constants</i>.
630 A constant value is represented by a
631 <a href="#Rune_literals">rune</a>,
632 <a href="#Integer_literals">integer</a>,
633 <a href="#Floating-point_literals">floating-point</a>,
634 <a href="#Imaginary_literals">imaginary</a>,
636 <a href="#String_literals">string</a> literal,
637 an identifier denoting a constant,
638 a <a href="#Constant_expressions">constant expression</a>,
639 a <a href="#Conversions">conversion</a> with a result that is a constant, or
640 the result value of some built-in functions such as
641 <code>unsafe.Sizeof</code> applied to <a href="#Package_unsafe">certain values</a>,
642 <code>cap</code> or <code>len</code> applied to
643 <a href="#Length_and_capacity">some expressions</a>,
644 <code>real</code> and <code>imag</code> applied to a complex constant
645 and <code>complex</code> applied to numeric constants.
646 The boolean truth values are represented by the predeclared constants
647 <code>true</code> and <code>false</code>. The predeclared identifier
648 <a href="#Iota">iota</a> denotes an integer constant.
652 In general, complex constants are a form of
653 <a href="#Constant_expressions">constant expression</a>
654 and are discussed in that section.
658 Numeric constants represent exact values of arbitrary precision and do not overflow.
659 Consequently, there are no constants denoting the IEEE-754 negative zero, infinity,
660 and not-a-number values.
664 Constants may be <a href="#Types">typed</a> or <i>untyped</i>.
665 Literal constants, <code>true</code>, <code>false</code>, <code>iota</code>,
666 and certain <a href="#Constant_expressions">constant expressions</a>
667 containing only untyped constant operands are untyped.
671 A constant may be given a type explicitly by a <a href="#Constant_declarations">constant declaration</a>
672 or <a href="#Conversions">conversion</a>, or implicitly when used in a
673 <a href="#Variable_declarations">variable declaration</a> or an
674 <a href="#Assignments">assignment</a> or as an
675 operand in an <a href="#Expressions">expression</a>.
676 It is an error if the constant value
677 cannot be <a href="#Representability">represented</a> as a value of the respective type.
678 If the type is a type parameter, the constant is converted into a non-constant
679 value of the type parameter.
683 An untyped constant has a <i>default type</i> which is the type to which the
684 constant is implicitly converted in contexts where a typed value is required,
685 for instance, in a <a href="#Short_variable_declarations">short variable declaration</a>
686 such as <code>i := 0</code> where there is no explicit type.
687 The default type of an untyped constant is <code>bool</code>, <code>rune</code>,
688 <code>int</code>, <code>float64</code>, <code>complex128</code> or <code>string</code>
689 respectively, depending on whether it is a boolean, rune, integer, floating-point,
690 complex, or string constant.
694 Implementation restriction: Although numeric constants have arbitrary
695 precision in the language, a compiler may implement them using an
696 internal representation with limited precision. That said, every
701 <li>Represent integer constants with at least 256 bits.</li>
703 <li>Represent floating-point constants, including the parts of
704 a complex constant, with a mantissa of at least 256 bits
705 and a signed binary exponent of at least 16 bits.</li>
707 <li>Give an error if unable to represent an integer constant
710 <li>Give an error if unable to represent a floating-point or
711 complex constant due to overflow.</li>
713 <li>Round to the nearest representable constant if unable to
714 represent a floating-point or complex constant due to limits
719 These requirements apply both to literal constants and to the result
720 of evaluating <a href="#Constant_expressions">constant
725 <h2 id="Variables">Variables</h2>
728 A variable is a storage location for holding a <i>value</i>.
729 The set of permissible values is determined by the
730 variable's <i><a href="#Types">type</a></i>.
734 A <a href="#Variable_declarations">variable declaration</a>
735 or, for function parameters and results, the signature
736 of a <a href="#Function_declarations">function declaration</a>
737 or <a href="#Function_literals">function literal</a> reserves
738 storage for a named variable.
740 Calling the built-in function <a href="#Allocation"><code>new</code></a>
741 or taking the address of a <a href="#Composite_literals">composite literal</a>
742 allocates storage for a variable at run time.
743 Such an anonymous variable is referred to via a (possibly implicit)
744 <a href="#Address_operators">pointer indirection</a>.
748 <i>Structured</i> variables of <a href="#Array_types">array</a>, <a href="#Slice_types">slice</a>,
749 and <a href="#Struct_types">struct</a> types have elements and fields that may
750 be <a href="#Address_operators">addressed</a> individually. Each such element
751 acts like a variable.
755 The <i>static type</i> (or just <i>type</i>) of a variable is the
756 type given in its declaration, the type provided in the
757 <code>new</code> call or composite literal, or the type of
758 an element of a structured variable.
759 Variables of interface type also have a distinct <i>dynamic type</i>,
760 which is the (non-interface) type of the value assigned to the variable at run time
761 (unless the value is the predeclared identifier <code>nil</code>,
763 The dynamic type may vary during execution but values stored in interface
764 variables are always <a href="#Assignability">assignable</a>
765 to the static type of the variable.
769 var x interface{} // x is nil and has static type interface{}
770 var v *T // v has value nil, static type *T
771 x = 42 // x has value 42 and dynamic type int
772 x = v // x has value (*T)(nil) and dynamic type *T
776 A variable's value is retrieved by referring to the variable in an
777 <a href="#Expressions">expression</a>; it is the most recent value
778 <a href="#Assignments">assigned</a> to the variable.
779 If a variable has not yet been assigned a value, its value is the
780 <a href="#The_zero_value">zero value</a> for its type.
784 <h2 id="Types">Types</h2>
787 A type determines a set of values together with operations and methods specific
788 to those values. A type may be denoted by a <i>type name</i>, if it has one, which must be
789 followed by <a href="#Instantiations">type arguments</a> if the type is generic.
790 A type may also be specified using a <i>type literal</i>, which composes a type
795 Type = TypeName [ TypeArgs ] | TypeLit | "(" Type ")" .
796 TypeName = identifier | QualifiedIdent .
797 TypeArgs = "[" TypeList [ "," ] "]" .
798 TypeList = Type { "," Type } .
799 TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
800 SliceType | MapType | ChannelType .
804 The language <a href="#Predeclared_identifiers">predeclares</a> certain type names.
805 Others are introduced with <a href="#Type_declarations">type declarations</a>
806 or <a href="#Type_parameter_declarations">type parameter lists</a>.
807 <i>Composite types</i>—array, struct, pointer, function,
808 interface, slice, map, and channel types—may be constructed using
813 Predeclared types, defined types, and type parameters are called <i>named types</i>.
814 An alias denotes a named type if the type given in the alias declaration is a named type.
817 <h3 id="Boolean_types">Boolean types</h3>
820 A <i>boolean type</i> represents the set of Boolean truth values
821 denoted by the predeclared constants <code>true</code>
822 and <code>false</code>. The predeclared boolean type is <code>bool</code>;
823 it is a <a href="#Type_definitions">defined type</a>.
826 <h3 id="Numeric_types">Numeric types</h3>
829 An <i>integer</i>, <i>floating-point</i>, or <i>complex</i> type
830 represents the set of integer, floating-point, or complex values, respectively.
831 They are collectively called <i>numeric types</i>.
832 The predeclared architecture-independent numeric types are:
835 <pre class="grammar">
836 uint8 the set of all unsigned 8-bit integers (0 to 255)
837 uint16 the set of all unsigned 16-bit integers (0 to 65535)
838 uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
839 uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
841 int8 the set of all signed 8-bit integers (-128 to 127)
842 int16 the set of all signed 16-bit integers (-32768 to 32767)
843 int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
844 int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
846 float32 the set of all IEEE-754 32-bit floating-point numbers
847 float64 the set of all IEEE-754 64-bit floating-point numbers
849 complex64 the set of all complex numbers with float32 real and imaginary parts
850 complex128 the set of all complex numbers with float64 real and imaginary parts
857 The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using
858 <a href="https://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>.
862 There is also a set of predeclared integer types with implementation-specific sizes:
865 <pre class="grammar">
866 uint either 32 or 64 bits
867 int same size as uint
868 uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value
872 To avoid portability issues all numeric types are <a href="#Type_definitions">defined
873 types</a> and thus distinct except
874 <code>byte</code>, which is an <a href="#Alias_declarations">alias</a> for <code>uint8</code>, and
875 <code>rune</code>, which is an alias for <code>int32</code>.
877 are required when different numeric types are mixed in an expression
878 or assignment. For instance, <code>int32</code> and <code>int</code>
879 are not the same type even though they may have the same size on a
880 particular architecture.
883 <h3 id="String_types">String types</h3>
886 A <i>string type</i> represents the set of string values.
887 A string value is a (possibly empty) sequence of bytes.
888 The number of bytes is called the length of the string and is never negative.
889 Strings are immutable: once created,
890 it is impossible to change the contents of a string.
891 The predeclared string type is <code>string</code>;
892 it is a <a href="#Type_definitions">defined type</a>.
896 The length of a string <code>s</code> can be discovered using
897 the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
898 The length is a compile-time constant if the string is a constant.
899 A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>
900 0 through <code>len(s)-1</code>.
901 It is illegal to take the address of such an element; if
902 <code>s[i]</code> is the <code>i</code>'th byte of a
903 string, <code>&s[i]</code> is invalid.
907 <h3 id="Array_types">Array types</h3>
910 An array is a numbered sequence of elements of a single
911 type, called the element type.
912 The number of elements is called the length of the array and is never negative.
916 ArrayType = "[" ArrayLength "]" ElementType .
917 ArrayLength = Expression .
922 The length is part of the array's type; it must evaluate to a
923 non-negative <a href="#Constants">constant</a>
924 <a href="#Representability">representable</a> by a value
925 of type <code>int</code>.
926 The length of array <code>a</code> can be discovered
927 using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
928 The elements can be addressed by integer <a href="#Index_expressions">indices</a>
929 0 through <code>len(a)-1</code>.
930 Array types are always one-dimensional but may be composed to form
931 multi-dimensional types.
936 [2*N] struct { x, y int32 }
939 [2][2][2]float64 // same as [2]([2]([2]float64))
942 <h3 id="Slice_types">Slice types</h3>
945 A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and
946 provides access to a numbered sequence of elements from that array.
947 A slice type denotes the set of all slices of arrays of its element type.
948 The number of elements is called the length of the slice and is never negative.
949 The value of an uninitialized slice is <code>nil</code>.
953 SliceType = "[" "]" ElementType .
957 The length of a slice <code>s</code> can be discovered by the built-in function
958 <a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during
959 execution. The elements can be addressed by integer <a href="#Index_expressions">indices</a>
960 0 through <code>len(s)-1</code>. The slice index of a
961 given element may be less than the index of the same element in the
965 A slice, once initialized, is always associated with an underlying
966 array that holds its elements. A slice therefore shares storage
967 with its array and with other slices of the same array; by contrast,
968 distinct arrays always represent distinct storage.
971 The array underlying a slice may extend past the end of the slice.
972 The <i>capacity</i> is a measure of that extent: it is the sum of
973 the length of the slice and the length of the array beyond the slice;
974 a slice of length up to that capacity can be created by
975 <a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice.
976 The capacity of a slice <code>a</code> can be discovered using the
977 built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.
981 A new, initialized slice value for a given element type <code>T</code> may be
982 made using the built-in function
983 <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
984 which takes a slice type
985 and parameters specifying the length and optionally the capacity.
986 A slice created with <code>make</code> always allocates a new, hidden array
987 to which the returned slice value refers. That is, executing
991 make([]T, length, capacity)
995 produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a>
996 it, so these two expressions are equivalent:
1000 make([]int, 50, 100)
1005 Like arrays, slices are always one-dimensional but may be composed to construct
1006 higher-dimensional objects.
1007 With arrays of arrays, the inner arrays are, by construction, always the same length;
1008 however with slices of slices (or arrays of slices), the inner lengths may vary dynamically.
1009 Moreover, the inner slices must be initialized individually.
1012 <h3 id="Struct_types">Struct types</h3>
1015 A struct is a sequence of named elements, called fields, each of which has a
1016 name and a type. Field names may be specified explicitly (IdentifierList) or
1017 implicitly (EmbeddedField).
1018 Within a struct, non-<a href="#Blank_identifier">blank</a> field names must
1019 be <a href="#Uniqueness_of_identifiers">unique</a>.
1023 StructType = "struct" "{" { FieldDecl ";" } "}" .
1024 FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] .
1025 EmbeddedField = [ "*" ] TypeName .
1033 // A struct with 6 fields.
1037 _ float32 // padding
1044 A field declared with a type but no explicit field name is called an <i>embedded field</i>.
1045 An embedded field must be specified as
1046 a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>,
1047 and <code>T</code> itself may not be
1048 a pointer type. The unqualified type name acts as the field name.
1052 // A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4
1054 T1 // field name is T1
1055 *T2 // field name is T2
1056 P.T3 // field name is T3
1057 *P.T4 // field name is T4
1058 x, y int // field names are x and y
1063 The following declaration is illegal because field names must be unique
1069 T // conflicts with embedded field *T and *P.T
1070 *T // conflicts with embedded field T and *P.T
1071 *P.T // conflicts with embedded field T and *T
1076 A field or <a href="#Method_declarations">method</a> <code>f</code> of an
1077 embedded field in a struct <code>x</code> is called <i>promoted</i> if
1078 <code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes
1079 that field or method <code>f</code>.
1083 Promoted fields act like ordinary fields
1084 of a struct except that they cannot be used as field names in
1085 <a href="#Composite_literals">composite literals</a> of the struct.
1089 Given a struct type <code>S</code> and a <a href="#Type_definitions">defined type</a>
1090 <code>T</code>, promoted methods are included in the method set of the struct as follows:
1094 If <code>S</code> contains an embedded field <code>T</code>,
1095 the <a href="#Method_sets">method sets</a> of <code>S</code>
1096 and <code>*S</code> both include promoted methods with receiver
1097 <code>T</code>. The method set of <code>*S</code> also
1098 includes promoted methods with receiver <code>*T</code>.
1102 If <code>S</code> contains an embedded field <code>*T</code>,
1103 the method sets of <code>S</code> and <code>*S</code> both
1104 include promoted methods with receiver <code>T</code> or
1110 A field declaration may be followed by an optional string literal <i>tag</i>,
1111 which becomes an attribute for all the fields in the corresponding
1112 field declaration. An empty tag string is equivalent to an absent tag.
1113 The tags are made visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a>
1114 and take part in <a href="#Type_identity">type identity</a> for structs
1115 but are otherwise ignored.
1120 x, y float64 "" // an empty tag string is like an absent tag
1121 name string "any string is permitted as a tag"
1122 _ [4]byte "ceci n'est pas un champ de structure"
1125 // A struct corresponding to a TimeStamp protocol buffer.
1126 // The tag strings define the protocol buffer field numbers;
1127 // they follow the convention outlined by the reflect package.
1129 microsec uint64 `protobuf:"1"`
1130 serverIP6 uint64 `protobuf:"2"`
1134 <h3 id="Pointer_types">Pointer types</h3>
1137 A pointer type denotes the set of all pointers to <a href="#Variables">variables</a> of a given
1138 type, called the <i>base type</i> of the pointer.
1139 The value of an uninitialized pointer is <code>nil</code>.
1143 PointerType = "*" BaseType .
1152 <h3 id="Function_types">Function types</h3>
1155 A function type denotes the set of all functions with the same parameter
1156 and result types. The value of an uninitialized variable of function type
1157 is <code>nil</code>.
1161 FunctionType = "func" Signature .
1162 Signature = Parameters [ Result ] .
1163 Result = Parameters | Type .
1164 Parameters = "(" [ ParameterList [ "," ] ] ")" .
1165 ParameterList = ParameterDecl { "," ParameterDecl } .
1166 ParameterDecl = [ IdentifierList ] [ "..." ] Type .
1170 Within a list of parameters or results, the names (IdentifierList)
1171 must either all be present or all be absent. If present, each name
1172 stands for one item (parameter or result) of the specified type and
1173 all non-<a href="#Blank_identifier">blank</a> names in the signature
1174 must be <a href="#Uniqueness_of_identifiers">unique</a>.
1175 If absent, each type stands for one item of that type.
1176 Parameter and result
1177 lists are always parenthesized except that if there is exactly
1178 one unnamed result it may be written as an unparenthesized type.
1182 The final incoming parameter in a function signature may have
1183 a type prefixed with <code>...</code>.
1184 A function with such a parameter is called <i>variadic</i> and
1185 may be invoked with zero or more arguments for that parameter.
1191 func(a, _ int, z float32) bool
1192 func(a, b int, z float32) (bool)
1193 func(prefix string, values ...int)
1194 func(a, b int, z float64, opt ...interface{}) (success bool)
1195 func(int, int, float64) (float64, *[]int)
1196 func(n int) func(p *T)
1199 <h3 id="Interface_types">Interface types</h3>
1202 An interface type defines a <i>type set</i>.
1203 A variable of interface type can store a value of any type that is in the type
1204 set of the interface. Such a type is said to
1205 <a href="#Implementing_an_interface">implement the interface</a>.
1206 The value of an uninitialized variable of interface type is <code>nil</code>.
1210 InterfaceType = "interface" "{" { InterfaceElem ";" } "}" .
1211 InterfaceElem = MethodElem | TypeElem .
1212 MethodElem = MethodName Signature .
1213 MethodName = identifier .
1214 TypeElem = TypeTerm { "|" TypeTerm } .
1215 TypeTerm = Type | UnderlyingType .
1216 UnderlyingType = "~" Type .
1220 An interface type is specified by a list of <i>interface elements</i>.
1221 An interface element is either a <i>method</i> or a <i>type element</i>,
1222 where a type element is a union of one or more <i>type terms</i>.
1223 A type term is either a single type or a single underlying type.
1226 <h4 id="Basic_interfaces">Basic interfaces</h4>
1229 In its most basic form an interface specifies a (possibly empty) list of methods.
1230 The type set defined by such an interface is the set of types which implement all of
1231 those methods, and the corresponding <a href="#Method_sets">method set</a> consists
1232 exactly of the methods specified by the interface.
1233 Interfaces whose type sets can be defined entirely by a list of methods are called
1234 <i>basic interfaces.</i>
1238 // A simple File interface.
1240 Read([]byte) (int, error)
1241 Write([]byte) (int, error)
1247 The name of each explicitly specified method must be <a href="#Uniqueness_of_identifiers">unique</a>
1248 and not <a href="#Blank_identifier">blank</a>.
1254 String() string // illegal: String not unique
1255 _(x int) // illegal: method must have non-blank name
1260 More than one type may implement an interface.
1261 For instance, if two types <code>S1</code> and <code>S2</code>
1266 func (p T) Read(p []byte) (n int, err error)
1267 func (p T) Write(p []byte) (n int, err error)
1268 func (p T) Close() error
1272 (where <code>T</code> stands for either <code>S1</code> or <code>S2</code>)
1273 then the <code>File</code> interface is implemented by both <code>S1</code> and
1274 <code>S2</code>, regardless of what other methods
1275 <code>S1</code> and <code>S2</code> may have or share.
1279 Every type that is a member of the type set of an interface implements that interface.
1280 Any given type may implement several distinct interfaces.
1281 For instance, all types implement the <i>empty interface</i> which stands for the set
1282 of all (non-interface) types:
1290 For convenience, the predeclared type <code>any</code> is an alias for the empty interface.
1294 Similarly, consider this interface specification,
1295 which appears within a <a href="#Type_declarations">type declaration</a>
1296 to define an interface called <code>Locker</code>:
1300 type Locker interface {
1307 If <code>S1</code> and <code>S2</code> also implement
1311 func (p T) Lock() { … }
1312 func (p T) Unlock() { … }
1316 they implement the <code>Locker</code> interface as well
1317 as the <code>File</code> interface.
1320 <h4 id="Embedded_interfaces">Embedded interfaces</h4>
1323 In a slightly more general form
1324 an interface <code>T</code> may use a (possibly qualified) interface type
1325 name <code>E</code> as an interface element. This is called
1326 <i>embedding</i> interface <code>E</code> in <code>T</code>.
1327 The type set of <code>T</code> is the <i>intersection</i> of the type sets
1328 defined by <code>T</code>'s explicitly declared methods and the type sets
1329 of <code>T</code>’s embedded interfaces.
1330 In other words, the type set of <code>T</code> is the set of all types that implement all the
1331 explicitly declared methods of <code>T</code> and also all the methods of
1336 type Reader interface {
1337 Read(p []byte) (n int, err error)
1341 type Writer interface {
1342 Write(p []byte) (n int, err error)
1346 // ReadWriter's methods are Read, Write, and Close.
1347 type ReadWriter interface {
1348 Reader // includes methods of Reader in ReadWriter's method set
1349 Writer // includes methods of Writer in ReadWriter's method set
1354 When embedding interfaces, methods with the
1355 <a href="#Uniqueness_of_identifiers">same</a> names must
1356 have <a href="#Type_identity">identical</a> signatures.
1360 type ReadCloser interface {
1361 Reader // includes methods of Reader in ReadCloser's method set
1362 Close() // illegal: signatures of Reader.Close and Close are different
1366 <h4 id="General_interfaces">General interfaces</h4>
1369 In their most general form, an interface element may also be an arbitrary type term
1370 <code>T</code>, or a term of the form <code>~T</code> specifying the underlying type <code>T</code>,
1371 or a union of terms <code>t<sub>1</sub>|t<sub>2</sub>|…|t<sub>n</sub></code>.
1372 Together with method specifications, these elements enable the precise
1373 definition of an interface's type set as follows:
1377 <li>The type set of the empty interface is the set of all non-interface types.
1380 <li>The type set of a non-empty interface is the intersection of the type sets
1381 of its interface elements.
1384 <li>The type set of a method specification is the set of all non-interface types
1385 whose method sets include that method.
1388 <li>The type set of a non-interface type term is the set consisting
1392 <li>The type set of a term of the form <code>~T</code>
1393 is the set of all types whose underlying type is <code>T</code>.
1396 <li>The type set of a <i>union</i> of terms
1397 <code>t<sub>1</sub>|t<sub>2</sub>|…|t<sub>n</sub></code>
1398 is the union of the type sets of the terms.
1403 The quantification "the set of all non-interface types" refers not just to all (non-interface)
1404 types declared in the program at hand, but all possible types in all possible programs, and
1406 Similarly, given the set of all non-interface types that implement a particular method, the
1407 intersection of the method sets of those types will contain exactly that method, even if all
1408 types in the program at hand always pair that method with another method.
1412 By construction, an interface's type set never contains an interface type.
1416 // An interface representing only the type int.
1421 // An interface representing all types with underlying type int.
1426 // An interface representing all types with underlying type int that implement the String method.
1432 // An interface representing an empty type set: there is no type that is both an int and a string.
1440 In a term of the form <code>~T</code>, the underlying type of <code>T</code>
1441 must be itself, and <code>T</code> cannot be an interface.
1448 ~[]byte // the underlying type of []byte is itself
1449 ~MyInt // illegal: the underlying type of MyInt is not MyInt
1450 ~error // illegal: error is an interface
1455 Union elements denote unions of type sets:
1459 // The Float interface represents all floating-point types
1460 // (including any named types whose underlying types are
1461 // either float32 or float64).
1462 type Float interface {
1468 The type <code>T</code> in a term of the form <code>T</code> or <code>~T</code> cannot
1469 be a <a href="#Type_parameter_declarations">type parameter</a>, and the type sets of all
1470 non-interface terms must be pairwise disjoint (the pairwise intersection of the type sets must be empty).
1471 Given a type parameter <code>P</code>:
1476 P // illegal: P is a type parameter
1477 int | ~P // illegal: P is a type parameter
1478 ~int | MyInt // illegal: the type sets for ~int and MyInt are not disjoint (~int includes MyInt)
1479 float32 | Float // overlapping type sets but Float is an interface
1484 Implementation restriction:
1485 A union (with more than one term) cannot contain the
1486 <a href="#Predeclared_identifiers">predeclared identifier</a> <code>comparable</code>
1487 or interfaces that specify methods, or embed <code>comparable</code> or interfaces
1488 that specify methods.
1492 Interfaces that are not <a href="#Basic_interfaces">basic</a> may only be used as type
1493 constraints, or as elements of other interfaces used as constraints.
1494 They cannot be the types of values or variables, or components of other,
1495 non-interface types.
1499 var x Float // illegal: Float is not a basic interface
1501 var x interface{} = Float(nil) // illegal
1503 type Floatish struct {
1509 An interface type <code>T</code> may not embed any type element
1510 that is, contains, or embeds <code>T</code>, recursively.
1514 // illegal: Bad cannot embed itself
1515 type Bad interface {
1519 // illegal: Bad1 cannot embed itself using Bad2
1520 type Bad1 interface {
1523 type Bad2 interface {
1527 // illegal: Bad3 cannot embed a union containing Bad3
1528 type Bad3 interface {
1529 ~int | ~string | Bad3
1533 <h4 id="Implementing_an_interface">Implementing an interface</h4>
1536 A type <code>T</code> implements an interface <code>I</code> if
1541 <code>T</code> is not an interface and is an element of the type set of <code>I</code>; or
1544 <code>T</code> is an interface and the type set of <code>T</code> is a subset of the
1545 type set of <code>I</code>.
1550 A value of type <code>T</code> implements an interface if <code>T</code>
1551 implements the interface.
1554 <h3 id="Map_types">Map types</h3>
1557 A map is an unordered group of elements of one type, called the
1558 element type, indexed by a set of unique <i>keys</i> of another type,
1559 called the key type.
1560 The value of an uninitialized map is <code>nil</code>.
1564 MapType = "map" "[" KeyType "]" ElementType .
1569 The <a href="#Comparison_operators">comparison operators</a>
1570 <code>==</code> and <code>!=</code> must be fully defined
1571 for operands of the key type; thus the key type must not be a function, map, or
1573 If the key type is an interface type, these
1574 comparison operators must be defined for the dynamic key values;
1575 failure will cause a <a href="#Run_time_panics">run-time panic</a>.
1580 map[*T]struct{ x, y float64 }
1581 map[string]interface{}
1585 The number of map elements is called its length.
1586 For a map <code>m</code>, it can be discovered using the
1587 built-in function <a href="#Length_and_capacity"><code>len</code></a>
1588 and may change during execution. Elements may be added during execution
1589 using <a href="#Assignments">assignments</a> and retrieved with
1590 <a href="#Index_expressions">index expressions</a>; they may be removed with the
1591 <a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function.
1594 A new, empty map value is made using the built-in
1595 function <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1596 which takes the map type and an optional capacity hint as arguments:
1600 make(map[string]int)
1601 make(map[string]int, 100)
1605 The initial capacity does not bound its size:
1606 maps grow to accommodate the number of items
1607 stored in them, with the exception of <code>nil</code> maps.
1608 A <code>nil</code> map is equivalent to an empty map except that no elements
1611 <h3 id="Channel_types">Channel types</h3>
1614 A channel provides a mechanism for
1615 <a href="#Go_statements">concurrently executing functions</a>
1617 <a href="#Send_statements">sending</a> and
1618 <a href="#Receive_operator">receiving</a>
1619 values of a specified element type.
1620 The value of an uninitialized channel is <code>nil</code>.
1624 ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType .
1628 The optional <code><-</code> operator specifies the channel <i>direction</i>,
1629 <i>send</i> or <i>receive</i>. If a direction is given, the channel is <i>directional</i>,
1630 otherwise it is <i>bidirectional</i>.
1631 A channel may be constrained only to send or only to receive by
1632 <a href="#Assignments">assignment</a> or
1633 explicit <a href="#Conversions">conversion</a>.
1637 chan T // can be used to send and receive values of type T
1638 chan<- float64 // can only be used to send float64s
1639 <-chan int // can only be used to receive ints
1643 The <code><-</code> operator associates with the leftmost <code>chan</code>
1648 chan<- chan int // same as chan<- (chan int)
1649 chan<- <-chan int // same as chan<- (<-chan int)
1650 <-chan <-chan int // same as <-chan (<-chan int)
1651 chan (<-chan int)
1655 A new, initialized channel
1656 value can be made using the built-in function
1657 <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1658 which takes the channel type and an optional <i>capacity</i> as arguments:
1666 The capacity, in number of elements, sets the size of the buffer in the channel.
1667 If the capacity is zero or absent, the channel is unbuffered and communication
1668 succeeds only when both a sender and receiver are ready. Otherwise, the channel
1669 is buffered and communication succeeds without blocking if the buffer
1670 is not full (sends) or not empty (receives).
1671 A <code>nil</code> channel is never ready for communication.
1675 A channel may be closed with the built-in function
1676 <a href="#Close"><code>close</code></a>.
1677 The multi-valued assignment form of the
1678 <a href="#Receive_operator">receive operator</a>
1679 reports whether a received value was sent before
1680 the channel was closed.
1684 A single channel may be used in
1685 <a href="#Send_statements">send statements</a>,
1686 <a href="#Receive_operator">receive operations</a>,
1687 and calls to the built-in functions
1688 <a href="#Length_and_capacity"><code>cap</code></a> and
1689 <a href="#Length_and_capacity"><code>len</code></a>
1690 by any number of goroutines without further synchronization.
1691 Channels act as first-in-first-out queues.
1692 For example, if one goroutine sends values on a channel
1693 and a second goroutine receives them, the values are
1694 received in the order sent.
1697 <h2 id="Properties_of_types_and_values">Properties of types and values</h2>
1699 <h3 id="Underlying_types">Underlying types</h3>
1702 Each type <code>T</code> has an <i>underlying type</i>: If <code>T</code>
1703 is one of the predeclared boolean, numeric, or string types, or a type literal,
1704 the corresponding underlying type is <code>T</code> itself.
1705 Otherwise, <code>T</code>'s underlying type is the underlying type of the
1706 type to which <code>T</code> refers in its declaration.
1707 For a type parameter that is the underlying type of its
1708 <a href="#Type_constraints">type constraint</a>, which is always an interface.
1724 func f[P any](x P) { … }
1728 The underlying type of <code>string</code>, <code>A1</code>, <code>A2</code>, <code>B1</code>,
1729 and <code>B2</code> is <code>string</code>.
1730 The underlying type of <code>[]B1</code>, <code>B3</code>, and <code>B4</code> is <code>[]B1</code>.
1731 The underlying type of <code>P</code> is <code>interface{}</code>.
1734 <h3 id="Core_types">Core types</h3>
1737 Each non-interface type <code>T</code> has a <i>core type</i>, which is the same as the
1738 <a href="#Underlying_types">underlying type</a> of <code>T</code>.
1742 An interface <code>T</code> has a core type if one of the following
1743 conditions is satisfied:
1748 There is a single type <code>U</code> which is the <a href="#Underlying_types">underlying type</a>
1749 of all types in the <a href="#Interface_types">type set</a> of <code>T</code>; or
1752 the type set of <code>T</code> contains only <a href="#Channel_types">channel types</a>
1753 with identical element type <code>E</code>, and all directional channels have the same
1759 No other interfaces have a core type.
1763 The core type of an interface is, depending on the condition that is satisfied, either:
1768 the type <code>U</code>; or
1771 the type <code>chan E</code> if <code>T</code> contains only bidirectional
1772 channels, or the type <code>chan<- E</code> or <code><-chan E</code>
1773 depending on the direction of the directional channels present.
1778 By definition, a core type is never a <a href="#Type_definitions">defined type</a>,
1779 <a href="#Type_parameter_declarations">type parameter</a>, or
1780 <a href="#Interface_types">interface type</a>.
1784 Examples of interfaces with core types:
1788 type Celsius float32
1791 interface{ int } // int
1792 interface{ Celsius|Kelvin } // float32
1793 interface{ ~chan int } // chan int
1794 interface{ ~chan int|~chan<- int } // chan<- int
1795 interface{ ~[]*data; String() string } // []*data
1799 Examples of interfaces without core types:
1803 interface{} // no single underlying type
1804 interface{ Celsius|float64 } // no single underlying type
1805 interface{ chan int | chan<- string } // channels have different element types
1806 interface{ <-chan int | chan<- int } // directional channels have different directions
1809 <h3 id="Type_identity">Type identity</h3>
1812 Two types are either <i>identical</i> or <i>different</i>.
1816 A <a href="#Types">named type</a> is always different from any other type.
1817 Otherwise, two types are identical if their <a href="#Types">underlying</a> type literals are
1818 structurally equivalent; that is, they have the same literal structure and corresponding
1819 components have identical types. In detail:
1823 <li>Two array types are identical if they have identical element types and
1824 the same array length.</li>
1826 <li>Two slice types are identical if they have identical element types.</li>
1828 <li>Two struct types are identical if they have the same sequence of fields,
1829 and if corresponding fields have the same names, and identical types,
1831 <a href="#Exported_identifiers">Non-exported</a> field names from different
1832 packages are always different.</li>
1834 <li>Two pointer types are identical if they have identical base types.</li>
1836 <li>Two function types are identical if they have the same number of parameters
1837 and result values, corresponding parameter and result types are
1838 identical, and either both functions are variadic or neither is.
1839 Parameter and result names are not required to match.</li>
1841 <li>Two interface types are identical if they define the same type set.
1844 <li>Two map types are identical if they have identical key and element types.</li>
1846 <li>Two channel types are identical if they have identical element types and
1847 the same direction.</li>
1849 <li>Two <a href="#Instantiations">instantiated</a> types are identical if
1850 their defined types and all type arguments are identical.
1855 Given the declarations
1862 A2 = struct{ a, b int }
1864 A4 = func(A3, float64) *A0
1865 A5 = func(x int, _ float64) *[]string
1869 B2 struct{ a, b int }
1870 B3 struct{ a, c int }
1871 B4 func(int, float64) *B0
1872 B5 func(x int, y float64) *A1
1875 D0[P1, P2 any] struct{ x P1; y P2 }
1876 E0 = D0[int, string]
1881 these types are identical:
1885 A0, A1, and []string
1886 A2 and struct{ a, b int }
1888 A4, func(int, float64) *[]string, and A5
1891 D0[int, string] and E0
1893 struct{ a, b *B5 } and struct{ a, b *B5 }
1894 func(x int, y float64) *[]string, func(int, float64) (result *[]string), and A5
1898 <code>B0</code> and <code>B1</code> are different because they are new types
1899 created by distinct <a href="#Type_definitions">type definitions</a>;
1900 <code>func(int, float64) *B0</code> and <code>func(x int, y float64) *[]string</code>
1901 are different because <code>B0</code> is different from <code>[]string</code>;
1902 and <code>P1</code> and <code>P2</code> are different because they are different
1904 <code>D0[int, string]</code> and <code>struct{ x int; y string }</code> are
1905 different because the former is an <a href="#Instantiations">instantiated</a>
1906 defined type while the latter is a type literal
1907 (but they are still <a href="#Assignability">assignable</a>).
1910 <h3 id="Assignability">Assignability</h3>
1913 A value <code>x</code> of type <code>V</code> is <i>assignable</i> to a <a href="#Variables">variable</a> of type <code>T</code>
1914 ("<code>x</code> is assignable to <code>T</code>") if one of the following conditions applies:
1919 <code>V</code> and <code>T</code> are identical.
1922 <code>V</code> and <code>T</code> have identical
1923 <a href="#Underlying_types">underlying types</a>
1924 but are not type parameters and at least one of <code>V</code>
1925 or <code>T</code> is not a <a href="#Types">named type</a>.
1928 <code>V</code> and <code>T</code> are channel types with
1929 identical element types, <code>V</code> is a bidirectional channel,
1930 and at least one of <code>V</code> or <code>T</code> is not a <a href="#Types">named type</a>.
1933 <code>T</code> is an interface type, but not a type parameter, and
1934 <code>x</code> <a href="#Implementing_an_interface">implements</a> <code>T</code>.
1937 <code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code>
1938 is a pointer, function, slice, map, channel, or interface type,
1939 but not a type parameter.
1942 <code>x</code> is an untyped <a href="#Constants">constant</a>
1943 <a href="#Representability">representable</a>
1944 by a value of type <code>T</code>.
1949 Additionally, if <code>x</code>'s type <code>V</code> or <code>T</code> are type parameters, <code>x</code>
1950 is assignable to a variable of type <code>T</code> if one of the following conditions applies:
1955 <code>x</code> is the predeclared identifier <code>nil</code>, <code>T</code> is
1956 a type parameter, and <code>x</code> is assignable to each type in
1957 <code>T</code>'s type set.
1960 <code>V</code> is not a <a href="#Types">named type</a>, <code>T</code> is
1961 a type parameter, and <code>x</code> is assignable to each type in
1962 <code>T</code>'s type set.
1965 <code>V</code> is a type parameter and <code>T</code> is not a named type,
1966 and values of each type in <code>V</code>'s type set are assignable
1971 <h3 id="Representability">Representability</h3>
1974 A <a href="#Constants">constant</a> <code>x</code> is <i>representable</i>
1975 by a value of type <code>T</code>,
1976 where <code>T</code> is not a <a href="#Type_parameter_declarations">type parameter</a>,
1977 if one of the following conditions applies:
1982 <code>x</code> is in the set of values <a href="#Types">determined</a> by <code>T</code>.
1986 <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
1987 precision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEE
1988 negative zero further simplified to an unsigned zero. Note that constant values never result
1989 in an IEEE negative zero, NaN, or infinity.
1993 <code>T</code> is a complex type, and <code>x</code>'s
1994 <a href="#Complex_numbers">components</a> <code>real(x)</code> and <code>imag(x)</code>
1995 are representable by values of <code>T</code>'s component type (<code>float32</code> or
1996 <code>float64</code>).
2001 If <code>T</code> is a type parameter,
2002 <code>x</code> is representable by a value of type <code>T</code> if <code>x</code> is representable
2003 by a value of each type in <code>T</code>'s type set.
2007 x T x is representable by a value of T because
2009 'a' byte 97 is in the set of byte values
2010 97 rune rune is an alias for int32, and 97 is in the set of 32-bit integers
2011 "foo" string "foo" is in the set of string values
2012 1024 int16 1024 is in the set of 16-bit integers
2013 42.0 byte 42 is in the set of unsigned 8-bit integers
2014 1e10 uint64 10000000000 is in the set of unsigned 64-bit integers
2015 2.718281828459045 float32 2.718281828459045 rounds to 2.7182817 which is in the set of float32 values
2016 -1e-1000 float64 -1e-1000 rounds to IEEE -0.0 which is further simplified to 0.0
2017 0i int 0 is an integer value
2018 (42 + 0i) float32 42.0 (with zero imaginary part) is in the set of float32 values
2022 x T x is not representable by a value of T because
2024 0 bool 0 is not in the set of boolean values
2025 'a' string 'a' is a rune, it is not in the set of string values
2026 1024 byte 1024 is not in the set of unsigned 8-bit integers
2027 -1 uint16 -1 is not in the set of unsigned 16-bit integers
2028 1.1 int 1.1 is not an integer value
2029 42i float32 (0 + 42i) is not in the set of float32 values
2030 1e1000 float64 1e1000 overflows to IEEE +Inf after rounding
2033 <h3 id="Method_sets">Method sets</h3>
2036 The <i>method set</i> of a type determines the methods that can be
2037 <a href="#Calls">called</a> on an <a href="#Operands">operand</a> of that type.
2038 Every type has a (possibly empty) method set associated with it:
2042 <li>The method set of a <a href="#Type_definitions">defined type</a> <code>T</code> consists of all
2043 <a href="#Method_declarations">methods</a> declared with receiver type <code>T</code>.
2047 The method set of a pointer to a defined type <code>T</code>
2048 (where <code>T</code> is neither a pointer nor an interface)
2049 is the set of all methods declared with receiver <code>*T</code> or <code>T</code>.
2052 <li>The method set of an <a href="#Interface_types">interface type</a> is the intersection
2053 of the method sets of each type in the interface's <a href="#Interface_types">type set</a>
2054 (the resulting method set is usually just the set of declared methods in the interface).
2059 Further rules apply to structs (and pointer to structs) containing embedded fields,
2060 as described in the section on <a href="#Struct_types">struct types</a>.
2061 Any other type has an empty method set.
2065 In a method set, each method must have a
2066 <a href="#Uniqueness_of_identifiers">unique</a>
2067 non-<a href="#Blank_identifier">blank</a> <a href="#MethodName">method name</a>.
2070 <h2 id="Blocks">Blocks</h2>
2073 A <i>block</i> is a possibly empty sequence of declarations and statements
2074 within matching brace brackets.
2078 Block = "{" StatementList "}" .
2079 StatementList = { Statement ";" } .
2083 In addition to explicit blocks in the source code, there are implicit blocks:
2087 <li>The <i>universe block</i> encompasses all Go source text.</li>
2089 <li>Each <a href="#Packages">package</a> has a <i>package block</i> containing all
2090 Go source text for that package.</li>
2092 <li>Each file has a <i>file block</i> containing all Go source text
2095 <li>Each <a href="#If_statements">"if"</a>,
2096 <a href="#For_statements">"for"</a>, and
2097 <a href="#Switch_statements">"switch"</a>
2098 statement is considered to be in its own implicit block.</li>
2100 <li>Each clause in a <a href="#Switch_statements">"switch"</a>
2101 or <a href="#Select_statements">"select"</a> statement
2102 acts as an implicit block.</li>
2106 Blocks nest and influence <a href="#Declarations_and_scope">scoping</a>.
2110 <h2 id="Declarations_and_scope">Declarations and scope</h2>
2113 A <i>declaration</i> binds a non-<a href="#Blank_identifier">blank</a> identifier to a
2114 <a href="#Constant_declarations">constant</a>,
2115 <a href="#Type_declarations">type</a>,
2116 <a href="#Type_parameter_declarations">type parameter</a>,
2117 <a href="#Variable_declarations">variable</a>,
2118 <a href="#Function_declarations">function</a>,
2119 <a href="#Labeled_statements">label</a>, or
2120 <a href="#Import_declarations">package</a>.
2121 Every identifier in a program must be declared.
2122 No identifier may be declared twice in the same block, and
2123 no identifier may be declared in both the file and package block.
2127 The <a href="#Blank_identifier">blank identifier</a> may be used like any other identifier
2128 in a declaration, but it does not introduce a binding and thus is not declared.
2129 In the package block, the identifier <code>init</code> may only be used for
2130 <a href="#Package_initialization"><code>init</code> function</a> declarations,
2131 and like the blank identifier it does not introduce a new binding.
2135 Declaration = ConstDecl | TypeDecl | VarDecl .
2136 TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
2140 The <i>scope</i> of a declared identifier is the extent of source text in which
2141 the identifier denotes the specified constant, type, variable, function, label, or package.
2145 Go is lexically scoped using <a href="#Blocks">blocks</a>:
2149 <li>The scope of a <a href="#Predeclared_identifiers">predeclared identifier</a> is the universe block.</li>
2151 <li>The scope of an identifier denoting a constant, type, variable,
2152 or function (but not method) declared at top level (outside any
2153 function) is the package block.</li>
2155 <li>The scope of the package name of an imported package is the file block
2156 of the file containing the import declaration.</li>
2158 <li>The scope of an identifier denoting a method receiver, function parameter,
2159 or result variable is the function body.</li>
2161 <li>The scope of an identifier denoting a type parameter of a function
2162 or declared by a method receiver begins after the name of the function
2163 and ends at the end of the function body.</li>
2165 <li>The scope of an identifier denoting a type parameter of a type
2166 begins after the name of the type and ends at the end
2167 of the TypeSpec.</li>
2169 <li>The scope of a constant or variable identifier declared
2170 inside a function begins at the end of the ConstSpec or VarSpec
2171 (ShortVarDecl for short variable declarations)
2172 and ends at the end of the innermost containing block.</li>
2174 <li>The scope of a type identifier declared inside a function
2175 begins at the identifier in the TypeSpec
2176 and ends at the end of the innermost containing block.</li>
2180 An identifier declared in a block may be redeclared in an inner block.
2181 While the identifier of the inner declaration is in scope, it denotes
2182 the entity declared by the inner declaration.
2186 The <a href="#Package_clause">package clause</a> is not a declaration; the package name
2187 does not appear in any scope. Its purpose is to identify the files belonging
2188 to the same <a href="#Packages">package</a> and to specify the default package name for import
2193 <h3 id="Label_scopes">Label scopes</h3>
2196 Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are
2197 used in the <a href="#Break_statements">"break"</a>,
2198 <a href="#Continue_statements">"continue"</a>, and
2199 <a href="#Goto_statements">"goto"</a> statements.
2200 It is illegal to define a label that is never used.
2201 In contrast to other identifiers, labels are not block scoped and do
2202 not conflict with identifiers that are not labels. The scope of a label
2203 is the body of the function in which it is declared and excludes
2204 the body of any nested function.
2208 <h3 id="Blank_identifier">Blank identifier</h3>
2211 The <i>blank identifier</i> is represented by the underscore character <code>_</code>.
2212 It serves as an anonymous placeholder instead of a regular (non-blank)
2213 identifier and has special meaning in <a href="#Declarations_and_scope">declarations</a>,
2214 as an <a href="#Operands">operand</a>, and in <a href="#Assignments">assignments</a>.
2218 <h3 id="Predeclared_identifiers">Predeclared identifiers</h3>
2221 The following identifiers are implicitly declared in the
2222 <a href="#Blocks">universe block</a>:
2224 <pre class="grammar">
2226 any bool byte comparable
2227 complex64 complex128 error float32 float64
2228 int int8 int16 int32 int64 rune string
2229 uint uint8 uint16 uint32 uint64 uintptr
2238 append cap close complex copy delete imag len
2239 make new panic print println real recover
2242 <h3 id="Exported_identifiers">Exported identifiers</h3>
2245 An identifier may be <i>exported</i> to permit access to it from another package.
2246 An identifier is exported if both:
2249 <li>the first character of the identifier's name is a Unicode uppercase
2250 letter (Unicode character category Lu); and</li>
2251 <li>the identifier is declared in the <a href="#Blocks">package block</a>
2252 or it is a <a href="#Struct_types">field name</a> or
2253 <a href="#MethodName">method name</a>.</li>
2256 All other identifiers are not exported.
2259 <h3 id="Uniqueness_of_identifiers">Uniqueness of identifiers</h3>
2262 Given a set of identifiers, an identifier is called <i>unique</i> if it is
2263 <i>different</i> from every other in the set.
2264 Two identifiers are different if they are spelled differently, or if they
2265 appear in different <a href="#Packages">packages</a> and are not
2266 <a href="#Exported_identifiers">exported</a>. Otherwise, they are the same.
2269 <h3 id="Constant_declarations">Constant declarations</h3>
2272 A constant declaration binds a list of identifiers (the names of
2273 the constants) to the values of a list of <a href="#Constant_expressions">constant expressions</a>.
2274 The number of identifiers must be equal
2275 to the number of expressions, and the <i>n</i>th identifier on
2276 the left is bound to the value of the <i>n</i>th expression on the
2281 ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
2282 ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
2284 IdentifierList = identifier { "," identifier } .
2285 ExpressionList = Expression { "," Expression } .
2289 If the type is present, all constants take the type specified, and
2290 the expressions must be <a href="#Assignability">assignable</a> to that type,
2291 which must not be a type parameter.
2292 If the type is omitted, the constants take the
2293 individual types of the corresponding expressions.
2294 If the expression values are untyped <a href="#Constants">constants</a>,
2295 the declared constants remain untyped and the constant identifiers
2296 denote the constant values. For instance, if the expression is a
2297 floating-point literal, the constant identifier denotes a floating-point
2298 constant, even if the literal's fractional part is zero.
2302 const Pi float64 = 3.14159265358979323846
2303 const zero = 0.0 // untyped floating-point constant
2306 eof = -1 // untyped integer constant
2308 const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants
2309 const u, v float32 = 0, 3 // u = 0.0, v = 3.0
2313 Within a parenthesized <code>const</code> declaration list the
2314 expression list may be omitted from any but the first ConstSpec.
2315 Such an empty list is equivalent to the textual substitution of the
2316 first preceding non-empty expression list and its type if any.
2317 Omitting the list of expressions is therefore equivalent to
2318 repeating the previous list. The number of identifiers must be equal
2319 to the number of expressions in the previous list.
2320 Together with the <a href="#Iota"><code>iota</code> constant generator</a>
2321 this mechanism permits light-weight declaration of sequential values:
2333 numberOfDays // this constant is not exported
2338 <h3 id="Iota">Iota</h3>
2341 Within a <a href="#Constant_declarations">constant declaration</a>, the predeclared identifier
2342 <code>iota</code> represents successive untyped integer <a href="#Constants">
2343 constants</a>. Its value is the index of the respective <a href="#ConstSpec">ConstSpec</a>
2344 in that constant declaration, starting at zero.
2345 It can be used to construct a set of related constants:
2350 c0 = iota // c0 == 0
2351 c1 = iota // c1 == 1
2352 c2 = iota // c2 == 2
2356 a = 1 << iota // a == 1 (iota == 0)
2357 b = 1 << iota // b == 2 (iota == 1)
2358 c = 3 // c == 3 (iota == 2, unused)
2359 d = 1 << iota // d == 8 (iota == 3)
2363 u = iota * 42 // u == 0 (untyped integer constant)
2364 v float64 = iota * 42 // v == 42.0 (float64 constant)
2365 w = iota * 42 // w == 84 (untyped integer constant)
2368 const x = iota // x == 0
2369 const y = iota // y == 0
2373 By definition, multiple uses of <code>iota</code> in the same ConstSpec all have the same value:
2378 bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 (iota == 0)
2379 bit1, mask1 // bit1 == 2, mask1 == 1 (iota == 1)
2380 _, _ // (iota == 2, unused)
2381 bit3, mask3 // bit3 == 8, mask3 == 7 (iota == 3)
2386 This last example exploits the <a href="#Constant_declarations">implicit repetition</a>
2387 of the last non-empty expression list.
2391 <h3 id="Type_declarations">Type declarations</h3>
2394 A type declaration binds an identifier, the <i>type name</i>, to a <a href="#Types">type</a>.
2395 Type declarations come in two forms: alias declarations and type definitions.
2399 TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
2400 TypeSpec = AliasDecl | TypeDef .
2403 <h4 id="Alias_declarations">Alias declarations</h4>
2406 An alias declaration binds an identifier to the given type.
2410 AliasDecl = identifier "=" Type .
2414 Within the <a href="#Declarations_and_scope">scope</a> of
2415 the identifier, it serves as an <i>alias</i> for the type.
2420 nodeList = []*Node // nodeList and []*Node are identical types
2421 Polar = polar // Polar and polar denote identical types
2426 <h4 id="Type_definitions">Type definitions</h4>
2429 A type definition creates a new, distinct type with the same
2430 <a href="#Types">underlying type</a> and operations as the given type
2431 and binds an identifier, the <i>type name</i>, to it.
2435 TypeDef = identifier [ TypeParameters ] Type .
2439 The new type is called a <i>defined type</i>.
2440 It is <a href="#Type_identity">different</a> from any other type,
2441 including the type it is created from.
2446 Point struct{ x, y float64 } // Point and struct{ x, y float64 } are different types
2447 polar Point // polar and Point denote different types
2450 type TreeNode struct {
2451 left, right *TreeNode
2455 type Block interface {
2457 Encrypt(src, dst []byte)
2458 Decrypt(src, dst []byte)
2463 A defined type may have <a href="#Method_declarations">methods</a> associated with it.
2464 It does not inherit any methods bound to the given type,
2465 but the <a href="#Method_sets">method set</a>
2466 of an interface type or of elements of a composite type remains unchanged:
2470 // A Mutex is a data type with two methods, Lock and Unlock.
2471 type Mutex struct { /* Mutex fields */ }
2472 func (m *Mutex) Lock() { /* Lock implementation */ }
2473 func (m *Mutex) Unlock() { /* Unlock implementation */ }
2475 // NewMutex has the same composition as Mutex but its method set is empty.
2478 // The method set of PtrMutex's underlying type *Mutex remains unchanged,
2479 // but the method set of PtrMutex is empty.
2480 type PtrMutex *Mutex
2482 // The method set of *PrintableMutex contains the methods
2483 // Lock and Unlock bound to its embedded field Mutex.
2484 type PrintableMutex struct {
2488 // MyBlock is an interface type that has the same method set as Block.
2493 Type definitions may be used to define different boolean, numeric,
2494 or string types and associate methods with them:
2501 EST TimeZone = -(5 + iota)
2507 func (tz TimeZone) String() string {
2508 return fmt.Sprintf("GMT%+dh", tz)
2513 If the type definition specifies <a href="#Type_parameter_declarations">type parameters</a>,
2514 the type name denotes a <i>generic type</i>.
2515 Generic types must be <a href="#Instantiations">instantiated</a> when they
2520 type List[T any] struct {
2527 In a type definition the given type cannot be a type parameter.
2531 type T[P any] P // illegal: P is a type parameter
2534 type L T // illegal: T is a type parameter declared by the enclosing function
2539 A generic type may also have <a href="#Method_declarations">methods</a> associated with it.
2540 In this case, the method receivers must declare the same number of type parameters as
2541 present in the generic type definition.
2545 // The method Len returns the number of elements in the linked list l.
2546 func (l *List[T]) Len() int { … }
2549 <h3 id="Type_parameter_declarations">Type parameter declarations</h3>
2552 A type parameter list declares the <i>type parameters</i> of a generic function or type declaration.
2553 The type parameter list looks like an ordinary <a href="#Function_types">function parameter list</a>
2554 except that the type parameter names must all be present and the list is enclosed
2555 in square brackets rather than parentheses.
2559 TypeParameters = "[" TypeParamList [ "," ] "]" .
2560 TypeParamList = TypeParamDecl { "," TypeParamDecl } .
2561 TypeParamDecl = IdentifierList TypeConstraint .
2565 All non-blank names in the list must be unique.
2566 Each name declares a type parameter, which is a new and different <a href="#Types">named type</a>
2567 that acts as a place holder for an (as of yet) unknown type in the declaration.
2568 The type parameter is replaced with a <i>type argument</i> upon
2569 <a href="#Instantiations">instantiation</a> of the generic function or type.
2574 [S interface{ ~[]byte|string }]
2581 Just as each ordinary function parameter has a parameter type, each type parameter
2582 has a corresponding (meta-)type which is called its
2583 <a href="#Type_constraints"><i>type constraint</i></a>.
2587 A parsing ambiguity arises when the type parameter list for a generic type
2588 declares a single type parameter <code>P</code> with a constraint <code>C</code>
2589 such that the text <code>P C</code> forms a valid expression:
2600 In these rare cases, the type parameter list is indistinguishable from an
2601 expression and the type declaration is parsed as an array type declaration.
2602 To resolve the ambiguity, embed the constraint in an
2603 <a href="#Interface_types">interface</a> or use a trailing comma:
2607 type T[P interface{*C}] …
2612 Type parameters may also be declared by the receiver specification
2613 of a <a href="#Method_declarations">method declaration</a> associated
2614 with a generic type.
2618 This section needs to explain if and what kind of cycles are permitted
2619 using type parameters in a type parameter list.
2622 <h4 id="Type_constraints">Type constraints</h4>
2625 A type constraint is an <a href="#Interface_types">interface</a> that defines the
2626 set of permissible type arguments for the respective type parameter and controls the
2627 operations supported by values of that type parameter.
2631 TypeConstraint = TypeElem .
2635 If the constraint is an interface literal of the form <code>interface{E}</code> where
2636 <code>E</code> is an embedded type element (not a method), in a type parameter list
2637 the enclosing <code>interface{ … }</code> may be omitted for convenience:
2641 [T []P] // = [T interface{[]P}]
2642 [T ~int] // = [T interface{~int}]
2643 [T int|string] // = [T interface{int|string}]
2644 type Constraint ~int // illegal: ~int is not inside a type parameter list
2648 We should be able to simplify the rules for comparable or delegate some of them
2649 elsewhere since we have a section that clearly defines how interfaces implement
2650 other interfaces based on their type sets. But this should get us going for now.
2654 The <a href="#Predeclared_identifiers">predeclared</a>
2655 <a href="#Interface_types">interface type</a> <code>comparable</code>
2656 denotes the set of all non-interface types that are
2657 <a href="#Comparison_operators">comparable</a>. Specifically,
2658 a type <code>T</code> implements <code>comparable</code> if:
2663 <code>T</code> is not an interface type and <code>T</code> supports the operations
2664 <code>==</code> and <code>!=</code>; or
2667 <code>T</code> is an interface type and each type in <code>T</code>'s
2668 <a href="#Interface_types">type set</a> implements <code>comparable</code>.
2673 Even though interfaces that are not type parameters can be
2674 <a href="#Comparison_operators">compared</a>
2675 (possibly causing a run-time panic) they do not implement
2676 <code>comparable</code>.
2680 int // implements comparable
2681 []byte // does not implement comparable (slices cannot be compared)
2682 interface{} // does not implement comparable (see above)
2683 interface{ ~int | ~string } // type parameter only: implements comparable
2684 interface{ comparable } // type parameter only: implements comparable
2685 interface{ ~int | ~[]byte } // type parameter only: does not implement comparable (not all types in the type set are comparable)
2689 The <code>comparable</code> interface and interfaces that (directly or indirectly) embed
2690 <code>comparable</code> may only be used as type constraints. They cannot be the types of
2691 values or variables, or components of other, non-interface types.
2694 <h3 id="Variable_declarations">Variable declarations</h3>
2697 A variable declaration creates one or more <a href="#Variables">variables</a>,
2698 binds corresponding identifiers to them, and gives each a type and an initial value.
2702 VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
2703 VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
2710 var x, y float32 = -1, -2
2713 u, v, s = 2.0, 3.0, "bar"
2715 var re, im = complexSqrt(-1)
2716 var _, found = entries[name] // map lookup; only interested in "found"
2720 If a list of expressions is given, the variables are initialized
2721 with the expressions following the rules for <a href="#Assignments">assignments</a>.
2722 Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>.
2726 If a type is present, each variable is given that type.
2727 Otherwise, each variable is given the type of the corresponding
2728 initialization value in the assignment.
2729 If that value is an untyped constant, it is first implicitly
2730 <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>;
2731 if it is an untyped boolean value, it is first implicitly converted to type <code>bool</code>.
2732 The predeclared value <code>nil</code> cannot be used to initialize a variable
2733 with no explicit type.
2737 var d = math.Sin(0.5) // d is float64
2738 var i = 42 // i is int
2739 var t, ok = x.(T) // t is T, ok is bool
2740 var n = nil // illegal
2744 Implementation restriction: A compiler may make it illegal to declare a variable
2745 inside a <a href="#Function_declarations">function body</a> if the variable is
2749 <h3 id="Short_variable_declarations">Short variable declarations</h3>
2752 A <i>short variable declaration</i> uses the syntax:
2756 ShortVarDecl = IdentifierList ":=" ExpressionList .
2760 It is shorthand for a regular <a href="#Variable_declarations">variable declaration</a>
2761 with initializer expressions but no types:
2764 <pre class="grammar">
2765 "var" IdentifierList "=" ExpressionList .
2770 f := func() int { return 7 }
2771 ch := make(chan int)
2772 r, w, _ := os.Pipe() // os.Pipe() returns a connected pair of Files and an error, if any
2773 _, y, _ := coord(p) // coord() returns three values; only interested in y coordinate
2777 Unlike regular variable declarations, a short variable declaration may <i>redeclare</i>
2778 variables provided they were originally declared earlier in the same block
2779 (or the parameter lists if the block is the function body) with the same type,
2780 and at least one of the non-<a href="#Blank_identifier">blank</a> variables is new.
2781 As a consequence, redeclaration can only appear in a multi-variable short declaration.
2782 Redeclaration does not introduce a new variable; it just assigns a new value to the original.
2783 The non-blank variable names on the left side of <code>:=</code>
2784 must be <a href="#Uniqueness_of_identifiers">unique</a>.
2788 field1, offset := nextField(str, 0)
2789 field2, offset := nextField(str, offset) // redeclares offset
2790 x, y, x := 1, 2, 3 // illegal: x repeated on left side of :=
2794 Short variable declarations may appear only inside functions.
2795 In some contexts such as the initializers for
2796 <a href="#If_statements">"if"</a>,
2797 <a href="#For_statements">"for"</a>, or
2798 <a href="#Switch_statements">"switch"</a> statements,
2799 they can be used to declare local temporary variables.
2802 <h3 id="Function_declarations">Function declarations</h3>
2805 Given the importance of functions, this section has always
2806 been woefully underdeveloped. Would be nice to expand this
2811 A function declaration binds an identifier, the <i>function name</i>,
2816 FunctionDecl = "func" FunctionName [ TypeParameters ] Signature [ FunctionBody ] .
2817 FunctionName = identifier .
2818 FunctionBody = Block .
2822 If the function's <a href="#Function_types">signature</a> declares
2823 result parameters, the function body's statement list must end in
2824 a <a href="#Terminating_statements">terminating statement</a>.
2828 func IndexRune(s string, r rune) int {
2829 for i, c := range s {
2834 // invalid: missing return statement
2839 If the function declaration specifies <a href="#Type_parameter_declarations">type parameters</a>,
2840 the function name denotes a <i>generic function</i>.
2841 A generic function must be <a href="#Instantiations">instantiated</a> before it can be
2842 called or used as a value.
2846 func min[T ~int|~float64](x, y T) T {
2855 A function declaration without type parameters may omit the body.
2856 Such a declaration provides the signature for a function implemented outside Go,
2857 such as an assembly routine.
2861 func flushICache(begin, end uintptr) // implemented externally
2864 <h3 id="Method_declarations">Method declarations</h3>
2867 A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>.
2868 A method declaration binds an identifier, the <i>method name</i>, to a method,
2869 and associates the method with the receiver's <i>base type</i>.
2873 MethodDecl = "func" Receiver MethodName Signature [ FunctionBody ] .
2874 Receiver = Parameters .
2878 The receiver is specified via an extra parameter section preceding the method
2879 name. That parameter section must declare a single non-variadic parameter, the receiver.
2880 Its type must be a <a href="#Type_definitions">defined</a> type <code>T</code> or a
2881 pointer to a defined type <code>T</code>, possibly followed by a list of type parameter
2882 names <code>[P1, P2, …]</code> enclosed in square brackets.
2883 <code>T</code> is called the receiver <i>base type</i>. A receiver base type cannot be
2884 a pointer or interface type and it must be defined in the same package as the method.
2885 The method is said to be <i>bound</i> to its receiver base type and the method name
2886 is visible only within <a href="#Selectors">selectors</a> for type <code>T</code>
2891 A non-<a href="#Blank_identifier">blank</a> receiver identifier must be
2892 <a href="#Uniqueness_of_identifiers">unique</a> in the method signature.
2893 If the receiver's value is not referenced inside the body of the method,
2894 its identifier may be omitted in the declaration. The same applies in
2895 general to parameters of functions and methods.
2899 For a base type, the non-blank names of methods bound to it must be unique.
2900 If the base type is a <a href="#Struct_types">struct type</a>,
2901 the non-blank method and field names must be distinct.
2905 Given defined type <code>Point</code> the declarations
2909 func (p *Point) Length() float64 {
2910 return math.Sqrt(p.x * p.x + p.y * p.y)
2913 func (p *Point) Scale(factor float64) {
2920 bind the methods <code>Length</code> and <code>Scale</code>,
2921 with receiver type <code>*Point</code>,
2922 to the base type <code>Point</code>.
2926 If the receiver base type is a <a href="#Type_declarations">generic type</a>, the
2927 receiver specification must declare corresponding type parameters for the method
2928 to use. This makes the receiver type parameters available to the method.
2929 Syntactically, this type parameter declaration looks like an
2930 <a href="#Instantiations">instantiation</a> of the receiver base type: the type
2931 arguments must be identifiers denoting the type parameters being declared, one
2932 for each type parameter of the receiver base type.
2933 The type parameter names do not need to match their corresponding parameter names in the
2934 receiver base type definition, and all non-blank parameter names must be unique in the
2935 receiver parameter section and the method signature.
2936 The receiver type parameter constraints are implied by the receiver base type definition:
2937 corresponding type parameters have corresponding constraints.
2941 type Pair[A, B any] struct {
2946 func (p Pair[A, B]) Swap() Pair[B, A] { … } // receiver declares A, B
2947 func (p Pair[First, _]) First() First { … } // receiver declares First, corresponds to A in Pair
2950 <h2 id="Expressions">Expressions</h2>
2953 An expression specifies the computation of a value by applying
2954 operators and functions to operands.
2957 <h3 id="Operands">Operands</h3>
2960 Operands denote the elementary values in an expression. An operand may be a
2961 literal, a (possibly <a href="#Qualified_identifiers">qualified</a>)
2962 non-<a href="#Blank_identifier">blank</a> identifier denoting a
2963 <a href="#Constant_declarations">constant</a>,
2964 <a href="#Variable_declarations">variable</a>, or
2965 <a href="#Function_declarations">function</a>,
2966 or a parenthesized expression.
2970 Operand = Literal | OperandName [ TypeArgs ] | "(" Expression ")" .
2971 Literal = BasicLit | CompositeLit | FunctionLit .
2972 BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
2973 OperandName = identifier | QualifiedIdent .
2977 An operand name denoting a <a href="#Function_declarations">generic function</a>
2978 may be followed by a list of <a href="#Instantiations">type arguments</a>; the
2979 resulting operand is an <a href="#Instantiations">instantiated</a> function.
2983 The <a href="#Blank_identifier">blank identifier</a> may appear as an
2984 operand only on the left-hand side of an <a href="#Assignments">assignment</a>.
2988 Implementation restriction: A compiler need not report an error if an operand's
2989 type is a <a href="#Type_parameter_declarations">type parameter</a> with an empty
2990 <a href="#Interface_types">type set</a>. Functions with such type parameters
2991 cannot be <a href="#Instantiations">instantiated</a>; any attempt will lead
2992 to an error at the instantiation site.
2995 <h3 id="Qualified_identifiers">Qualified identifiers</h3>
2998 A <i>qualified identifier</i> is an identifier qualified with a package name prefix.
2999 Both the package name and the identifier must not be
3000 <a href="#Blank_identifier">blank</a>.
3004 QualifiedIdent = PackageName "." identifier .
3008 A qualified identifier accesses an identifier in a different package, which
3009 must be <a href="#Import_declarations">imported</a>.
3010 The identifier must be <a href="#Exported_identifiers">exported</a> and
3011 declared in the <a href="#Blocks">package block</a> of that package.
3015 math.Sin // denotes the Sin function in package math
3018 <h3 id="Composite_literals">Composite literals</h3>
3021 Composite literals construct new composite values each time they are evaluated.
3022 They consist of the type of the literal followed by a brace-bound list of elements.
3023 Each element may optionally be preceded by a corresponding key.
3027 CompositeLit = LiteralType LiteralValue .
3028 LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
3029 SliceType | MapType | TypeName .
3030 LiteralValue = "{" [ ElementList [ "," ] ] "}" .
3031 ElementList = KeyedElement { "," KeyedElement } .
3032 KeyedElement = [ Key ":" ] Element .
3033 Key = FieldName | Expression | LiteralValue .
3034 FieldName = identifier .
3035 Element = Expression | LiteralValue .
3039 The LiteralType's <a href="#Core_types">core type</a> <code>T</code>
3040 must be a struct, array, slice, or map type
3041 (the grammar enforces this constraint except when the type is given
3043 The types of the elements and keys must be <a href="#Assignability">assignable</a>
3044 to the respective field, element, and key types of type <code>T</code>;
3045 there is no additional conversion.
3046 The key is interpreted as a field name for struct literals,
3047 an index for array and slice literals, and a key for map literals.
3048 For map literals, all elements must have a key. It is an error
3049 to specify multiple elements with the same field name or
3050 constant key value. For non-constant map keys, see the section on
3051 <a href="#Order_of_evaluation">evaluation order</a>.
3055 For struct literals the following rules apply:
3058 <li>A key must be a field name declared in the struct type.
3060 <li>An element list that does not contain any keys must
3061 list an element for each struct field in the
3062 order in which the fields are declared.
3064 <li>If any element has a key, every element must have a key.
3066 <li>An element list that contains keys does not need to
3067 have an element for each struct field. Omitted fields
3068 get the zero value for that field.
3070 <li>A literal may omit the element list; such a literal evaluates
3071 to the zero value for its type.
3073 <li>It is an error to specify an element for a non-exported
3074 field of a struct belonging to a different package.
3079 Given the declarations
3082 type Point3D struct { x, y, z float64 }
3083 type Line struct { p, q Point3D }
3091 origin := Point3D{} // zero value for Point3D
3092 line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x
3096 For array and slice literals the following rules apply:
3099 <li>Each element has an associated integer index marking
3100 its position in the array.
3102 <li>An element with a key uses the key as its index. The
3103 key must be a non-negative constant
3104 <a href="#Representability">representable</a> by
3105 a value of type <code>int</code>; and if it is typed
3106 it must be of <a href="#Numeric_types">integer type</a>.
3108 <li>An element without a key uses the previous element's index plus one.
3109 If the first element has no key, its index is zero.
3114 <a href="#Address_operators">Taking the address</a> of a composite literal
3115 generates a pointer to a unique <a href="#Variables">variable</a> initialized
3116 with the literal's value.
3120 var pointer *Point3D = &Point3D{y: 1000}
3124 Note that the <a href="#The_zero_value">zero value</a> for a slice or map
3125 type is not the same as an initialized but empty value of the same type.
3126 Consequently, taking the address of an empty slice or map composite literal
3127 does not have the same effect as allocating a new slice or map value with
3128 <a href="#Allocation">new</a>.
3132 p1 := &[]int{} // p1 points to an initialized, empty slice with value []int{} and length 0
3133 p2 := new([]int) // p2 points to an uninitialized slice with value nil and length 0
3137 The length of an array literal is the length specified in the literal type.
3138 If fewer elements than the length are provided in the literal, the missing
3139 elements are set to the zero value for the array element type.
3140 It is an error to provide elements with index values outside the index range
3141 of the array. The notation <code>...</code> specifies an array length equal
3142 to the maximum element index plus one.
3146 buffer := [10]string{} // len(buffer) == 10
3147 intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6
3148 days := [...]string{"Sat", "Sun"} // len(days) == 2
3152 A slice literal describes the entire underlying array literal.
3153 Thus the length and capacity of a slice literal are the maximum
3154 element index plus one. A slice literal has the form
3162 and is shorthand for a slice operation applied to an array:
3166 tmp := [n]T{x1, x2, … xn}
3171 Within a composite literal of array, slice, or map type <code>T</code>,
3172 elements or map keys that are themselves composite literals may elide the respective
3173 literal type if it is identical to the element or key type of <code>T</code>.
3174 Similarly, elements or keys that are addresses of composite literals may elide
3175 the <code>&T</code> when the element or key type is <code>*T</code>.
3179 [...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}}
3180 [][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}}
3181 [][]Point{{{0, 1}, {1, 2}}} // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}}
3182 map[string]Point{"orig": {0, 0}} // same as map[string]Point{"orig": Point{0, 0}}
3183 map[Point]string{{0, 0}: "orig"} // same as map[Point]string{Point{0, 0}: "orig"}
3186 [2]*Point{{1.5, -3.5}, {}} // same as [2]*Point{&Point{1.5, -3.5}, &Point{}}
3187 [2]PPoint{{1.5, -3.5}, {}} // same as [2]PPoint{PPoint(&Point{1.5, -3.5}), PPoint(&Point{})}
3191 A parsing ambiguity arises when a composite literal using the
3192 TypeName form of the LiteralType appears as an operand between the
3193 <a href="#Keywords">keyword</a> and the opening brace of the block
3194 of an "if", "for", or "switch" statement, and the composite literal
3195 is not enclosed in parentheses, square brackets, or curly braces.
3196 In this rare case, the opening brace of the literal is erroneously parsed
3197 as the one introducing the block of statements. To resolve the ambiguity,
3198 the composite literal must appear within parentheses.
3202 if x == (T{a,b,c}[i]) { … }
3203 if (x == T{a,b,c}[i]) { … }
3207 Examples of valid array, slice, and map literals:
3211 // list of prime numbers
3212 primes := []int{2, 3, 5, 7, 9, 2147483647}
3214 // vowels[ch] is true if ch is a vowel
3215 vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}
3217 // the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1}
3218 filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1}
3220 // frequencies in Hz for equal-tempered scale (A4 = 440Hz)
3221 noteFrequency := map[string]float32{
3222 "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83,
3223 "G0": 24.50, "A0": 27.50, "B0": 30.87,
3228 <h3 id="Function_literals">Function literals</h3>
3231 A function literal represents an anonymous <a href="#Function_declarations">function</a>.
3232 Function literals cannot declare type parameters.
3236 FunctionLit = "func" Signature FunctionBody .
3240 func(a, b int, z float64) bool { return a*b < int(z) }
3244 A function literal can be assigned to a variable or invoked directly.
3248 f := func(x, y int) int { return x + y }
3249 func(ch chan int) { ch <- ACK }(replyChan)
3253 Function literals are <i>closures</i>: they may refer to variables
3254 defined in a surrounding function. Those variables are then shared between
3255 the surrounding function and the function literal, and they survive as long
3256 as they are accessible.
3260 <h3 id="Primary_expressions">Primary expressions</h3>
3263 Primary expressions are the operands for unary and binary expressions.
3271 PrimaryExpr Selector |
3274 PrimaryExpr TypeAssertion |
3275 PrimaryExpr Arguments .
3277 Selector = "." identifier .
3278 Index = "[" Expression "]" .
3279 Slice = "[" [ Expression ] ":" [ Expression ] "]" |
3280 "[" [ Expression ] ":" Expression ":" Expression "]" .
3281 TypeAssertion = "." "(" Type ")" .
3282 Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
3299 <h3 id="Selectors">Selectors</h3>
3302 For a <a href="#Primary_expressions">primary expression</a> <code>x</code>
3303 that is not a <a href="#Package_clause">package name</a>, the
3304 <i>selector expression</i>
3312 denotes the field or method <code>f</code> of the value <code>x</code>
3313 (or sometimes <code>*x</code>; see below).
3314 The identifier <code>f</code> is called the (field or method) <i>selector</i>;
3315 it must not be the <a href="#Blank_identifier">blank identifier</a>.
3316 The type of the selector expression is the type of <code>f</code>.
3317 If <code>x</code> is a package name, see the section on
3318 <a href="#Qualified_identifiers">qualified identifiers</a>.
3322 A selector <code>f</code> may denote a field or method <code>f</code> of
3323 a type <code>T</code>, or it may refer
3324 to a field or method <code>f</code> of a nested
3325 <a href="#Struct_types">embedded field</a> of <code>T</code>.
3326 The number of embedded fields traversed
3327 to reach <code>f</code> is called its <i>depth</i> in <code>T</code>.
3328 The depth of a field or method <code>f</code>
3329 declared in <code>T</code> is zero.
3330 The depth of a field or method <code>f</code> declared in
3331 an embedded field <code>A</code> in <code>T</code> is the
3332 depth of <code>f</code> in <code>A</code> plus one.
3336 The following rules apply to selectors:
3341 For a value <code>x</code> of type <code>T</code> or <code>*T</code>
3342 where <code>T</code> is not a pointer or interface type,
3343 <code>x.f</code> denotes the field or method at the shallowest depth
3344 in <code>T</code> where there is such an <code>f</code>.
3345 If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a>
3346 with shallowest depth, the selector expression is illegal.
3350 For a value <code>x</code> of type <code>I</code> where <code>I</code>
3351 is an interface type, <code>x.f</code> denotes the actual method with name
3352 <code>f</code> of the dynamic value of <code>x</code>.
3353 If there is no method with name <code>f</code> in the
3354 <a href="#Method_sets">method set</a> of <code>I</code>, the selector
3355 expression is illegal.
3359 As an exception, if the type of <code>x</code> is a <a href="#Type_definitions">defined</a>
3360 pointer type and <code>(*x).f</code> is a valid selector expression denoting a field
3361 (but not a method), <code>x.f</code> is shorthand for <code>(*x).f</code>.
3365 In all other cases, <code>x.f</code> is illegal.
3369 If <code>x</code> is of pointer type and has the value
3370 <code>nil</code> and <code>x.f</code> denotes a struct field,
3371 assigning to or evaluating <code>x.f</code>
3372 causes a <a href="#Run_time_panics">run-time panic</a>.
3376 If <code>x</code> is of interface type and has the value
3377 <code>nil</code>, <a href="#Calls">calling</a> or
3378 <a href="#Method_values">evaluating</a> the method <code>x.f</code>
3379 causes a <a href="#Run_time_panics">run-time panic</a>.
3384 For example, given the declarations:
3410 var t T2 // with t.T0 != nil
3411 var p *T2 // with p != nil and (*p).T0 != nil
3428 q.x // (*(*q).T0).x (*q).x is a valid field selector
3430 p.M0() // ((*p).T0).M0() M0 expects *T0 receiver
3431 p.M1() // ((*p).T1).M1() M1 expects T1 receiver
3432 p.M2() // p.M2() M2 expects *T2 receiver
3433 t.M2() // (&t).M2() M2 expects *T2 receiver, see section on Calls
3437 but the following is invalid:
3441 q.M0() // (*q).M0 is valid but not a field selector
3445 <h3 id="Method_expressions">Method expressions</h3>
3448 If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
3449 <code>T.M</code> is a function that is callable as a regular function
3450 with the same arguments as <code>M</code> prefixed by an additional
3451 argument that is the receiver of the method.
3455 MethodExpr = ReceiverType "." MethodName .
3456 ReceiverType = Type .
3460 Consider a struct type <code>T</code> with two methods,
3461 <code>Mv</code>, whose receiver is of type <code>T</code>, and
3462 <code>Mp</code>, whose receiver is of type <code>*T</code>.
3469 func (tv T) Mv(a int) int { return 0 } // value receiver
3470 func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
3484 yields a function equivalent to <code>Mv</code> but
3485 with an explicit receiver as its first argument; it has signature
3489 func(tv T, a int) int
3493 That function may be called normally with an explicit receiver, so
3494 these five invocations are equivalent:
3501 f1 := T.Mv; f1(t, 7)
3502 f2 := (T).Mv; f2(t, 7)
3506 Similarly, the expression
3514 yields a function value representing <code>Mp</code> with signature
3518 func(tp *T, f float32) float32
3522 For a method with a value receiver, one can derive a function
3523 with an explicit pointer receiver, so
3531 yields a function value representing <code>Mv</code> with signature
3535 func(tv *T, a int) int
3539 Such a function indirects through the receiver to create a value
3540 to pass as the receiver to the underlying method;
3541 the method does not overwrite the value whose address is passed in
3546 The final case, a value-receiver function for a pointer-receiver method,
3547 is illegal because pointer-receiver methods are not in the method set
3552 Function values derived from methods are called with function call syntax;
3553 the receiver is provided as the first argument to the call.
3554 That is, given <code>f := T.Mv</code>, <code>f</code> is invoked
3555 as <code>f(t, 7)</code> not <code>t.f(7)</code>.
3556 To construct a function that binds the receiver, use a
3557 <a href="#Function_literals">function literal</a> or
3558 <a href="#Method_values">method value</a>.
3562 It is legal to derive a function value from a method of an interface type.
3563 The resulting function takes an explicit receiver of that interface type.
3566 <h3 id="Method_values">Method values</h3>
3569 If the expression <code>x</code> has static type <code>T</code> and
3570 <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
3571 <code>x.M</code> is called a <i>method value</i>.
3572 The method value <code>x.M</code> is a function value that is callable
3573 with the same arguments as a method call of <code>x.M</code>.
3574 The expression <code>x</code> is evaluated and saved during the evaluation of the
3575 method value; the saved copy is then used as the receiver in any calls,
3576 which may be executed later.
3580 type S struct { *T }
3582 func (t T) M() { print(t) }
3586 f := t.M // receiver *t is evaluated and stored in f
3587 g := s.M // receiver *(s.T) is evaluated and stored in g
3588 *t = 42 // does not affect stored receivers in f and g
3592 The type <code>T</code> may be an interface or non-interface type.
3596 As in the discussion of <a href="#Method_expressions">method expressions</a> above,
3597 consider a struct type <code>T</code> with two methods,
3598 <code>Mv</code>, whose receiver is of type <code>T</code>, and
3599 <code>Mp</code>, whose receiver is of type <code>*T</code>.
3606 func (tv T) Mv(a int) int { return 0 } // value receiver
3607 func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
3623 yields a function value of type
3631 These two invocations are equivalent:
3640 Similarly, the expression
3648 yields a function value of type
3652 func(float32) float32
3656 As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver
3657 using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>.
3661 As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver
3662 using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&t).Mp</code>.
3666 f := t.Mv; f(7) // like t.Mv(7)
3667 f := pt.Mp; f(7) // like pt.Mp(7)
3668 f := pt.Mv; f(7) // like (*pt).Mv(7)
3669 f := t.Mp; f(7) // like (&t).Mp(7)
3670 f := makeT().Mp // invalid: result of makeT() is not addressable
3674 Although the examples above use non-interface types, it is also legal to create a method value
3675 from a value of interface type.
3679 var i interface { M(int) } = myVal
3680 f := i.M; f(7) // like i.M(7)
3684 <h3 id="Index_expressions">Index expressions</h3>
3687 A primary expression of the form
3695 denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>.
3696 The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively.
3697 The following rules apply:
3701 If <code>a</code> is neither a map nor a type parameter:
3704 <li>the index <code>x</code> must be an untyped constant or its
3705 <a href="#Core_types">core type</a> must be an <a href="#Numeric_types">integer</a></li>
3706 <li>a constant index must be non-negative and
3707 <a href="#Representability">representable</a> by a value of type <code>int</code></li>
3708 <li>a constant index that is untyped is given type <code>int</code></li>
3709 <li>the index <code>x</code> is <i>in range</i> if <code>0 <= x < len(a)</code>,
3710 otherwise it is <i>out of range</i></li>
3714 For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>:
3717 <li>a <a href="#Constants">constant</a> index must be in range</li>
3718 <li>if <code>x</code> is out of range at run time,
3719 a <a href="#Run_time_panics">run-time panic</a> occurs</li>
3720 <li><code>a[x]</code> is the array element at index <code>x</code> and the type of
3721 <code>a[x]</code> is the element type of <code>A</code></li>
3725 For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type:
3728 <li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li>
3732 For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>:
3735 <li>if <code>x</code> is out of range at run time,
3736 a <a href="#Run_time_panics">run-time panic</a> occurs</li>
3737 <li><code>a[x]</code> is the slice element at index <code>x</code> and the type of
3738 <code>a[x]</code> is the element type of <code>S</code></li>
3742 For <code>a</code> of <a href="#String_types">string type</a>:
3745 <li>a <a href="#Constants">constant</a> index must be in range
3746 if the string <code>a</code> is also constant</li>
3747 <li>if <code>x</code> is out of range at run time,
3748 a <a href="#Run_time_panics">run-time panic</a> occurs</li>
3749 <li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of
3750 <code>a[x]</code> is <code>byte</code></li>
3751 <li><code>a[x]</code> may not be assigned to</li>
3755 For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>:
3758 <li><code>x</code>'s type must be
3759 <a href="#Assignability">assignable</a>
3760 to the key type of <code>M</code></li>
3761 <li>if the map contains an entry with key <code>x</code>,
3762 <code>a[x]</code> is the map element with key <code>x</code>
3763 and the type of <code>a[x]</code> is the element type of <code>M</code></li>
3764 <li>if the map is <code>nil</code> or does not contain such an entry,
3765 <code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
3766 for the element type of <code>M</code></li>
3770 For <code>a</code> of <a href="#Type_parameter_declarations">type parameter type</a> <code>P</code>:
3773 <li>The index expression <code>a[x]</code> must be valid for values
3774 of all types in <code>P</code>'s type set.</li>
3775 <li>The element types of all types in <code>P</code>'s type set must be identical.
3776 In this context, the element type of a string type is <code>byte</code>.</li>
3777 <li>If there is a map type in the type set of <code>P</code>,
3778 all types in that type set must be map types, and the respective key types
3779 must be all identical.</li>
3780 <li><code>a[x]</code> is the array, slice, or string element at index <code>x</code>,
3781 or the map element with key <code>x</code> of the type argument
3782 that <code>P</code> is instantiated with, and the type of <code>a[x]</code> is
3783 the type of the (identical) element types.</li>
3784 <li><code>a[x]</code> may not be assigned to if <code>P</code>'s type set
3785 includes string types.
3789 Otherwise <code>a[x]</code> is illegal.
3793 An index expression on a map <code>a</code> of type <code>map[K]V</code>
3794 used in an <a href="#Assignments">assignment</a> or initialization of the special form
3804 yields an additional untyped boolean value. The value of <code>ok</code> is
3805 <code>true</code> if the key <code>x</code> is present in the map, and
3806 <code>false</code> otherwise.
3810 Assigning to an element of a <code>nil</code> map causes a
3811 <a href="#Run_time_panics">run-time panic</a>.
3815 <h3 id="Slice_expressions">Slice expressions</h3>
3818 Slice expressions construct a substring or slice from a string, array, pointer
3819 to array, or slice. There are two variants: a simple form that specifies a low
3820 and high bound, and a full form that also specifies a bound on the capacity.
3823 <h4>Simple slice expressions</h4>
3826 The primary expression
3834 constructs a substring or slice. The <a href="#Core_types">core type</a> of
3835 <code>a</code> must be a string, array, pointer to array, or slice.
3836 The <i>indices</i> <code>low</code> and
3837 <code>high</code> select which elements of operand <code>a</code> appear
3838 in the result. The result has indices starting at 0 and length equal to
3839 <code>high</code> - <code>low</code>.
3840 After slicing the array <code>a</code>
3844 a := [5]int{1, 2, 3, 4, 5}
3849 the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements
3859 For convenience, any of the indices may be omitted. A missing <code>low</code>
3860 index defaults to zero; a missing <code>high</code> index defaults to the length of the
3865 a[2:] // same as a[2 : len(a)]
3866 a[:3] // same as a[0 : 3]
3867 a[:] // same as a[0 : len(a)]
3871 If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for
3872 <code>(*a)[low : high]</code>.
3876 For arrays or strings, the indices are <i>in range</i> if
3877 <code>0</code> <= <code>low</code> <= <code>high</code> <= <code>len(a)</code>,
3878 otherwise they are <i>out of range</i>.
3879 For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length.
3880 A <a href="#Constants">constant</a> index must be non-negative and
3881 <a href="#Representability">representable</a> by a value of type
3882 <code>int</code>; for arrays or constant strings, constant indices must also be in range.
3883 If both indices are constant, they must satisfy <code>low <= high</code>.
3884 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3888 Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice,
3889 the result of the slice operation is a non-constant value of the same type as the operand.
3890 For untyped string operands the result is a non-constant value of type <code>string</code>.
3891 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>
3892 and the result of the slice operation is a slice with the same element type as the array.
3896 If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result
3897 is a <code>nil</code> slice. Otherwise, if the result is a slice, it shares its underlying
3898 array with the operand.
3903 s1 := a[3:7] // underlying array of s1 is array a; &s1[2] == &a[5]
3904 s2 := s1[1:4] // underlying array of s2 is underlying array of s1 which is array a; &s2[1] == &a[5]
3905 s2[1] = 42 // s2[1] == s1[2] == a[5] == 42; they all refer to the same underlying array element
3909 <h4>Full slice expressions</h4>
3912 The primary expression
3920 constructs a slice of the same type, and with the same length and elements as the simple slice
3921 expression <code>a[low : high]</code>. Additionally, it controls the resulting slice's capacity
3922 by setting it to <code>max - low</code>. Only the first index may be omitted; it defaults to 0.
3923 The <a href="#Core_types">core type</a> of <code>a</code> must be an array, pointer to array,
3924 or slice (but not a string).
3925 After slicing the array <code>a</code>
3929 a := [5]int{1, 2, 3, 4, 5}
3934 the slice <code>t</code> has type <code>[]int</code>, length 2, capacity 4, and elements
3943 As for simple slice expressions, if <code>a</code> is a pointer to an array,
3944 <code>a[low : high : max]</code> is shorthand for <code>(*a)[low : high : max]</code>.
3945 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>.
3949 The indices are <i>in range</i> if <code>0 <= low <= high <= max <= cap(a)</code>,
3950 otherwise they are <i>out of range</i>.
3951 A <a href="#Constants">constant</a> index must be non-negative and
3952 <a href="#Representability">representable</a> by a value of type
3953 <code>int</code>; for arrays, constant indices must also be in range.
3954 If multiple indices are constant, the constants that are present must be in range relative to each
3956 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3959 <h3 id="Type_assertions">Type assertions</h3>
3962 For an expression <code>x</code> of <a href="#Interface_types">interface type</a>,
3963 but not a <a href="#Type_parameter_declarations">type parameter</a>, and a type <code>T</code>,
3964 the primary expression
3972 asserts that <code>x</code> is not <code>nil</code>
3973 and that the value stored in <code>x</code> is of type <code>T</code>.
3974 The notation <code>x.(T)</code> is called a <i>type assertion</i>.
3977 More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
3978 that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a>
3979 to the type <code>T</code>.
3980 In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>;
3981 otherwise the type assertion is invalid since it is not possible for <code>x</code>
3982 to store a value of type <code>T</code>.
3983 If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
3984 of <code>x</code> <a href="#Implementing_an_interface">implements</a> the interface <code>T</code>.
3987 If the type assertion holds, the value of the expression is the value
3988 stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false,
3989 a <a href="#Run_time_panics">run-time panic</a> occurs.
3990 In other words, even though the dynamic type of <code>x</code>
3991 is known only at run time, the type of <code>x.(T)</code> is
3992 known to be <code>T</code> in a correct program.
3996 var x interface{} = 7 // x has dynamic type int and value 7
3997 i := x.(int) // i has type int and value 7
3999 type I interface { m() }
4002 s := y.(string) // illegal: string does not implement I (missing method m)
4003 r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader
4009 A type assertion used in an <a href="#Assignments">assignment</a> or initialization of the special form
4016 var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool
4020 yields an additional untyped boolean value. The value of <code>ok</code> is <code>true</code>
4021 if the assertion holds. Otherwise it is <code>false</code> and the value of <code>v</code> is
4022 the <a href="#The_zero_value">zero value</a> for type <code>T</code>.
4023 No <a href="#Run_time_panics">run-time panic</a> occurs in this case.
4027 <h3 id="Calls">Calls</h3>
4030 Given an expression <code>f</code> with a <a href="#Core_types">core type</a>
4031 <code>F</code> of <a href="#Function_types">function type</a>,
4039 calls <code>f</code> with arguments <code>a1, a2, … an</code>.
4040 Except for one special case, arguments must be single-valued expressions
4041 <a href="#Assignability">assignable</a> to the parameter types of
4042 <code>F</code> and are evaluated before the function is called.
4043 The type of the expression is the result type
4045 A method invocation is similar but the method itself
4046 is specified as a selector upon a value of the receiver type for
4051 math.Atan2(x, y) // function call
4053 pt.Scale(3.5) // method call with receiver pt
4057 If <code>f</code> denotes a generic function, it must be
4058 <a href="#Instantiations">instantiated</a> before it can be called
4059 or used as a function value.
4063 In a function call, the function value and arguments are evaluated in
4064 <a href="#Order_of_evaluation">the usual order</a>.
4065 After they are evaluated, the parameters of the call are passed by value to the function
4066 and the called function begins execution.
4067 The return parameters of the function are passed by value
4068 back to the caller when the function returns.
4072 Calling a <code>nil</code> function value
4073 causes a <a href="#Run_time_panics">run-time panic</a>.
4077 As a special case, if the return values of a function or method
4078 <code>g</code> are equal in number and individually
4079 assignable to the parameters of another function or method
4080 <code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code>
4081 will invoke <code>f</code> after binding the return values of
4082 <code>g</code> to the parameters of <code>f</code> in order. The call
4083 of <code>f</code> must contain no parameters other than the call of <code>g</code>,
4084 and <code>g</code> must have at least one return value.
4085 If <code>f</code> has a final <code>...</code> parameter, it is
4086 assigned the return values of <code>g</code> that remain after
4087 assignment of regular parameters.
4091 func Split(s string, pos int) (string, string) {
4092 return s[0:pos], s[pos:]
4095 func Join(s, t string) string {
4099 if Join(Split(value, len(value)/2)) != value {
4100 log.Panic("test fails")
4105 A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a>
4106 of (the type of) <code>x</code> contains <code>m</code> and the
4107 argument list can be assigned to the parameter list of <code>m</code>.
4108 If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&x</code>'s method
4109 set contains <code>m</code>, <code>x.m()</code> is shorthand
4110 for <code>(&x).m()</code>:
4119 There is no distinct method type and there are no method literals.
4122 <h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3>
4125 If <code>f</code> is <a href="#Function_types">variadic</a> with a final
4126 parameter <code>p</code> of type <code>...T</code>, then within <code>f</code>
4127 the type of <code>p</code> is equivalent to type <code>[]T</code>.
4128 If <code>f</code> is invoked with no actual arguments for <code>p</code>,
4129 the value passed to <code>p</code> is <code>nil</code>.
4130 Otherwise, the value passed is a new slice
4131 of type <code>[]T</code> with a new underlying array whose successive elements
4132 are the actual arguments, which all must be <a href="#Assignability">assignable</a>
4133 to <code>T</code>. The length and capacity of the slice is therefore
4134 the number of arguments bound to <code>p</code> and may differ for each
4139 Given the function and calls
4142 func Greeting(prefix string, who ...string)
4144 Greeting("hello:", "Joe", "Anna", "Eileen")
4148 within <code>Greeting</code>, <code>who</code> will have the value
4149 <code>nil</code> in the first call, and
4150 <code>[]string{"Joe", "Anna", "Eileen"}</code> in the second.
4154 If the final argument is assignable to a slice type <code>[]T</code> and
4155 is followed by <code>...</code>, it is passed unchanged as the value
4156 for a <code>...T</code> parameter. In this case no new slice is created.
4160 Given the slice <code>s</code> and call
4164 s := []string{"James", "Jasmine"}
4165 Greeting("goodbye:", s...)
4169 within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code>
4170 with the same underlying array.
4173 <h3 id="Instantiations">Instantiations</h3>
4176 A generic function or type is <i>instantiated</i> by substituting <i>type arguments</i>
4177 for the type parameters.
4178 Instantiation proceeds in two steps:
4183 Each type argument is substituted for its corresponding type parameter in the generic
4185 This substitution happens across the entire function or type declaration,
4186 including the type parameter list itself and any types in that list.
4190 After substitution, each type argument must <a href="#Interface_types">implement</a>
4191 the <a href="#Type_parameter_declarations">constraint</a> (instantiated, if necessary)
4192 of the corresponding type parameter. Otherwise instantiation fails.
4197 Instantiating a type results in a new non-generic <a href="#Types">named type</a>;
4198 instantiating a function produces a new non-generic function.
4202 type parameter list type arguments after substitution
4204 [P any] int int implements any
4205 [S ~[]E, E any] []int, int []int implements ~[]int, int implements any
4206 [P io.Writer] string illegal: string doesn't implement io.Writer
4210 For a generic function, type arguments may be provided explicitly, or they
4211 may be partially or completely <a href="#Type_inference">inferred</a>.
4212 A generic function that is <i>not</i> <a href="#Calls">called</a> requires a
4213 type argument list for instantiation; if the list is partial, all
4214 remaining type arguments must be inferrable.
4215 A generic function that is called may provide a (possibly partial) type
4216 argument list, or may omit it entirely if the omitted type arguments are
4217 inferrable from the ordinary (non-type) function arguments.
4221 func min[T ~int|~float64](x, y T) T { … }
4223 f := min // illegal: min must be instantiated with type arguments when used without being called
4224 minInt := min[int] // minInt has type func(x, y int) int
4225 a := minInt(2, 3) // a has value 2 of type int
4226 b := min[float64](2.0, 3) // b has value 2.0 of type float64
4227 c := min(b, -1) // c has value -1.0 of type float64
4231 A partial type argument list cannot be empty; at least the first argument must be present.
4232 The list is a prefix of the full list of type arguments, leaving the remaining arguments
4233 to be inferred. Loosely speaking, type arguments may be omitted from "right to left".
4237 func apply[S ~[]E, E any](s S, f(E) E) S { … }
4239 f0 := apply[] // illegal: type argument list cannot be empty
4240 f1 := apply[[]int] // type argument for S explicitly provided, type argument for E inferred
4241 f2 := apply[[]string, string] // both type arguments explicitly provided
4244 r := apply(bytes, func(byte) byte { … }) // both type arguments inferred from the function arguments
4248 For a generic type, all type arguments must always be provided explicitly.
4251 <h3 id="Type_inference">Type inference</h3>
4254 Missing function type arguments may be <i>inferred</i> by a series of steps, described below.
4255 Each step attempts to use known information to infer additional type arguments.
4256 Type inference stops as soon as all type arguments are known.
4257 After type inference is complete, it is still necessary to substitute all type arguments
4258 for type parameters and verify that each type argument
4259 <a href="#Implementing_an_interface">implements</a> the relevant constraint;
4260 it is possible for an inferred type argument to fail to implement a constraint, in which
4261 case instantiation fails.
4265 Type inference is based on
4270 a <a href="#Type_parameter_declarations">type parameter list</a>
4273 a substitution map <i>M</i> initialized with the known type arguments, if any
4276 a (possibly empty) list of ordinary function arguments (in case of a function call only)
4281 and then proceeds with the following steps:
4286 apply <a href="#Function_argument_type_inference"><i>function argument type inference</i></a>
4287 to all <i>typed</i> ordinary function arguments
4290 apply <a href="#Constraint_type_inference"><i>constraint type inference</i></a>
4293 apply function argument type inference to all <i>untyped</i> ordinary function arguments
4294 using the default type for each of the untyped function arguments
4297 apply constraint type inference
4302 If there are no ordinary or untyped function arguments, the respective steps are skipped.
4303 Constraint type inference is skipped if the previous step didn't infer any new type arguments,
4304 but it is run at least once if there are missing type arguments.
4308 The substitution map <i>M</i> is carried through all steps, and each step may add entries to <i>M</i>.
4309 The process stops as soon as <i>M</i> has a type argument for each type parameter or if an inference step fails.
4310 If an inference step fails, or if <i>M</i> is still missing type arguments after the last step, type inference fails.
4313 <h4 id="Type_unification">Type unification</h4>
4316 Type inference is based on <i>type unification</i>. A single unification step
4317 applies to a <a href="#Type_inference">substitution map</a> and two types, either
4318 or both of which may be or contain type parameters. The substitution map tracks
4319 the known (explicitly provided or already inferred) type arguments: the map
4320 contains an entry <code>P</code> → <code>A</code> for each type
4321 parameter <code>P</code> and corresponding known type argument <code>A</code>.
4322 During unification, known type arguments take the place of their corresponding type
4323 parameters when comparing types. Unification is the process of finding substitution
4324 map entries that make the two types equivalent.
4328 For unification, two types that don't contain any type parameters from the current type
4329 parameter list are <i>equivalent</i>
4330 if they are identical, or if they are channel types that are identical ignoring channel
4331 direction, or if their underlying types are equivalent.
4335 Unification works by comparing the structure of pairs of types: their structure
4336 disregarding type parameters must be identical, and types other than type parameters
4338 A type parameter in one type may match any complete subtype in the other type;
4339 each successful match causes an entry to be added to the substitution map.
4340 If the structure differs, or types other than type parameters are not equivalent,
4345 TODO(gri) Somewhere we need to describe the process of adding an entry to the
4346 substitution map: if the entry is already present, the type argument
4347 values are themselves unified.
4351 For example, if <code>T1</code> and <code>T2</code> are type parameters,
4352 <code>[]map[int]bool</code> can be unified with any of the following:
4356 []map[int]bool // types are identical
4357 T1 // adds T1 → []map[int]bool to substitution map
4358 []T1 // adds T1 → map[int]bool to substitution map
4359 []map[T1]T2 // adds T1 → int and T2 → bool to substitution map
4363 On the other hand, <code>[]map[int]bool</code> cannot be unified with any of
4367 int // int is not a slice
4368 struct{} // a struct is not a slice
4369 []struct{} // a struct is not a map
4370 []map[T1]string // map element types don't match
4374 As an exception to this general rule, because a <a href="#Type_definitions">defined type</a>
4375 <code>D</code> and a type literal <code>L</code> are never equivalent,
4376 unification compares the underlying type of <code>D</code> with <code>L</code> instead.
4377 For example, given the defined type
4381 type Vector []float64
4385 and the type literal <code>[]E</code>, unification compares <code>[]float64</code> with
4386 <code>[]E</code> and adds an entry <code>E</code> → <code>float64</code> to
4387 the substitution map.
4390 <h4 id="Function_argument_type_inference">Function argument type inference</h4>
4392 <!-- In this section and the section on constraint type inference we start with examples
4393 rather than have the examples follow the rules as is customary elsewhere in spec.
4394 Hopefully this helps building an intuition and makes the rules easier to follow. -->
4397 Function argument type inference infers type arguments from function arguments:
4398 if a function parameter is declared with a type <code>T</code> that uses
4400 <a href="#Type_unification">unifying</a> the type of the corresponding
4401 function argument with <code>T</code> may infer type arguments for the type
4402 parameters used by <code>T</code>.
4406 For instance, given the generic function
4410 func scale[Number ~int64|~float64|~complex128](v []Number, s Number) []Number
4418 var vector []float64
4419 scaledVector := scale(vector, 42)
4423 the type argument for <code>Number</code> can be inferred from the function argument
4424 <code>vector</code> by unifying the type of <code>vector</code> with the corresponding
4425 parameter type: <code>[]float64</code> and <code>[]Number</code>
4426 match in structure and <code>float64</code> matches with <code>Number</code>.
4427 This adds the entry <code>Number</code> → <code>float64</code> to the
4428 <a href="#Type_unification">substitution map</a>.
4429 Untyped arguments, such as the second function argument <code>42</code> here, are ignored
4430 in the first round of function argument type inference and only considered if there are
4431 unresolved type parameters left.
4435 Inference happens in two separate phases; each phase operates on a specific list of
4436 (parameter, argument) pairs:
4441 The list <i>Lt</i> contains all (parameter, argument) pairs where the parameter
4442 type uses type parameters and where the function argument is <i>typed</i>.
4445 The list <i>Lu</i> contains all remaining pairs where the parameter type is a single
4446 type parameter. In this list, the respective function arguments are untyped.
4451 Any other (parameter, argument) pair is ignored.
4455 By construction, the arguments of the pairs in <i>Lu</i> are <i>untyped</i> constants
4456 (or the untyped boolean result of a comparison). And because <a href="#Constants">default types</a>
4457 of untyped values are always predeclared non-composite types, they can never match against
4458 a composite type, so it is sufficient to only consider parameter types that are single type
4463 Each list is processed in a separate phase:
4468 In the first phase, the parameter and argument types of each pair in <i>Lt</i>
4469 are unified. If unification succeeds for a pair, it may yield new entries that
4470 are added to the substitution map <i>M</i>. If unification fails, type inference
4474 The second phase considers the entries of list <i>Lu</i>. Type parameters for
4475 which the type argument has already been determined are ignored in this phase.
4476 For each remaining pair, the parameter type (which is a single type parameter) and
4477 the <a href="#Constants">default type</a> of the corresponding untyped argument is
4478 unified. If unification fails, type inference fails.
4483 While unification is successful, processing of each list continues until all list elements
4484 are considered, even if all type arguments are inferred before the last list element has
4493 func min[T ~int|~float64](x, y T) T
4496 min(x, 2.0) // T is int, inferred from typed argument x; 2.0 is assignable to int
4497 min(1.0, 2.0) // T is float64, inferred from default type for 1.0 and matches default type for 2.0
4498 min(1.0, 2) // illegal: default type float64 (for 1.0) doesn't match default type int (for 2)
4502 In the example <code>min(1.0, 2)</code>, processing the function argument <code>1.0</code>
4503 yields the substitution map entry <code>T</code> → <code>float64</code>. Because
4504 processing continues until all untyped arguments are considered, an error is reported. This
4505 ensures that type inference does not depend on the order of the untyped arguments.
4508 <h4 id="Constraint_type_inference">Constraint type inference</h4>
4511 Constraint type inference infers type arguments by considering type constraints.
4512 If a type parameter <code>P</code> has a constraint with a
4513 <a href="#Core_types">core type</a> <code>C</code>,
4514 <a href="#Type_unification">unifying</a> <code>P</code> with <code>C</code>
4515 may infer additional type arguments, either the type argument for <code>P</code>,
4516 or if that is already known, possibly the type arguments for type parameters
4517 used in <code>C</code>.
4521 For instance, consider the type parameter list with type parameters <code>List</code> and
4526 [List ~[]Elem, Elem any]
4530 Constraint type inference can deduce the type of <code>Elem</code> from the type argument
4531 for <code>List</code> because <code>Elem</code> is a type parameter in the core type
4532 <code>[]Elem</code> of <code>List</code>.
4533 If the type argument is <code>Bytes</code>:
4541 unifying the underlying type of <code>Bytes</code> with the core type means
4542 unifying <code>[]byte</code> with <code>[]Elem</code>. That unification succeeds and yields
4543 the <a href="#Type_unification">substitution map</a> entry
4544 <code>Elem</code> → <code>byte</code>.
4545 Thus, in this example, constraint type inference can infer the second type argument from the
4550 Using the core type of a constraint may lose some information: In the (unlikely) case that
4551 the constraint's type set contains a single <a href="#Type_definitions">defined type</a>
4552 <code>N</code>, the corresponding core type is <code>N</code>'s underlying type rather than
4553 <code>N</code> itself. In this case, constraint type inference may succeed but instantiation
4554 will fail because the inferred type is not in the type set of the constraint.
4555 Thus, constraint type inference uses the <i>adjusted core type</i> of
4556 a constraint: if the type set contains a single type, use that type; otherwise use the
4557 constraint's core type.
4561 Generally, constraint type inference proceeds in two phases: Starting with a given
4562 substitution map <i>M</i>
4567 For all type parameters with an adjusted core type, unify the type parameter with that
4568 type. If any unification fails, constraint type inference fails.
4572 At this point, some entries in <i>M</i> may map type parameters to other
4573 type parameters or to types containing type parameters. For each entry
4574 <code>P</code> → <code>A</code> in <i>M</i> where <code>A</code> is or
4575 contains type parameters <code>Q</code> for which there exist entries
4576 <code>Q</code> → <code>B</code> in <i>M</i>, substitute those
4577 <code>Q</code> with the respective <code>B</code> in <code>A</code>.
4578 Stop when no further substitution is possible.
4583 The result of constraint type inference is the final substitution map <i>M</i> from type
4584 parameters <code>P</code> to type arguments <code>A</code> where no type parameter <code>P</code>
4585 appears in any of the <code>A</code>.
4589 For instance, given the type parameter list
4593 [A any, B []C, C *A]
4597 and the single provided type argument <code>int</code> for type parameter <code>A</code>,
4598 the initial substitution map <i>M</i> contains the entry <code>A</code> → <code>int</code>.
4602 In the first phase, the type parameters <code>B</code> and <code>C</code> are unified
4603 with the core type of their respective constraints. This adds the entries
4604 <code>B</code> → <code>[]C</code> and <code>C</code> → <code>*A</code>
4608 At this point there are two entries in <i>M</i> where the right-hand side
4609 is or contains type parameters for which there exists other entries in <i>M</i>:
4610 <code>[]C</code> and <code>*A</code>.
4611 In the second phase, these type parameters are replaced with their respective
4612 types. It doesn't matter in which order this happens. Starting with the state
4613 of <i>M</i> after the first phase:
4617 <code>A</code> → <code>int</code>,
4618 <code>B</code> → <code>[]C</code>,
4619 <code>C</code> → <code>*A</code>
4623 Replace <code>A</code> on the right-hand side of → with <code>int</code>:
4627 <code>A</code> → <code>int</code>,
4628 <code>B</code> → <code>[]C</code>,
4629 <code>C</code> → <code>*int</code>
4633 Replace <code>C</code> on the right-hand side of → with <code>*int</code>:
4637 <code>A</code> → <code>int</code>,
4638 <code>B</code> → <code>[]*int</code>,
4639 <code>C</code> → <code>*int</code>
4643 At this point no further substitution is possible and the map is full.
4644 Therefore, <code>M</code> represents the final map of type parameters
4645 to type arguments for the given type parameter list.
4648 <h3 id="Operators">Operators</h3>
4651 Operators combine operands into expressions.
4655 Expression = UnaryExpr | Expression binary_op Expression .
4656 UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
4658 binary_op = "||" | "&&" | rel_op | add_op | mul_op .
4659 rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" .
4660 add_op = "+" | "-" | "|" | "^" .
4661 mul_op = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" .
4663 unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-" .
4667 Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>.
4668 For other binary operators, the operand types must be <a href="#Type_identity">identical</a>
4669 unless the operation involves shifts or untyped <a href="#Constants">constants</a>.
4670 For operations involving constants only, see the section on
4671 <a href="#Constant_expressions">constant expressions</a>.
4675 Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a>
4676 and the other operand is not, the constant is implicitly <a href="#Conversions">converted</a>
4677 to the type of the other operand.
4681 The right operand in a shift expression must have <a href="#Numeric_types">integer type</a>
4682 or be an untyped constant <a href="#Representability">representable</a> by a
4683 value of type <code>uint</code>.
4684 If the left operand of a non-constant shift expression is an untyped constant,
4685 it is first implicitly converted to the type it would assume if the shift expression were
4686 replaced by its left operand alone.
4693 // The results of the following examples are given for 64-bit ints.
4694 var i = 1<<s // 1 has type int
4695 var j int32 = 1<<s // 1 has type int32; j == 0
4696 var k = uint64(1<<s) // 1 has type uint64; k == 1<<33
4697 var m int = 1.0<<s // 1.0 has type int; m == 1<<33
4698 var n = 1.0<<s == j // 1.0 has type int32; n == true
4699 var o = 1<<s == 2<<s // 1 and 2 have type int; o == false
4700 var p = 1<<s == 1<<33 // 1 has type int; p == true
4701 var u = 1.0<<s // illegal: 1.0 has type float64, cannot shift
4702 var u1 = 1.0<<s != 0 // illegal: 1.0 has type float64, cannot shift
4703 var u2 = 1<<s != 1.0 // illegal: 1 has type float64, cannot shift
4704 var v1 float32 = 1<<s // illegal: 1 has type float32, cannot shift
4705 var v2 = string(1<<s) // illegal: 1 is converted to a string, cannot shift
4706 var w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression; w == 1<<33
4707 var x = a[1.0<<s] // panics: 1.0 has type int, but 1<<33 overflows array bounds
4708 var b = make([]byte, 1.0<<s) // 1.0 has type int; len(b) == 1<<33
4710 // The results of the following examples are given for 32-bit ints,
4711 // which means the shifts will overflow.
4712 var mm int = 1.0<<s // 1.0 has type int; mm == 0
4713 var oo = 1<<s == 2<<s // 1 and 2 have type int; oo == true
4714 var pp = 1<<s == 1<<33 // illegal: 1 has type int, but 1<<33 overflows int
4715 var xx = a[1.0<<s] // 1.0 has type int; xx == a[0]
4716 var bb = make([]byte, 1.0<<s) // 1.0 has type int; len(bb) == 0
4719 <h4 id="Operator_precedence">Operator precedence</h4>
4721 Unary operators have the highest precedence.
4722 As the <code>++</code> and <code>--</code> operators form
4723 statements, not expressions, they fall
4724 outside the operator hierarchy.
4725 As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>.
4727 There are five precedence levels for binary operators.
4728 Multiplication operators bind strongest, followed by addition
4729 operators, comparison operators, <code>&&</code> (logical AND),
4730 and finally <code>||</code> (logical OR):
4733 <pre class="grammar">
4735 5 * / % << >> & &^
4737 3 == != < <= > >=
4743 Binary operators of the same precedence associate from left to right.
4744 For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>.
4753 x == y+1 && <-chanInt > 0
4757 <h3 id="Arithmetic_operators">Arithmetic operators</h3>
4759 Arithmetic operators apply to numeric values and yield a result of the same
4760 type as the first operand. The four standard arithmetic operators (<code>+</code>,
4761 <code>-</code>, <code>*</code>, <code>/</code>) apply to
4762 <a href="#Numeric_types">integer</a>, <a href="#Numeric_types">floating-point</a>, and
4763 <a href="#Numeric_types">complex</a> types; <code>+</code> also applies to <a href="#String_types">strings</a>.
4764 The bitwise logical and shift operators apply to integers only.
4767 <pre class="grammar">
4768 + sum integers, floats, complex values, strings
4769 - difference integers, floats, complex values
4770 * product integers, floats, complex values
4771 / quotient integers, floats, complex values
4772 % remainder integers
4774 & bitwise AND integers
4775 | bitwise OR integers
4776 ^ bitwise XOR integers
4777 &^ bit clear (AND NOT) integers
4779 << left shift integer << integer >= 0
4780 >> right shift integer >> integer >= 0
4784 If the operand type is a <a href="#Type_parameter_declarations">type parameter</a>,
4785 the operator must apply to each type in that type set.
4786 The operands are represented as values of the type argument that the type parameter
4787 is <a href="#Instantiations">instantiated</a> with, and the operation is computed
4788 with the precision of that type argument. For example, given the function:
4792 func dotProduct[F ~float32|~float64](v1, v2 []F) F {
4794 for i, x := range v1 {
4803 the product <code>x * y</code> and the addition <code>s += x * y</code>
4804 are computed with <code>float32</code> or <code>float64</code> precision,
4805 respectively, depending on the type argument for <code>F</code>.
4808 <h4 id="Integer_operators">Integer operators</h4>
4811 For two integer values <code>x</code> and <code>y</code>, the integer quotient
4812 <code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following
4817 x = q*y + r and |r| < |y|
4821 with <code>x / y</code> truncated towards zero
4822 (<a href="https://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>).
4834 The one exception to this rule is that if the dividend <code>x</code> is
4835 the most negative value for the int type of <code>x</code>, the quotient
4836 <code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>)
4837 due to two's-complement <a href="#Integer_overflow">integer overflow</a>:
4845 int64 -9223372036854775808
4849 If the divisor is a <a href="#Constants">constant</a>, it must not be zero.
4850 If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
4851 If the dividend is non-negative and the divisor is a constant power of 2,
4852 the division may be replaced by a right shift, and computing the remainder may
4853 be replaced by a bitwise AND operation:
4857 x x / 4 x % 4 x >> 2 x & 3
4863 The shift operators shift the left operand by the shift count specified by the
4864 right operand, which must be non-negative. If the shift count is negative at run time,
4865 a <a href="#Run_time_panics">run-time panic</a> occurs.
4866 The shift operators implement arithmetic shifts if the left operand is a signed
4867 integer and logical shifts if it is an unsigned integer.
4868 There is no upper limit on the shift count. Shifts behave
4869 as if the left operand is shifted <code>n</code> times by 1 for a shift
4870 count of <code>n</code>.
4871 As a result, <code>x << 1</code> is the same as <code>x*2</code>
4872 and <code>x >> 1</code> is the same as
4873 <code>x/2</code> but truncated towards negative infinity.
4877 For integer operands, the unary operators
4878 <code>+</code>, <code>-</code>, and <code>^</code> are defined as
4882 <pre class="grammar">
4884 -x negation is 0 - x
4885 ^x bitwise complement is m ^ x with m = "all bits set to 1" for unsigned x
4886 and m = -1 for signed x
4890 <h4 id="Integer_overflow">Integer overflow</h4>
4893 For <a href="#Numeric_types">unsigned integer</a> values, the operations <code>+</code>,
4894 <code>-</code>, <code>*</code>, and <code><<</code> are
4895 computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of
4896 the unsigned integer's type.
4897 Loosely speaking, these unsigned integer operations
4898 discard high bits upon overflow, and programs may rely on "wrap around".
4902 For signed integers, the operations <code>+</code>,
4903 <code>-</code>, <code>*</code>, <code>/</code>, and <code><<</code> may legally
4904 overflow and the resulting value exists and is deterministically defined
4905 by the signed integer representation, the operation, and its operands.
4906 Overflow does not cause a <a href="#Run_time_panics">run-time panic</a>.
4907 A compiler may not optimize code under the assumption that overflow does
4908 not occur. For instance, it may not assume that <code>x < x + 1</code> is always true.
4911 <h4 id="Floating_point_operators">Floating-point operators</h4>
4914 For floating-point and complex numbers,
4915 <code>+x</code> is the same as <code>x</code>,
4916 while <code>-x</code> is the negation of <code>x</code>.
4917 The result of a floating-point or complex division by zero is not specified beyond the
4918 IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a>
4919 occurs is implementation-specific.
4923 An implementation may combine multiple floating-point operations into a single
4924 fused operation, possibly across statements, and produce a result that differs
4925 from the value obtained by executing and rounding the instructions individually.
4926 An explicit <a href="#Numeric_types">floating-point type</a> <a href="#Conversions">conversion</a> rounds to
4927 the precision of the target type, preventing fusion that would discard that rounding.
4931 For instance, some architectures provide a "fused multiply and add" (FMA) instruction
4932 that computes <code>x*y + z</code> without rounding the intermediate result <code>x*y</code>.
4933 These examples show when a Go implementation can use that instruction:
4937 // FMA allowed for computing r, because x*y is not explicitly rounded:
4941 *p = x*y; r = *p + z
4942 r = x*y + float64(z)
4944 // FMA disallowed for computing r, because it would omit rounding of x*y:
4945 r = float64(x*y) + z
4946 r = z; r += float64(x*y)
4947 t = float64(x*y); r = t + z
4950 <h4 id="String_concatenation">String concatenation</h4>
4953 Strings can be concatenated using the <code>+</code> operator
4954 or the <code>+=</code> assignment operator:
4958 s := "hi" + string(c)
4959 s += " and good bye"
4963 String addition creates a new string by concatenating the operands.
4966 <h3 id="Comparison_operators">Comparison operators</h3>
4969 Comparison operators compare two operands and yield an untyped boolean value.
4972 <pre class="grammar">
4978 >= greater or equal
4982 In any comparison, the first operand
4983 must be <a href="#Assignability">assignable</a>
4984 to the type of the second operand, or vice versa.
4987 The equality operators <code>==</code> and <code>!=</code> apply
4988 to operands that are <i>comparable</i>.
4989 The ordering operators <code><</code>, <code><=</code>, <code>></code>, and <code>>=</code>
4990 apply to operands that are <i>ordered</i>.
4991 These terms and the result of the comparisons are defined as follows:
4996 Boolean values are comparable.
4997 Two boolean values are equal if they are either both
4998 <code>true</code> or both <code>false</code>.
5002 Integer values are comparable and ordered, in the usual way.
5006 Floating-point values are comparable and ordered,
5007 as defined by the IEEE-754 standard.
5011 Complex values are comparable.
5012 Two complex values <code>u</code> and <code>v</code> are
5013 equal if both <code>real(u) == real(v)</code> and
5014 <code>imag(u) == imag(v)</code>.
5018 String values are comparable and ordered, lexically byte-wise.
5022 Pointer values are comparable.
5023 Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>.
5024 Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal.
5028 Channel values are comparable.
5029 Two channel values are equal if they were created by the same call to
5030 <a href="#Making_slices_maps_and_channels"><code>make</code></a>
5031 or if both have value <code>nil</code>.
5035 Interface values are comparable.
5036 Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types
5037 and equal dynamic values or if both have value <code>nil</code>.
5041 A value <code>x</code> of non-interface type <code>X</code> and
5042 a value <code>t</code> of interface type <code>T</code> are comparable when values
5043 of type <code>X</code> are comparable and
5044 <code>X</code> <a href="#Implementing_an_interface">implements</a> <code>T</code>.
5045 They are equal if <code>t</code>'s dynamic type is identical to <code>X</code>
5046 and <code>t</code>'s dynamic value is equal to <code>x</code>.
5050 Struct values are comparable if all their fields are comparable.
5051 Two struct values are equal if their corresponding
5052 non-<a href="#Blank_identifier">blank</a> fields are equal.
5056 Array values are comparable if values of the array element type are comparable.
5057 Two array values are equal if their corresponding elements are equal.
5062 A comparison of two interface values with identical dynamic types
5063 causes a <a href="#Run_time_panics">run-time panic</a> if values
5064 of that type are not comparable. This behavior applies not only to direct interface
5065 value comparisons but also when comparing arrays of interface values
5066 or structs with interface-valued fields.
5070 Slice, map, and function values are not comparable.
5071 However, as a special case, a slice, map, or function value may
5072 be compared to the predeclared identifier <code>nil</code>.
5073 Comparison of pointer, channel, and interface values to <code>nil</code>
5074 is also allowed and follows from the general rules above.
5078 const c = 3 < 4 // c is the untyped boolean constant true
5083 // The result of a comparison is an untyped boolean.
5084 // The usual assignment rules apply.
5085 b3 = x == y // b3 has type bool
5086 b4 bool = x == y // b4 has type bool
5087 b5 MyBool = x == y // b5 has type MyBool
5091 <h3 id="Logical_operators">Logical operators</h3>
5094 Logical operators apply to <a href="#Boolean_types">boolean</a> values
5095 and yield a result of the same type as the operands.
5096 The right operand is evaluated conditionally.
5099 <pre class="grammar">
5100 && conditional AND p && q is "if p then q else false"
5101 || conditional OR p || q is "if p then true else q"
5106 <h3 id="Address_operators">Address operators</h3>
5109 For an operand <code>x</code> of type <code>T</code>, the address operation
5110 <code>&x</code> generates a pointer of type <code>*T</code> to <code>x</code>.
5111 The operand must be <i>addressable</i>,
5112 that is, either a variable, pointer indirection, or slice indexing
5113 operation; or a field selector of an addressable struct operand;
5114 or an array indexing operation of an addressable array.
5115 As an exception to the addressability requirement, <code>x</code> may also be a
5116 (possibly parenthesized)
5117 <a href="#Composite_literals">composite literal</a>.
5118 If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>,
5119 then the evaluation of <code>&x</code> does too.
5123 For an operand <code>x</code> of pointer type <code>*T</code>, the pointer
5124 indirection <code>*x</code> denotes the <a href="#Variables">variable</a> of type <code>T</code> pointed
5125 to by <code>x</code>.
5126 If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code>
5127 will cause a <a href="#Run_time_panics">run-time panic</a>.
5138 *x // causes a run-time panic
5139 &*x // causes a run-time panic
5143 <h3 id="Receive_operator">Receive operator</h3>
5146 For an operand <code>ch</code> whose <a href="#Core_types">core type</a> is a
5147 <a href="#Channel_types">channel</a>,
5148 the value of the receive operation <code><-ch</code> is the value received
5149 from the channel <code>ch</code>. The channel direction must permit receive operations,
5150 and the type of the receive operation is the element type of the channel.
5151 The expression blocks until a value is available.
5152 Receiving from a <code>nil</code> channel blocks forever.
5153 A receive operation on a <a href="#Close">closed</a> channel can always proceed
5154 immediately, yielding the element type's <a href="#The_zero_value">zero value</a>
5155 after any previously sent values have been received.
5162 <-strobe // wait until clock pulse and discard received value
5166 A receive expression used in an <a href="#Assignments">assignment</a> or initialization of the special form
5173 var x, ok T = <-ch
5177 yields an additional untyped boolean result reporting whether the
5178 communication succeeded. The value of <code>ok</code> is <code>true</code>
5179 if the value received was delivered by a successful send operation to the
5180 channel, or <code>false</code> if it is a zero value generated because the
5181 channel is closed and empty.
5185 <h3 id="Conversions">Conversions</h3>
5188 A conversion changes the <a href="#Types">type</a> of an expression
5189 to the type specified by the conversion.
5190 A conversion may appear literally in the source, or it may be <i>implied</i>
5191 by the context in which an expression appears.
5195 An <i>explicit</i> conversion is an expression of the form <code>T(x)</code>
5196 where <code>T</code> is a type and <code>x</code> is an expression
5197 that can be converted to type <code>T</code>.
5201 Conversion = Type "(" Expression [ "," ] ")" .
5205 If the type starts with the operator <code>*</code> or <code><-</code>,
5206 or if the type starts with the keyword <code>func</code>
5207 and has no result list, it must be parenthesized when
5208 necessary to avoid ambiguity:
5212 *Point(p) // same as *(Point(p))
5213 (*Point)(p) // p is converted to *Point
5214 <-chan int(c) // same as <-(chan int(c))
5215 (<-chan int)(c) // c is converted to <-chan int
5216 func()(x) // function signature func() x
5217 (func())(x) // x is converted to func()
5218 (func() int)(x) // x is converted to func() int
5219 func() int(x) // x is converted to func() int (unambiguous)
5223 A <a href="#Constants">constant</a> value <code>x</code> can be converted to
5224 type <code>T</code> if <code>x</code> is <a href="#Representability">representable</a>
5225 by a value of <code>T</code>.
5226 As a special case, an integer constant <code>x</code> can be explicitly converted to a
5227 <a href="#String_types">string type</a> using the
5228 <a href="#Conversions_to_and_from_a_string_type">same rule</a>
5229 as for non-constant <code>x</code>.
5233 Converting a constant to a type that is not a <a href="#Type_parameter_declarations">type parameter</a>
5234 yields a typed constant.
5238 uint(iota) // iota value of type uint
5239 float32(2.718281828) // 2.718281828 of type float32
5240 complex128(1) // 1.0 + 0.0i of type complex128
5241 float32(0.49999999) // 0.5 of type float32
5242 float64(-1e-1000) // 0.0 of type float64
5243 string('x') // "x" of type string
5244 string(0x266c) // "♬" of type string
5245 MyString("foo" + "bar") // "foobar" of type MyString
5246 string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant
5247 (*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
5248 int(1.2) // illegal: 1.2 cannot be represented as an int
5249 string(65.0) // illegal: 65.0 is not an integer constant
5253 Converting a constant to a type parameter yields a <i>non-constant</i> value of that type,
5254 with the value represented as a value of the type argument that the type parameter
5255 is <a href="#Instantiations">instantiated</a> with.
5256 For example, given the function:
5260 func f[P ~float32|~float64]() {
5266 the conversion <code>P(1.1)</code> results in a non-constant value of type <code>P</code>
5267 and the value <code>1.1</code> is represented as a <code>float32</code> or a <code>float64</code>
5268 depending on the type argument for <code>f</code>.
5269 Accordingly, if <code>f</code> is instantiated with a <code>float32</code> type,
5270 the numeric value of the expression <code>P(1.1) + 1.2</code> will be computed
5271 with the same precision as the corresponding non-constant <code>float32</code>
5276 A non-constant value <code>x</code> can be converted to type <code>T</code>
5277 in any of these cases:
5282 <code>x</code> is <a href="#Assignability">assignable</a>
5286 ignoring struct tags (see below),
5287 <code>x</code>'s type and <code>T</code> are not
5288 <a href="#Type_parameter_declarations">type parameters</a> but have
5289 <a href="#Type_identity">identical</a> <a href="#Types">underlying types</a>.
5292 ignoring struct tags (see below),
5293 <code>x</code>'s type and <code>T</code> are pointer types
5294 that are not <a href="#Types">named types</a>,
5295 and their pointer base types are not type parameters but
5296 have identical underlying types.
5299 <code>x</code>'s type and <code>T</code> are both integer or floating
5303 <code>x</code>'s type and <code>T</code> are both complex types.
5306 <code>x</code> is an integer or a slice of bytes or runes
5307 and <code>T</code> is a string type.
5310 <code>x</code> is a string and <code>T</code> is a slice of bytes or runes.
5313 <code>x</code> is a slice, <code>T</code> is a pointer to an array,
5314 and the slice and array types have <a href="#Type_identity">identical</a> element types.
5319 Additionally, if <code>T</code> or <code>x</code>'s type <code>V</code> are type
5320 parameters, <code>x</code>
5321 can also be converted to type <code>T</code> if one of the following conditions applies:
5326 Both <code>V</code> and <code>T</code> are type parameters and a value of each
5327 type in <code>V</code>'s type set can be converted to each type in <code>T</code>'s
5331 Only <code>V</code> is a type parameter and a value of each
5332 type in <code>V</code>'s type set can be converted to <code>T</code>.
5335 Only <code>T</code> is a type parameter and <code>x</code> can be converted to each
5336 type in <code>T</code>'s type set.
5341 <a href="#Struct_types">Struct tags</a> are ignored when comparing struct types
5342 for identity for the purpose of conversion:
5346 type Person struct {
5355 Name string `json:"name"`
5357 Street string `json:"street"`
5358 City string `json:"city"`
5362 var person = (*Person)(data) // ignoring tags, the underlying types are identical
5366 Specific rules apply to (non-constant) conversions between numeric types or
5367 to and from a string type.
5368 These conversions may change the representation of <code>x</code>
5369 and incur a run-time cost.
5370 All other conversions only change the type but not the representation
5375 There is no linguistic mechanism to convert between pointers and integers.
5376 The package <a href="#Package_unsafe"><code>unsafe</code></a>
5377 implements this functionality under restricted circumstances.
5380 <h4>Conversions between numeric types</h4>
5383 For the conversion of non-constant numeric values, the following rules apply:
5388 When converting between <a href="#Numeric_types">integer types</a>, if the value is a signed integer, it is
5389 sign extended to implicit infinite precision; otherwise it is zero extended.
5390 It is then truncated to fit in the result type's size.
5391 For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>.
5392 The conversion always yields a valid value; there is no indication of overflow.
5395 When converting a <a href="#Numeric_types">floating-point number</a> to an integer, the fraction is discarded
5396 (truncation towards zero).
5399 When converting an integer or floating-point number to a floating-point type,
5400 or a <a href="#Numeric_types">complex number</a> to another complex type, the result value is rounded
5401 to the precision specified by the destination type.
5402 For instance, the value of a variable <code>x</code> of type <code>float32</code>
5403 may be stored using additional precision beyond that of an IEEE-754 32-bit number,
5404 but float32(x) represents the result of rounding <code>x</code>'s value to
5405 32-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits
5406 of precision, but <code>float32(x + 0.1)</code> does not.
5411 In all non-constant conversions involving floating-point or complex values,
5412 if the result type cannot represent the value the conversion
5413 succeeds but the result value is implementation-dependent.
5416 <h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4>
5420 Converting a signed or unsigned integer value to a string type yields a
5421 string containing the UTF-8 representation of the integer. Values outside
5422 the range of valid Unicode code points are converted to <code>"\uFFFD"</code>.
5426 string(-1) // "\ufffd" == "\xef\xbf\xbd"
5427 string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8"
5428 type MyString string
5429 MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5"
5434 Converting a slice of bytes to a string type yields
5435 a string whose successive bytes are the elements of the slice.
5438 string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
5439 string([]byte{}) // ""
5440 string([]byte(nil)) // ""
5443 string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
5448 Converting a slice of runes to a string type yields
5449 a string that is the concatenation of the individual rune values
5450 converted to strings.
5453 string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
5454 string([]rune{}) // ""
5455 string([]rune(nil)) // ""
5458 string(MyRunes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
5463 Converting a value of a string type to a slice of bytes type
5464 yields a slice whose successive elements are the bytes of the string.
5467 []byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
5468 []byte("") // []byte{}
5470 MyBytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
5475 Converting a value of a string type to a slice of runes type
5476 yields a slice containing the individual Unicode code points of the string.
5479 []rune(MyString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4}
5480 []rune("") // []rune{}
5482 MyRunes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4}
5487 <h4 id="Conversions_from_slice_to_array_pointer">Conversions from slice to array pointer</h4>
5490 Converting a slice to an array pointer yields a pointer to the underlying array of the slice.
5491 If the <a href="#Length_and_capacity">length</a> of the slice is less than the length of the array,
5492 a <a href="#Run_time_panics">run-time panic</a> occurs.
5496 s := make([]byte, 2, 4)
5497 s0 := (*[0]byte)(s) // s0 != nil
5498 s1 := (*[1]byte)(s[1:]) // &s1[0] == &s[1]
5499 s2 := (*[2]byte)(s) // &s2[0] == &s[0]
5500 s4 := (*[4]byte)(s) // panics: len([4]byte) > len(s)
5503 t0 := (*[0]string)(t) // t0 == nil
5504 t1 := (*[1]string)(t) // panics: len([1]string) > len(t)
5506 u := make([]byte, 0)
5507 u0 := (*[0]byte)(u) // u0 != nil
5510 <h3 id="Constant_expressions">Constant expressions</h3>
5513 Constant expressions may contain only <a href="#Constants">constant</a>
5514 operands and are evaluated at compile time.
5518 Untyped boolean, numeric, and string constants may be used as operands
5519 wherever it is legal to use an operand of boolean, numeric, or string type,
5524 A constant <a href="#Comparison_operators">comparison</a> always yields
5525 an untyped boolean constant. If the left operand of a constant
5526 <a href="#Operators">shift expression</a> is an untyped constant, the
5527 result is an integer constant; otherwise it is a constant of the same
5528 type as the left operand, which must be of
5529 <a href="#Numeric_types">integer type</a>.
5533 Any other operation on untyped constants results in an untyped constant of the
5534 same kind; that is, a boolean, integer, floating-point, complex, or string
5536 If the untyped operands of a binary operation (other than a shift) are of
5537 different kinds, the result is of the operand's kind that appears later in this
5538 list: integer, rune, floating-point, complex.
5539 For example, an untyped integer constant divided by an
5540 untyped complex constant yields an untyped complex constant.
5544 const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant)
5545 const b = 15 / 4 // b == 3 (untyped integer constant)
5546 const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant)
5547 const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division)
5548 const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division)
5549 const d = 1 << 3.0 // d == 8 (untyped integer constant)
5550 const e = 1.0 << 3 // e == 8 (untyped integer constant)
5551 const f = int32(1) << 33 // illegal (constant 8589934592 overflows int32)
5552 const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant)
5553 const h = "foo" > "bar" // h == true (untyped boolean constant)
5554 const j = true // j == true (untyped boolean constant)
5555 const k = 'w' + 1 // k == 'x' (untyped rune constant)
5556 const l = "hi" // l == "hi" (untyped string constant)
5557 const m = string(k) // m == "x" (type string)
5558 const Σ = 1 - 0.707i // (untyped complex constant)
5559 const Δ = Σ + 2.0e-4 // (untyped complex constant)
5560 const Φ = iota*1i - 1/1i // (untyped complex constant)
5564 Applying the built-in function <code>complex</code> to untyped
5565 integer, rune, or floating-point constants yields
5566 an untyped complex constant.
5570 const ic = complex(0, c) // ic == 3.75i (untyped complex constant)
5571 const iΘ = complex(0, Θ) // iΘ == 1i (type complex128)
5575 Constant expressions are always evaluated exactly; intermediate values and the
5576 constants themselves may require precision significantly larger than supported
5577 by any predeclared type in the language. The following are legal declarations:
5581 const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (untyped integer constant)
5582 const Four int8 = Huge >> 98 // Four == 4 (type int8)
5586 The divisor of a constant division or remainder operation must not be zero:
5590 3.14 / 0.0 // illegal: division by zero
5594 The values of <i>typed</i> constants must always be accurately
5595 <a href="#Representability">representable</a> by values
5596 of the constant type. The following constant expressions are illegal:
5600 uint(-1) // -1 cannot be represented as a uint
5601 int(3.14) // 3.14 cannot be represented as an int
5602 int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64
5603 Four * 300 // operand 300 cannot be represented as an int8 (type of Four)
5604 Four * 100 // product 400 cannot be represented as an int8 (type of Four)
5608 The mask used by the unary bitwise complement operator <code>^</code> matches
5609 the rule for non-constants: the mask is all 1s for unsigned constants
5610 and -1 for signed and untyped constants.
5614 ^1 // untyped integer constant, equal to -2
5615 uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8
5616 ^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)
5617 int8(^1) // same as int8(-2)
5618 ^int8(1) // same as -1 ^ int8(1) = -2
5622 Implementation restriction: A compiler may use rounding while
5623 computing untyped floating-point or complex constant expressions; see
5624 the implementation restriction in the section
5625 on <a href="#Constants">constants</a>. This rounding may cause a
5626 floating-point constant expression to be invalid in an integer
5627 context, even if it would be integral when calculated using infinite
5628 precision, and vice versa.
5632 <h3 id="Order_of_evaluation">Order of evaluation</h3>
5635 At package level, <a href="#Package_initialization">initialization dependencies</a>
5636 determine the evaluation order of individual initialization expressions in
5637 <a href="#Variable_declarations">variable declarations</a>.
5638 Otherwise, when evaluating the <a href="#Operands">operands</a> of an
5639 expression, assignment, or
5640 <a href="#Return_statements">return statement</a>,
5641 all function calls, method calls, and
5642 communication operations are evaluated in lexical left-to-right
5647 For example, in the (function-local) assignment
5650 y[f()], ok = g(h(), i()+x[j()], <-c), k()
5653 the function calls and communication happen in the order
5654 <code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>,
5655 <code><-c</code>, <code>g()</code>, and <code>k()</code>.
5656 However, the order of those events compared to the evaluation
5657 and indexing of <code>x</code> and the evaluation
5658 of <code>y</code> is not specified.
5663 f := func() int { a++; return a }
5664 x := []int{a, f()} // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified
5665 m := map[int]int{a: 1, a: 2} // m may be {2: 1} or {2: 2}: evaluation order between the two map assignments is not specified
5666 n := map[int]int{a: f()} // n may be {2: 3} or {3: 3}: evaluation order between the key and the value is not specified
5670 At package level, initialization dependencies override the left-to-right rule
5671 for individual initialization expressions, but not for operands within each
5676 var a, b, c = f() + v(), g(), sqr(u()) + v()
5678 func f() int { return c }
5679 func g() int { return a }
5680 func sqr(x int) int { return x*x }
5682 // functions u and v are independent of all other variables and functions
5686 The function calls happen in the order
5687 <code>u()</code>, <code>sqr()</code>, <code>v()</code>,
5688 <code>f()</code>, <code>v()</code>, and <code>g()</code>.
5692 Floating-point operations within a single expression are evaluated according to
5693 the associativity of the operators. Explicit parentheses affect the evaluation
5694 by overriding the default associativity.
5695 In the expression <code>x + (y + z)</code> the addition <code>y + z</code>
5696 is performed before adding <code>x</code>.
5699 <h2 id="Statements">Statements</h2>
5702 Statements control execution.
5707 Declaration | LabeledStmt | SimpleStmt |
5708 GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
5709 FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
5712 SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
5715 <h3 id="Terminating_statements">Terminating statements</h3>
5718 A <i>terminating statement</i> interrupts the regular flow of control in
5719 a <a href="#Blocks">block</a>. The following statements are terminating:
5724 A <a href="#Return_statements">"return"</a> or
5725 <a href="#Goto_statements">"goto"</a> statement.
5726 <!-- ul below only for regular layout -->
5731 A call to the built-in function
5732 <a href="#Handling_panics"><code>panic</code></a>.
5733 <!-- ul below only for regular layout -->
5738 A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement.
5739 <!-- ul below only for regular layout -->
5744 An <a href="#If_statements">"if" statement</a> in which:
5746 <li>the "else" branch is present, and</li>
5747 <li>both branches are terminating statements.</li>
5752 A <a href="#For_statements">"for" statement</a> in which:
5754 <li>there are no "break" statements referring to the "for" statement, and</li>
5755 <li>the loop condition is absent, and</li>
5756 <li>the "for" statement does not use a range clause.</li>
5761 A <a href="#Switch_statements">"switch" statement</a> in which:
5763 <li>there are no "break" statements referring to the "switch" statement,</li>
5764 <li>there is a default case, and</li>
5765 <li>the statement lists in each case, including the default, end in a terminating
5766 statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough"
5772 A <a href="#Select_statements">"select" statement</a> in which:
5774 <li>there are no "break" statements referring to the "select" statement, and</li>
5775 <li>the statement lists in each case, including the default if present,
5776 end in a terminating statement.</li>
5781 A <a href="#Labeled_statements">labeled statement</a> labeling
5782 a terminating statement.
5787 All other statements are not terminating.
5791 A <a href="#Blocks">statement list</a> ends in a terminating statement if the list
5792 is not empty and its final non-empty statement is terminating.
5796 <h3 id="Empty_statements">Empty statements</h3>
5799 The empty statement does nothing.
5807 <h3 id="Labeled_statements">Labeled statements</h3>
5810 A labeled statement may be the target of a <code>goto</code>,
5811 <code>break</code> or <code>continue</code> statement.
5815 LabeledStmt = Label ":" Statement .
5816 Label = identifier .
5820 Error: log.Panic("error encountered")
5824 <h3 id="Expression_statements">Expression statements</h3>
5827 With the exception of specific built-in functions,
5828 function and method <a href="#Calls">calls</a> and
5829 <a href="#Receive_operator">receive operations</a>
5830 can appear in statement context. Such statements may be parenthesized.
5834 ExpressionStmt = Expression .
5838 The following built-in functions are not permitted in statement context:
5842 append cap complex imag len make new real
5843 unsafe.Add unsafe.Alignof unsafe.Offsetof unsafe.Sizeof unsafe.Slice
5851 len("foo") // illegal if len is the built-in function
5855 <h3 id="Send_statements">Send statements</h3>
5858 A send statement sends a value on a channel.
5859 The channel expression's <a href="#Core_types">core type</a>
5860 must be a <a href="#Channel_types">channel</a>,
5861 the channel direction must permit send operations,
5862 and the type of the value to be sent must be <a href="#Assignability">assignable</a>
5863 to the channel's element type.
5867 SendStmt = Channel "<-" Expression .
5868 Channel = Expression .
5872 Both the channel and the value expression are evaluated before communication
5873 begins. Communication blocks until the send can proceed.
5874 A send on an unbuffered channel can proceed if a receiver is ready.
5875 A send on a buffered channel can proceed if there is room in the buffer.
5876 A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>.
5877 A send on a <code>nil</code> channel blocks forever.
5881 ch <- 3 // send value 3 to channel ch
5885 <h3 id="IncDec_statements">IncDec statements</h3>
5888 The "++" and "--" statements increment or decrement their operands
5889 by the untyped <a href="#Constants">constant</a> <code>1</code>.
5890 As with an assignment, the operand must be <a href="#Address_operators">addressable</a>
5891 or a map index expression.
5895 IncDecStmt = Expression ( "++" | "--" ) .
5899 The following <a href="#Assignments">assignment statements</a> are semantically
5903 <pre class="grammar">
5904 IncDec statement Assignment
5910 <h3 id="Assignments">Assignments</h3>
5913 Assignment = ExpressionList assign_op ExpressionList .
5915 assign_op = [ add_op | mul_op ] "=" .
5919 Each left-hand side operand must be <a href="#Address_operators">addressable</a>,
5920 a map index expression, or (for <code>=</code> assignments only) the
5921 <a href="#Blank_identifier">blank identifier</a>.
5922 Operands may be parenthesized.
5929 (k) = <-ch // same as: k = <-ch
5933 An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code>
5934 <code>y</code> where <i>op</i> is a binary <a href="#Arithmetic_operators">arithmetic operator</a>
5935 is equivalent to <code>x</code> <code>=</code> <code>x</code> <i>op</i>
5936 <code>(y)</code> but evaluates <code>x</code>
5937 only once. The <i>op</i><code>=</code> construct is a single token.
5938 In assignment operations, both the left- and right-hand expression lists
5939 must contain exactly one single-valued expression, and the left-hand
5940 expression must not be the blank identifier.
5945 i &^= 1<<n
5949 A tuple assignment assigns the individual elements of a multi-valued
5950 operation to a list of variables. There are two forms. In the
5951 first, the right hand operand is a single multi-valued expression
5952 such as a function call, a <a href="#Channel_types">channel</a> or
5953 <a href="#Map_types">map</a> operation, or a <a href="#Type_assertions">type assertion</a>.
5954 The number of operands on the left
5955 hand side must match the number of values. For instance, if
5956 <code>f</code> is a function returning two values,
5964 assigns the first value to <code>x</code> and the second to <code>y</code>.
5965 In the second form, the number of operands on the left must equal the number
5966 of expressions on the right, each of which must be single-valued, and the
5967 <i>n</i>th expression on the right is assigned to the <i>n</i>th
5968 operand on the left:
5972 one, two, three = '一', '二', '三'
5976 The <a href="#Blank_identifier">blank identifier</a> provides a way to
5977 ignore right-hand side values in an assignment:
5981 _ = x // evaluate x but ignore it
5982 x, _ = f() // evaluate f() but ignore second result value
5986 The assignment proceeds in two phases.
5987 First, the operands of <a href="#Index_expressions">index expressions</a>
5988 and <a href="#Address_operators">pointer indirections</a>
5989 (including implicit pointer indirections in <a href="#Selectors">selectors</a>)
5990 on the left and the expressions on the right are all
5991 <a href="#Order_of_evaluation">evaluated in the usual order</a>.
5992 Second, the assignments are carried out in left-to-right order.
5996 a, b = b, a // exchange a and b
6000 i, x[i] = 1, 2 // set i = 1, x[0] = 2
6003 x[i], i = 2, 1 // set x[0] = 2, i = 1
6005 x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end)
6007 x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5.
6009 type Point struct { x, y int }
6011 x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7
6015 for i, x[i] = range x { // set i, x[2] = 0, x[0]
6018 // after this loop, i == 0 and x == []int{3, 5, 3}
6022 In assignments, each value must be <a href="#Assignability">assignable</a>
6023 to the type of the operand to which it is assigned, with the following special cases:
6028 Any typed value may be assigned to the blank identifier.
6032 If an untyped constant
6033 is assigned to a variable of interface type or the blank identifier,
6034 the constant is first implicitly <a href="#Conversions">converted</a> to its
6035 <a href="#Constants">default type</a>.
6039 If an untyped boolean value is assigned to a variable of interface type or
6040 the blank identifier, it is first implicitly converted to type <code>bool</code>.
6044 <h3 id="If_statements">If statements</h3>
6047 "If" statements specify the conditional execution of two branches
6048 according to the value of a boolean expression. If the expression
6049 evaluates to true, the "if" branch is executed, otherwise, if
6050 present, the "else" branch is executed.
6054 IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
6064 The expression may be preceded by a simple statement, which
6065 executes before the expression is evaluated.
6069 if x := f(); x < y {
6071 } else if x > z {
6079 <h3 id="Switch_statements">Switch statements</h3>
6082 "Switch" statements provide multi-way execution.
6083 An expression or type is compared to the "cases"
6084 inside the "switch" to determine which branch
6089 SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
6093 There are two forms: expression switches and type switches.
6094 In an expression switch, the cases contain expressions that are compared
6095 against the value of the switch expression.
6096 In a type switch, the cases contain types that are compared against the
6097 type of a specially annotated switch expression.
6098 The switch expression is evaluated exactly once in a switch statement.
6101 <h4 id="Expression_switches">Expression switches</h4>
6104 In an expression switch,
6105 the switch expression is evaluated and
6106 the case expressions, which need not be constants,
6107 are evaluated left-to-right and top-to-bottom; the first one that equals the
6109 triggers execution of the statements of the associated case;
6110 the other cases are skipped.
6111 If no case matches and there is a "default" case,
6112 its statements are executed.
6113 There can be at most one default case and it may appear anywhere in the
6115 A missing switch expression is equivalent to the boolean value
6120 ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
6121 ExprCaseClause = ExprSwitchCase ":" StatementList .
6122 ExprSwitchCase = "case" ExpressionList | "default" .
6126 If the switch expression evaluates to an untyped constant, it is first implicitly
6127 <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>.
6128 The predeclared untyped value <code>nil</code> cannot be used as a switch expression.
6129 The switch expression type must be <a href="#Comparison_operators">comparable</a>.
6133 If a case expression is untyped, it is first implicitly <a href="#Conversions">converted</a>
6134 to the type of the switch expression.
6135 For each (possibly converted) case expression <code>x</code> and the value <code>t</code>
6136 of the switch expression, <code>x == t</code> must be a valid <a href="#Comparison_operators">comparison</a>.
6140 In other words, the switch expression is treated as if it were used to declare and
6141 initialize a temporary variable <code>t</code> without explicit type; it is that
6142 value of <code>t</code> against which each case expression <code>x</code> is tested
6147 In a case or default clause, the last non-empty statement
6148 may be a (possibly <a href="#Labeled_statements">labeled</a>)
6149 <a href="#Fallthrough_statements">"fallthrough" statement</a> to
6150 indicate that control should flow from the end of this clause to
6151 the first statement of the next clause.
6152 Otherwise control flows to the end of the "switch" statement.
6153 A "fallthrough" statement may appear as the last statement of all
6154 but the last clause of an expression switch.
6158 The switch expression may be preceded by a simple statement, which
6159 executes before the expression is evaluated.
6165 case 0, 1, 2, 3: s1()
6166 case 4, 5, 6, 7: s2()
6169 switch x := f(); { // missing switch expression means "true"
6170 case x < 0: return -x
6182 Implementation restriction: A compiler may disallow multiple case
6183 expressions evaluating to the same constant.
6184 For instance, the current compilers disallow duplicate integer,
6185 floating point, or string constants in case expressions.
6188 <h4 id="Type_switches">Type switches</h4>
6191 A type switch compares types rather than values. It is otherwise similar
6192 to an expression switch. It is marked by a special switch expression that
6193 has the form of a <a href="#Type_assertions">type assertion</a>
6194 using the keyword <code>type</code> rather than an actual type:
6204 Cases then match actual types <code>T</code> against the dynamic type of the
6205 expression <code>x</code>. As with type assertions, <code>x</code> must be of
6206 <a href="#Interface_types">interface type</a>, but not a
6207 <a href="#Type_parameter_declarations">type parameter</a>, and each non-interface type
6208 <code>T</code> listed in a case must implement the type of <code>x</code>.
6209 The types listed in the cases of a type switch must all be
6210 <a href="#Type_identity">different</a>.
6214 TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
6215 TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
6216 TypeCaseClause = TypeSwitchCase ":" StatementList .
6217 TypeSwitchCase = "case" TypeList | "default" .
6221 The TypeSwitchGuard may include a
6222 <a href="#Short_variable_declarations">short variable declaration</a>.
6223 When that form is used, the variable is declared at the end of the
6224 TypeSwitchCase in the <a href="#Blocks">implicit block</a> of each clause.
6225 In clauses with a case listing exactly one type, the variable
6226 has that type; otherwise, the variable has the type of the expression
6227 in the TypeSwitchGuard.
6231 Instead of a type, a case may use the predeclared identifier
6232 <a href="#Predeclared_identifiers"><code>nil</code></a>;
6233 that case is selected when the expression in the TypeSwitchGuard
6234 is a <code>nil</code> interface value.
6235 There may be at most one <code>nil</code> case.
6239 Given an expression <code>x</code> of type <code>interface{}</code>,
6240 the following type switch:
6244 switch i := x.(type) {
6246 printString("x is nil") // type of i is type of x (interface{})
6248 printInt(i) // type of i is int
6250 printFloat64(i) // type of i is float64
6251 case func(int) float64:
6252 printFunction(i) // type of i is func(int) float64
6254 printString("type is bool or string") // type of i is type of x (interface{})
6256 printString("don't know the type") // type of i is type of x (interface{})
6265 v := x // x is evaluated exactly once
6267 i := v // type of i is type of x (interface{})
6268 printString("x is nil")
6269 } else if i, isInt := v.(int); isInt {
6270 printInt(i) // type of i is int
6271 } else if i, isFloat64 := v.(float64); isFloat64 {
6272 printFloat64(i) // type of i is float64
6273 } else if i, isFunc := v.(func(int) float64); isFunc {
6274 printFunction(i) // type of i is func(int) float64
6276 _, isBool := v.(bool)
6277 _, isString := v.(string)
6278 if isBool || isString {
6279 i := v // type of i is type of x (interface{})
6280 printString("type is bool or string")
6282 i := v // type of i is type of x (interface{})
6283 printString("don't know the type")
6289 A <a href="#Type_parameter_declarations">type parameter</a> or a <a href="#Type_declarations">generic type</a>
6290 may be used as a type in a case. If upon <a href="#Instantiations">instantiation</a> that type turns
6291 out to duplicate another entry in the switch, the first matching case is chosen.
6295 func f[P any](x any) int {
6310 var v1 = f[string]("foo") // v1 == 0
6311 var v2 = f[byte]([]byte{}) // v2 == 2
6315 The type switch guard may be preceded by a simple statement, which
6316 executes before the guard is evaluated.
6320 The "fallthrough" statement is not permitted in a type switch.
6323 <h3 id="For_statements">For statements</h3>
6326 A "for" statement specifies repeated execution of a block. There are three forms:
6327 The iteration may be controlled by a single condition, a "for" clause, or a "range" clause.
6331 ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
6332 Condition = Expression .
6335 <h4 id="For_condition">For statements with single condition</h4>
6338 In its simplest form, a "for" statement specifies the repeated execution of
6339 a block as long as a boolean condition evaluates to true.
6340 The condition is evaluated before each iteration.
6341 If the condition is absent, it is equivalent to the boolean value
6351 <h4 id="For_clause">For statements with <code>for</code> clause</h4>
6354 A "for" statement with a ForClause is also controlled by its condition, but
6355 additionally it may specify an <i>init</i>
6356 and a <i>post</i> statement, such as an assignment,
6357 an increment or decrement statement. The init statement may be a
6358 <a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not.
6359 Variables declared by the init statement are re-used in each iteration.
6363 ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
6364 InitStmt = SimpleStmt .
6365 PostStmt = SimpleStmt .
6369 for i := 0; i < 10; i++ {
6375 If non-empty, the init statement is executed once before evaluating the
6376 condition for the first iteration;
6377 the post statement is executed after each execution of the block (and
6378 only if the block was executed).
6379 Any element of the ForClause may be empty but the
6380 <a href="#Semicolons">semicolons</a> are
6381 required unless there is only a condition.
6382 If the condition is absent, it is equivalent to the boolean value
6387 for cond { S() } is the same as for ; cond ; { S() }
6388 for { S() } is the same as for true { S() }
6391 <h4 id="For_range">For statements with <code>range</code> clause</h4>
6394 A "for" statement with a "range" clause
6395 iterates through all entries of an array, slice, string or map,
6396 or values received on a channel. For each entry it assigns <i>iteration values</i>
6397 to corresponding <i>iteration variables</i> if present and then executes the block.
6401 RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .
6405 The expression on the right in the "range" clause is called the <i>range expression</i>,
6406 its <a href="#Core_types">core type</a> must be
6407 an array, pointer to an array, slice, string, map, or channel permitting
6408 <a href="#Receive_operator">receive operations</a>.
6409 As with an assignment, if present the operands on the left must be
6410 <a href="#Address_operators">addressable</a> or map index expressions; they
6411 denote the iteration variables. If the range expression is a channel, at most
6412 one iteration variable is permitted, otherwise there may be up to two.
6413 If the last iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
6414 the range clause is equivalent to the same clause without that identifier.
6418 The range expression <code>x</code> is evaluated once before beginning the loop,
6419 with one exception: if at most one iteration variable is present and
6420 <code>len(x)</code> is <a href="#Length_and_capacity">constant</a>,
6421 the range expression is not evaluated.
6425 Function calls on the left are evaluated once per iteration.
6426 For each iteration, iteration values are produced as follows
6427 if the respective iteration variables are present:
6430 <pre class="grammar">
6431 Range expression 1st value 2nd value
6433 array or slice a [n]E, *[n]E, or []E index i int a[i] E
6434 string s string type index i int see below rune
6435 map m map[K]V key k K m[k] V
6436 channel c chan E, <-chan E element e E
6441 For an array, pointer to array, or slice value <code>a</code>, the index iteration
6442 values are produced in increasing order, starting at element index 0.
6443 If at most one iteration variable is present, the range loop produces
6444 iteration values from 0 up to <code>len(a)-1</code> and does not index into the array
6445 or slice itself. For a <code>nil</code> slice, the number of iterations is 0.
6449 For a string value, the "range" clause iterates over the Unicode code points
6450 in the string starting at byte index 0. On successive iterations, the index value will be the
6451 index of the first byte of successive UTF-8-encoded code points in the string,
6452 and the second value, of type <code>rune</code>, will be the value of
6453 the corresponding code point. If the iteration encounters an invalid
6454 UTF-8 sequence, the second value will be <code>0xFFFD</code>,
6455 the Unicode replacement character, and the next iteration will advance
6456 a single byte in the string.
6460 The iteration order over maps is not specified
6461 and is not guaranteed to be the same from one iteration to the next.
6462 If a map entry that has not yet been reached is removed during iteration,
6463 the corresponding iteration value will not be produced. If a map entry is
6464 created during iteration, that entry may be produced during the iteration or
6465 may be skipped. The choice may vary for each entry created and from one
6466 iteration to the next.
6467 If the map is <code>nil</code>, the number of iterations is 0.
6471 For channels, the iteration values produced are the successive values sent on
6472 the channel until the channel is <a href="#Close">closed</a>. If the channel
6473 is <code>nil</code>, the range expression blocks forever.
6478 The iteration values are assigned to the respective
6479 iteration variables as in an <a href="#Assignments">assignment statement</a>.
6483 The iteration variables may be declared by the "range" clause using a form of
6484 <a href="#Short_variable_declarations">short variable declaration</a>
6486 In this case their types are set to the types of the respective iteration values
6487 and their <a href="#Declarations_and_scope">scope</a> is the block of the "for"
6488 statement; they are re-used in each iteration.
6489 If the iteration variables are declared outside the "for" statement,
6490 after execution their values will be those of the last iteration.
6494 var testdata *struct {
6497 for i, _ := range testdata.a {
6498 // testdata.a is never evaluated; len(testdata.a) is constant
6499 // i ranges from 0 to 6
6504 for i, s := range a {
6506 // type of s is string
6512 var val interface{} // element type of m is assignable to val
6513 m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}
6514 for key, val = range m {
6517 // key == last map key encountered in iteration
6520 var ch chan Work = producer()
6530 <h3 id="Go_statements">Go statements</h3>
6533 A "go" statement starts the execution of a function call
6534 as an independent concurrent thread of control, or <i>goroutine</i>,
6535 within the same address space.
6539 GoStmt = "go" Expression .
6543 The expression must be a function or method call; it cannot be parenthesized.
6544 Calls of built-in functions are restricted as for
6545 <a href="#Expression_statements">expression statements</a>.
6549 The function value and parameters are
6550 <a href="#Calls">evaluated as usual</a>
6551 in the calling goroutine, but
6552 unlike with a regular call, program execution does not wait
6553 for the invoked function to complete.
6554 Instead, the function begins executing independently
6556 When the function terminates, its goroutine also terminates.
6557 If the function has any return values, they are discarded when the
6563 go func(ch chan<- bool) { for { sleep(10); ch <- true }} (c)
6567 <h3 id="Select_statements">Select statements</h3>
6570 A "select" statement chooses which of a set of possible
6571 <a href="#Send_statements">send</a> or
6572 <a href="#Receive_operator">receive</a>
6573 operations will proceed.
6574 It looks similar to a
6575 <a href="#Switch_statements">"switch"</a> statement but with the
6576 cases all referring to communication operations.
6580 SelectStmt = "select" "{" { CommClause } "}" .
6581 CommClause = CommCase ":" StatementList .
6582 CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
6583 RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
6584 RecvExpr = Expression .
6588 A case with a RecvStmt may assign the result of a RecvExpr to one or
6589 two variables, which may be declared using a
6590 <a href="#Short_variable_declarations">short variable declaration</a>.
6591 The RecvExpr must be a (possibly parenthesized) receive operation.
6592 There can be at most one default case and it may appear anywhere
6593 in the list of cases.
6597 Execution of a "select" statement proceeds in several steps:
6602 For all the cases in the statement, the channel operands of receive operations
6603 and the channel and right-hand-side expressions of send statements are
6604 evaluated exactly once, in source order, upon entering the "select" statement.
6605 The result is a set of channels to receive from or send to,
6606 and the corresponding values to send.
6607 Any side effects in that evaluation will occur irrespective of which (if any)
6608 communication operation is selected to proceed.
6609 Expressions on the left-hand side of a RecvStmt with a short variable declaration
6610 or assignment are not yet evaluated.
6614 If one or more of the communications can proceed,
6615 a single one that can proceed is chosen via a uniform pseudo-random selection.
6616 Otherwise, if there is a default case, that case is chosen.
6617 If there is no default case, the "select" statement blocks until
6618 at least one of the communications can proceed.
6622 Unless the selected case is the default case, the respective communication
6623 operation is executed.
6627 If the selected case is a RecvStmt with a short variable declaration or
6628 an assignment, the left-hand side expressions are evaluated and the
6629 received value (or values) are assigned.
6633 The statement list of the selected case is executed.
6638 Since communication on <code>nil</code> channels can never proceed,
6639 a select with only <code>nil</code> channels and no default case blocks forever.
6644 var c, c1, c2, c3, c4 chan int
6648 print("received ", i1, " from c1\n")
6650 print("sent ", i2, " to c2\n")
6651 case i3, ok := (<-c3): // same as: i3, ok := <-c3
6653 print("received ", i3, " from c3\n")
6655 print("c3 is closed\n")
6657 case a[f()] = <-c4:
6659 // case t := <-c4
6662 print("no communication\n")
6665 for { // send random sequence of bits to c
6667 case c <- 0: // note: no statement, no fallthrough, no folding of cases
6672 select {} // block forever
6676 <h3 id="Return_statements">Return statements</h3>
6679 A "return" statement in a function <code>F</code> terminates the execution
6680 of <code>F</code>, and optionally provides one or more result values.
6681 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
6682 are executed before <code>F</code> returns to its caller.
6686 ReturnStmt = "return" [ ExpressionList ] .
6690 In a function without a result type, a "return" statement must not
6691 specify any result values.
6700 There are three ways to return values from a function with a result
6705 <li>The return value or values may be explicitly listed
6706 in the "return" statement. Each expression must be single-valued
6707 and <a href="#Assignability">assignable</a>
6708 to the corresponding element of the function's result type.
6710 func simpleF() int {
6714 func complexF1() (re float64, im float64) {
6719 <li>The expression list in the "return" statement may be a single
6720 call to a multi-valued function. The effect is as if each value
6721 returned from that function were assigned to a temporary
6722 variable with the type of the respective value, followed by a
6723 "return" statement listing these variables, at which point the
6724 rules of the previous case apply.
6726 func complexF2() (re float64, im float64) {
6731 <li>The expression list may be empty if the function's result
6732 type specifies names for its <a href="#Function_types">result parameters</a>.
6733 The result parameters act as ordinary local variables
6734 and the function may assign values to them as necessary.
6735 The "return" statement returns the values of these variables.
6737 func complexF3() (re float64, im float64) {
6743 func (devnull) Write(p []byte) (n int, _ error) {
6752 Regardless of how they are declared, all the result values are initialized to
6753 the <a href="#The_zero_value">zero values</a> for their type upon entry to the
6754 function. A "return" statement that specifies results sets the result parameters before
6755 any deferred functions are executed.
6759 Implementation restriction: A compiler may disallow an empty expression list
6760 in a "return" statement if a different entity (constant, type, or variable)
6761 with the same name as a result parameter is in
6762 <a href="#Declarations_and_scope">scope</a> at the place of the return.
6766 func f(n int) (res int, err error) {
6767 if _, err := f(n-1); err != nil {
6768 return // invalid return statement: err is shadowed
6774 <h3 id="Break_statements">Break statements</h3>
6777 A "break" statement terminates execution of the innermost
6778 <a href="#For_statements">"for"</a>,
6779 <a href="#Switch_statements">"switch"</a>, or
6780 <a href="#Select_statements">"select"</a> statement
6781 within the same function.
6785 BreakStmt = "break" [ Label ] .
6789 If there is a label, it must be that of an enclosing
6790 "for", "switch", or "select" statement,
6791 and that is the one whose execution terminates.
6796 for i = 0; i < n; i++ {
6797 for j = 0; j < m; j++ {
6810 <h3 id="Continue_statements">Continue statements</h3>
6813 A "continue" statement begins the next iteration of the
6814 innermost enclosing <a href="#For_statements">"for" loop</a>
6815 by advancing control to the end of the loop block.
6816 The "for" loop must be within the same function.
6820 ContinueStmt = "continue" [ Label ] .
6824 If there is a label, it must be that of an enclosing
6825 "for" statement, and that is the one whose execution
6831 for y, row := range rows {
6832 for x, data := range row {
6833 if data == endOfRow {
6836 row[x] = data + bias(x, y)
6841 <h3 id="Goto_statements">Goto statements</h3>
6844 A "goto" statement transfers control to the statement with the corresponding label
6845 within the same function.
6849 GotoStmt = "goto" Label .
6857 Executing the "goto" statement must not cause any variables to come into
6858 <a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto.
6859 For instance, this example:
6869 is erroneous because the jump to label <code>L</code> skips
6870 the creation of <code>v</code>.
6874 A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block.
6875 For instance, this example:
6892 is erroneous because the label <code>L1</code> is inside
6893 the "for" statement's block but the <code>goto</code> is not.
6896 <h3 id="Fallthrough_statements">Fallthrough statements</h3>
6899 A "fallthrough" statement transfers control to the first statement of the
6900 next case clause in an <a href="#Expression_switches">expression "switch" statement</a>.
6901 It may be used only as the final non-empty statement in such a clause.
6905 FallthroughStmt = "fallthrough" .
6909 <h3 id="Defer_statements">Defer statements</h3>
6912 A "defer" statement invokes a function whose execution is deferred
6913 to the moment the surrounding function returns, either because the
6914 surrounding function executed a <a href="#Return_statements">return statement</a>,
6915 reached the end of its <a href="#Function_declarations">function body</a>,
6916 or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>.
6920 DeferStmt = "defer" Expression .
6924 The expression must be a function or method call; it cannot be parenthesized.
6925 Calls of built-in functions are restricted as for
6926 <a href="#Expression_statements">expression statements</a>.
6930 Each time a "defer" statement
6931 executes, the function value and parameters to the call are
6932 <a href="#Calls">evaluated as usual</a>
6933 and saved anew but the actual function is not invoked.
6934 Instead, deferred functions are invoked immediately before
6935 the surrounding function returns, in the reverse order
6936 they were deferred. That is, if the surrounding function
6937 returns through an explicit <a href="#Return_statements">return statement</a>,
6938 deferred functions are executed <i>after</i> any result parameters are set
6939 by that return statement but <i>before</i> the function returns to its caller.
6940 If a deferred function value evaluates
6941 to <code>nil</code>, execution <a href="#Handling_panics">panics</a>
6942 when the function is invoked, not when the "defer" statement is executed.
6946 For instance, if the deferred function is
6947 a <a href="#Function_literals">function literal</a> and the surrounding
6948 function has <a href="#Function_types">named result parameters</a> that
6949 are in scope within the literal, the deferred function may access and modify
6950 the result parameters before they are returned.
6951 If the deferred function has any return values, they are discarded when
6952 the function completes.
6953 (See also the section on <a href="#Handling_panics">handling panics</a>.)
6958 defer unlock(l) // unlocking happens before surrounding function returns
6960 // prints 3 2 1 0 before surrounding function returns
6961 for i := 0; i <= 3; i++ {
6966 func f() (result int) {
6968 // result is accessed after it was set to 6 by the return statement
6975 <h2 id="Built-in_functions">Built-in functions</h2>
6978 Built-in functions are
6979 <a href="#Predeclared_identifiers">predeclared</a>.
6980 They are called like any other function but some of them
6981 accept a type instead of an expression as the first argument.
6985 The built-in functions do not have standard Go types,
6986 so they can only appear in <a href="#Calls">call expressions</a>;
6987 they cannot be used as function values.
6990 <h3 id="Close">Close</h3>
6993 For an argument <code>ch</code> with a <a href="#Core_types">core type</a>
6994 that is a <a href="#Channel_types">channel</a>, the built-in function <code>close</code>
6995 records that no more values will be sent on the channel.
6996 It is an error if <code>ch</code> is a receive-only channel.
6997 Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>.
6998 Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>.
6999 After calling <code>close</code>, and after any previously
7000 sent values have been received, receive operations will return
7001 the zero value for the channel's type without blocking.
7002 The multi-valued <a href="#Receive_operator">receive operation</a>
7003 returns a received value along with an indication of whether the channel is closed.
7006 <h3 id="Length_and_capacity">Length and capacity</h3>
7009 The built-in functions <code>len</code> and <code>cap</code> take arguments
7010 of various types and return a result of type <code>int</code>.
7011 The implementation guarantees that the result always fits into an <code>int</code>.
7014 <pre class="grammar">
7015 Call Argument type Result
7017 len(s) string type string length in bytes
7018 [n]T, *[n]T array length (== n)
7020 map[K]T map length (number of defined keys)
7021 chan T number of elements queued in channel buffer
7022 type parameter see below
7024 cap(s) [n]T, *[n]T array length (== n)
7026 chan T channel buffer capacity
7027 type parameter see below
7031 If the argument type is a <a href="#Type_parameter_declarations">type parameter</a> <code>P</code>,
7032 the call <code>len(e)</code> (or <code>cap(e)</code> respectively) must be valid for
7033 each type in <code>P</code>'s type set.
7034 The result is the length (or capacity, respectively) of the argument whose type
7035 corresponds to the type argument with which <code>P</code> was
7036 <a href="#Instantiations">instantiated</a>.
7040 The capacity of a slice is the number of elements for which there is
7041 space allocated in the underlying array.
7042 At any time the following relationship holds:
7046 0 <= len(s) <= cap(s)
7050 The length of a <code>nil</code> slice, map or channel is 0.
7051 The capacity of a <code>nil</code> slice or channel is 0.
7055 The expression <code>len(s)</code> is <a href="#Constants">constant</a> if
7056 <code>s</code> is a string constant. The expressions <code>len(s)</code> and
7057 <code>cap(s)</code> are constants if the type of <code>s</code> is an array
7058 or pointer to an array and the expression <code>s</code> does not contain
7059 <a href="#Receive_operator">channel receives</a> or (non-constant)
7060 <a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated.
7061 Otherwise, invocations of <code>len</code> and <code>cap</code> are not
7062 constant and <code>s</code> is evaluated.
7067 c1 = imag(2i) // imag(2i) = 2.0 is a constant
7068 c2 = len([10]float64{2}) // [10]float64{2} contains no function calls
7069 c3 = len([10]float64{c1}) // [10]float64{c1} contains no function calls
7070 c4 = len([10]float64{imag(2i)}) // imag(2i) is a constant and no function call is issued
7071 c5 = len([10]float64{imag(z)}) // invalid: imag(z) is a (non-constant) function call
7076 <h3 id="Allocation">Allocation</h3>
7079 The built-in function <code>new</code> takes a type <code>T</code>,
7080 allocates storage for a <a href="#Variables">variable</a> of that type
7081 at run time, and returns a value of type <code>*T</code>
7082 <a href="#Pointer_types">pointing</a> to it.
7083 The variable is initialized as described in the section on
7084 <a href="#The_zero_value">initial values</a>.
7087 <pre class="grammar">
7096 type S struct { a int; b float64 }
7101 allocates storage for a variable of type <code>S</code>,
7102 initializes it (<code>a=0</code>, <code>b=0.0</code>),
7103 and returns a value of type <code>*S</code> containing the address
7107 <h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3>
7110 The built-in function <code>make</code> takes a type <code>T</code>,
7111 optionally followed by a type-specific list of expressions.
7112 The <a href="#Core_types">core type</a> of <code>T</code> must
7113 be a slice, map or channel.
7114 It returns a value of type <code>T</code> (not <code>*T</code>).
7115 The memory is initialized as described in the section on
7116 <a href="#The_zero_value">initial values</a>.
7119 <pre class="grammar">
7120 Call Core type Result
7122 make(T, n) slice slice of type T with length n and capacity n
7123 make(T, n, m) slice slice of type T with length n and capacity m
7125 make(T) map map of type T
7126 make(T, n) map map of type T with initial space for approximately n elements
7128 make(T) channel unbuffered channel of type T
7129 make(T, n) channel buffered channel of type T, buffer size n
7134 Each of the size arguments <code>n</code> and <code>m</code> must be of <a href="#Numeric_types">integer type</a>,
7135 have a <a href="#Interface_types">type set</a> containing only integer types,
7136 or be an untyped <a href="#Constants">constant</a>.
7137 A constant size argument must be non-negative and <a href="#Representability">representable</a>
7138 by a value of type <code>int</code>; if it is an untyped constant it is given type <code>int</code>.
7139 If both <code>n</code> and <code>m</code> are provided and are constant, then
7140 <code>n</code> must be no larger than <code>m</code>.
7141 If <code>n</code> is negative or larger than <code>m</code> at run time,
7142 a <a href="#Run_time_panics">run-time panic</a> occurs.
7146 s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100
7147 s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000
7148 s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type int
7149 s := make([]int, 10, 0) // illegal: len(s) > cap(s)
7150 c := make(chan int, 10) // channel with a buffer size of 10
7151 m := make(map[string]int, 100) // map with initial space for approximately 100 elements
7155 Calling <code>make</code> with a map type and size hint <code>n</code> will
7156 create a map with initial space to hold <code>n</code> map elements.
7157 The precise behavior is implementation-dependent.
7161 <h3 id="Appending_and_copying_slices">Appending to and copying slices</h3>
7164 The built-in functions <code>append</code> and <code>copy</code> assist in
7165 common slice operations.
7166 For both functions, the result is independent of whether the memory referenced
7167 by the arguments overlaps.
7171 The <a href="#Function_types">variadic</a> function <code>append</code>
7172 appends zero or more values <code>x</code> to a slice <code>s</code>
7173 and returns the resulting slice of the same type as <code>s</code>.
7174 The <a href="#Core_types">core type</a> of <code>s</code> must be a slice
7175 of type <code>[]E</code>.
7176 The values <code>x</code> are passed to a parameter of type <code>...E</code>
7177 and the respective <a href="#Passing_arguments_to_..._parameters">parameter
7178 passing rules</a> apply.
7179 As a special case, if the core type of <code>s</code> is <code>[]byte</code>,
7180 <code>append</code> also accepts a second argument with core type <code>string</code>
7181 followed by <code>...</code>. This form appends the bytes of the string.
7184 <pre class="grammar">
7185 append(s S, x ...E) S // core type of S is []E
7189 If the capacity of <code>s</code> is not large enough to fit the additional
7190 values, <code>append</code> allocates a new, sufficiently large underlying
7191 array that fits both the existing slice elements and the additional values.
7192 Otherwise, <code>append</code> re-uses the underlying array.
7197 s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2}
7198 s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7}
7199 s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
7200 s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
7203 t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"}
7206 b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' }
7210 The function <code>copy</code> copies slice elements from
7211 a source <code>src</code> to a destination <code>dst</code> and returns the
7212 number of elements copied.
7213 The <a href="#Core_types">core types</a> of both arguments must be slices
7214 with <a href="#Type_identity">identical</a> element type.
7215 The number of elements copied is the minimum of
7216 <code>len(src)</code> and <code>len(dst)</code>.
7217 As a special case, if the destination's core type is <code>[]byte</code>,
7218 <code>copy</code> also accepts a source argument with core type <code>string</code>.
7219 This form copies the bytes from the string into the byte slice.
7222 <pre class="grammar">
7223 copy(dst, src []T) int
7224 copy(dst []byte, src string) int
7232 var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7}
7233 var s = make([]int, 6)
7234 var b = make([]byte, 5)
7235 n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5}
7236 n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5}
7237 n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello")
7241 <h3 id="Deletion_of_map_elements">Deletion of map elements</h3>
7244 The built-in function <code>delete</code> removes the element with key
7245 <code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The
7246 value <code>k</code> must be <a href="#Assignability">assignable</a>
7247 to the key type of <code>m</code>.
7250 <pre class="grammar">
7251 delete(m, k) // remove element m[k] from map m
7255 If the type of <code>m</code> is a <a href="#Type_parameter_declarations">type parameter</a>,
7256 all types in that type set must be maps, and they must all have identical key types.
7260 If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code>
7261 does not exist, <code>delete</code> is a no-op.
7265 <h3 id="Complex_numbers">Manipulating complex numbers</h3>
7268 Three functions assemble and disassemble complex numbers.
7269 The built-in function <code>complex</code> constructs a complex
7270 value from a floating-point real and imaginary part, while
7271 <code>real</code> and <code>imag</code>
7272 extract the real and imaginary parts of a complex value.
7275 <pre class="grammar">
7276 complex(realPart, imaginaryPart floatT) complexT
7277 real(complexT) floatT
7278 imag(complexT) floatT
7282 The type of the arguments and return value correspond.
7283 For <code>complex</code>, the two arguments must be of the same
7284 <a href="#Numeric_types">floating-point type</a> and the return type is the
7285 <a href="#Numeric_types">complex type</a>
7286 with the corresponding floating-point constituents:
7287 <code>complex64</code> for <code>float32</code> arguments, and
7288 <code>complex128</code> for <code>float64</code> arguments.
7289 If one of the arguments evaluates to an untyped constant, it is first implicitly
7290 <a href="#Conversions">converted</a> to the type of the other argument.
7291 If both arguments evaluate to untyped constants, they must be non-complex
7292 numbers or their imaginary parts must be zero, and the return value of
7293 the function is an untyped complex constant.
7297 For <code>real</code> and <code>imag</code>, the argument must be
7298 of complex type, and the return type is the corresponding floating-point
7299 type: <code>float32</code> for a <code>complex64</code> argument, and
7300 <code>float64</code> for a <code>complex128</code> argument.
7301 If the argument evaluates to an untyped constant, it must be a number,
7302 and the return value of the function is an untyped floating-point constant.
7306 The <code>real</code> and <code>imag</code> functions together form the inverse of
7307 <code>complex</code>, so for a value <code>z</code> of a complex type <code>Z</code>,
7308 <code>z == Z(complex(real(z), imag(z)))</code>.
7312 If the operands of these functions are all constants, the return
7313 value is a constant.
7317 var a = complex(2, -2) // complex128
7318 const b = complex(1.0, -1.4) // untyped complex constant 1 - 1.4i
7319 x := float32(math.Cos(math.Pi/2)) // float32
7320 var c64 = complex(5, -x) // complex64
7321 var s int = complex(1, 0) // untyped complex constant 1 + 0i can be converted to int
7322 _ = complex(1, 2<<s) // illegal: 2 assumes floating-point type, cannot shift
7323 var rl = real(c64) // float32
7324 var im = imag(a) // float64
7325 const c = imag(b) // untyped constant -1.4
7326 _ = imag(3 << s) // illegal: 3 assumes complex type, cannot shift
7330 Arguments of type parameter type are not permitted.
7333 <h3 id="Handling_panics">Handling panics</h3>
7335 <p> Two built-in functions, <code>panic</code> and <code>recover</code>,
7336 assist in reporting and handling <a href="#Run_time_panics">run-time panics</a>
7337 and program-defined error conditions.
7340 <pre class="grammar">
7341 func panic(interface{})
7342 func recover() interface{}
7346 While executing a function <code>F</code>,
7347 an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a>
7348 terminates the execution of <code>F</code>.
7349 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
7350 are then executed as usual.
7351 Next, any deferred functions run by <code>F</code>'s caller are run,
7352 and so on up to any deferred by the top-level function in the executing goroutine.
7353 At that point, the program is terminated and the error
7354 condition is reported, including the value of the argument to <code>panic</code>.
7355 This termination sequence is called <i>panicking</i>.
7360 panic("unreachable")
7361 panic(Error("cannot parse"))
7365 The <code>recover</code> function allows a program to manage behavior
7366 of a panicking goroutine.
7367 Suppose a function <code>G</code> defers a function <code>D</code> that calls
7368 <code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code>
7370 When the running of deferred functions reaches <code>D</code>,
7371 the return value of <code>D</code>'s call to <code>recover</code> will be the value passed to the call of <code>panic</code>.
7372 If <code>D</code> returns normally, without starting a new
7373 <code>panic</code>, the panicking sequence stops. In that case,
7374 the state of functions called between <code>G</code> and the call to <code>panic</code>
7375 is discarded, and normal execution resumes.
7376 Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s
7377 execution terminates by returning to its caller.
7381 The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds:
7385 <code>panic</code>'s argument was <code>nil</code>;
7388 the goroutine is not panicking;
7391 <code>recover</code> was not called directly by a deferred function.
7396 The <code>protect</code> function in the example below invokes
7397 the function argument <code>g</code> and protects callers from
7398 run-time panics raised by <code>g</code>.
7402 func protect(g func()) {
7404 log.Println("done") // Println executes normally even if there is a panic
7405 if x := recover(); x != nil {
7406 log.Printf("run time panic: %v", x)
7409 log.Println("start")
7415 <h3 id="Bootstrapping">Bootstrapping</h3>
7418 Current implementations provide several built-in functions useful during
7419 bootstrapping. These functions are documented for completeness but are not
7420 guaranteed to stay in the language. They do not return a result.
7423 <pre class="grammar">
7426 print prints all arguments; formatting of arguments is implementation-specific
7427 println like print but prints spaces between arguments and a newline at the end
7431 Implementation restriction: <code>print</code> and <code>println</code> need not
7432 accept arbitrary argument types, but printing of boolean, numeric, and string
7433 <a href="#Types">types</a> must be supported.
7436 <h2 id="Packages">Packages</h2>
7439 Go programs are constructed by linking together <i>packages</i>.
7440 A package in turn is constructed from one or more source files
7441 that together declare constants, types, variables and functions
7442 belonging to the package and which are accessible in all files
7443 of the same package. Those elements may be
7444 <a href="#Exported_identifiers">exported</a> and used in another package.
7447 <h3 id="Source_file_organization">Source file organization</h3>
7450 Each source file consists of a package clause defining the package
7451 to which it belongs, followed by a possibly empty set of import
7452 declarations that declare packages whose contents it wishes to use,
7453 followed by a possibly empty set of declarations of functions,
7454 types, variables, and constants.
7458 SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
7461 <h3 id="Package_clause">Package clause</h3>
7464 A package clause begins each source file and defines the package
7465 to which the file belongs.
7469 PackageClause = "package" PackageName .
7470 PackageName = identifier .
7474 The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>.
7482 A set of files sharing the same PackageName form the implementation of a package.
7483 An implementation may require that all source files for a package inhabit the same directory.
7486 <h3 id="Import_declarations">Import declarations</h3>
7489 An import declaration states that the source file containing the declaration
7490 depends on functionality of the <i>imported</i> package
7491 (<a href="#Program_initialization_and_execution">§Program initialization and execution</a>)
7492 and enables access to <a href="#Exported_identifiers">exported</a> identifiers
7494 The import names an identifier (PackageName) to be used for access and an ImportPath
7495 that specifies the package to be imported.
7499 ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
7500 ImportSpec = [ "." | PackageName ] ImportPath .
7501 ImportPath = string_lit .
7505 The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a>
7506 to access exported identifiers of the package within the importing source file.
7507 It is declared in the <a href="#Blocks">file block</a>.
7508 If the PackageName is omitted, it defaults to the identifier specified in the
7509 <a href="#Package_clause">package clause</a> of the imported package.
7510 If an explicit period (<code>.</code>) appears instead of a name, all the
7511 package's exported identifiers declared in that package's
7512 <a href="#Blocks">package block</a> will be declared in the importing source
7513 file's file block and must be accessed without a qualifier.
7517 The interpretation of the ImportPath is implementation-dependent but
7518 it is typically a substring of the full file name of the compiled
7519 package and may be relative to a repository of installed packages.
7523 Implementation restriction: A compiler may restrict ImportPaths to
7524 non-empty strings using only characters belonging to
7525 <a href="https://www.unicode.org/versions/Unicode6.3.0/">Unicode's</a>
7526 L, M, N, P, and S general categories (the Graphic characters without
7527 spaces) and may also exclude the characters
7528 <code>!"#$%&'()*,:;<=>?[\]^`{|}</code>
7529 and the Unicode replacement character U+FFFD.
7533 Assume we have compiled a package containing the package clause
7534 <code>package math</code>, which exports function <code>Sin</code>, and
7535 installed the compiled package in the file identified by
7536 <code>"lib/math"</code>.
7537 This table illustrates how <code>Sin</code> is accessed in files
7538 that import the package after the
7539 various types of import declaration.
7542 <pre class="grammar">
7543 Import declaration Local name of Sin
7545 import "lib/math" math.Sin
7546 import m "lib/math" m.Sin
7547 import . "lib/math" Sin
7551 An import declaration declares a dependency relation between
7552 the importing and imported package.
7553 It is illegal for a package to import itself, directly or indirectly,
7554 or to directly import a package without
7555 referring to any of its exported identifiers. To import a package solely for
7556 its side-effects (initialization), use the <a href="#Blank_identifier">blank</a>
7557 identifier as explicit package name:
7565 <h3 id="An_example_package">An example package</h3>
7568 Here is a complete Go package that implements a concurrent prime sieve.
7576 // Send the sequence 2, 3, 4, … to channel 'ch'.
7577 func generate(ch chan<- int) {
7579 ch <- i // Send 'i' to channel 'ch'.
7583 // Copy the values from channel 'src' to channel 'dst',
7584 // removing those divisible by 'prime'.
7585 func filter(src <-chan int, dst chan<- int, prime int) {
7586 for i := range src { // Loop over values received from 'src'.
7588 dst <- i // Send 'i' to channel 'dst'.
7593 // The prime sieve: Daisy-chain filter processes together.
7595 ch := make(chan int) // Create a new channel.
7596 go generate(ch) // Start generate() as a subprocess.
7599 fmt.Print(prime, "\n")
7600 ch1 := make(chan int)
7601 go filter(ch, ch1, prime)
7611 <h2 id="Program_initialization_and_execution">Program initialization and execution</h2>
7613 <h3 id="The_zero_value">The zero value</h3>
7615 When storage is allocated for a <a href="#Variables">variable</a>,
7616 either through a declaration or a call of <code>new</code>, or when
7617 a new value is created, either through a composite literal or a call
7618 of <code>make</code>,
7619 and no explicit initialization is provided, the variable or value is
7620 given a default value. Each element of such a variable or value is
7621 set to the <i>zero value</i> for its type: <code>false</code> for booleans,
7622 <code>0</code> for numeric types, <code>""</code>
7623 for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps.
7624 This initialization is done recursively, so for instance each element of an
7625 array of structs will have its fields zeroed if no value is specified.
7628 These two simple declarations are equivalent:
7641 type T struct { i int; f float64; next *T }
7646 the following holds:
7656 The same would also be true after
7663 <h3 id="Package_initialization">Package initialization</h3>
7666 Within a package, package-level variable initialization proceeds stepwise,
7667 with each step selecting the variable earliest in <i>declaration order</i>
7668 which has no dependencies on uninitialized variables.
7672 More precisely, a package-level variable is considered <i>ready for
7673 initialization</i> if it is not yet initialized and either has
7674 no <a href="#Variable_declarations">initialization expression</a> or
7675 its initialization expression has no <i>dependencies</i> on uninitialized variables.
7676 Initialization proceeds by repeatedly initializing the next package-level
7677 variable that is earliest in declaration order and ready for initialization,
7678 until there are no variables ready for initialization.
7682 If any variables are still uninitialized when this
7683 process ends, those variables are part of one or more initialization cycles,
7684 and the program is not valid.
7688 Multiple variables on the left-hand side of a variable declaration initialized
7689 by single (multi-valued) expression on the right-hand side are initialized
7690 together: If any of the variables on the left-hand side is initialized, all
7691 those variables are initialized in the same step.
7696 var a, b = f() // a and b are initialized together, before x is initialized
7700 For the purpose of package initialization, <a href="#Blank_identifier">blank</a>
7701 variables are treated like any other variables in declarations.
7705 The declaration order of variables declared in multiple files is determined
7706 by the order in which the files are presented to the compiler: Variables
7707 declared in the first file are declared before any of the variables declared
7708 in the second file, and so on.
7712 Dependency analysis does not rely on the actual values of the
7713 variables, only on lexical <i>references</i> to them in the source,
7714 analyzed transitively. For instance, if a variable <code>x</code>'s
7715 initialization expression refers to a function whose body refers to
7716 variable <code>y</code> then <code>x</code> depends on <code>y</code>.
7722 A reference to a variable or function is an identifier denoting that
7723 variable or function.
7727 A reference to a method <code>m</code> is a
7728 <a href="#Method_values">method value</a> or
7729 <a href="#Method_expressions">method expression</a> of the form
7730 <code>t.m</code>, where the (static) type of <code>t</code> is
7731 not an interface type, and the method <code>m</code> is in the
7732 <a href="#Method_sets">method set</a> of <code>t</code>.
7733 It is immaterial whether the resulting function value
7734 <code>t.m</code> is invoked.
7738 A variable, function, or method <code>x</code> depends on a variable
7739 <code>y</code> if <code>x</code>'s initialization expression or body
7740 (for functions and methods) contains a reference to <code>y</code>
7741 or to a function or method that depends on <code>y</code>.
7746 For example, given the declarations
7754 d = 3 // == 5 after initialization has finished
7764 the initialization order is <code>d</code>, <code>b</code>, <code>c</code>, <code>a</code>.
7765 Note that the order of subexpressions in initialization expressions is irrelevant:
7766 <code>a = c + b</code> and <code>a = b + c</code> result in the same initialization
7767 order in this example.
7771 Dependency analysis is performed per package; only references referring
7772 to variables, functions, and (non-interface) methods declared in the current
7773 package are considered. If other, hidden, data dependencies exists between
7774 variables, the initialization order between those variables is unspecified.
7778 For instance, given the declarations
7782 var x = I(T{}).ab() // x has an undetected, hidden dependency on a and b
7783 var _ = sideEffect() // unrelated to x, a, or b
7787 type I interface { ab() []int }
7789 func (T) ab() []int { return []int{a, b} }
7793 the variable <code>a</code> will be initialized after <code>b</code> but
7794 whether <code>x</code> is initialized before <code>b</code>, between
7795 <code>b</code> and <code>a</code>, or after <code>a</code>, and
7796 thus also the moment at which <code>sideEffect()</code> is called (before
7797 or after <code>x</code> is initialized) is not specified.
7801 Variables may also be initialized using functions named <code>init</code>
7802 declared in the package block, with no arguments and no result parameters.
7810 Multiple such functions may be defined per package, even within a single
7811 source file. In the package block, the <code>init</code> identifier can
7812 be used only to declare <code>init</code> functions, yet the identifier
7813 itself is not <a href="#Declarations_and_scope">declared</a>. Thus
7814 <code>init</code> functions cannot be referred to from anywhere
7819 A package with no imports is initialized by assigning initial values
7820 to all its package-level variables followed by calling all <code>init</code>
7821 functions in the order they appear in the source, possibly in multiple files,
7822 as presented to the compiler.
7823 If a package has imports, the imported packages are initialized
7824 before initializing the package itself. If multiple packages import
7825 a package, the imported package will be initialized only once.
7826 The importing of packages, by construction, guarantees that there
7827 can be no cyclic initialization dependencies.
7831 Package initialization—variable initialization and the invocation of
7832 <code>init</code> functions—happens in a single goroutine,
7833 sequentially, one package at a time.
7834 An <code>init</code> function may launch other goroutines, which can run
7835 concurrently with the initialization code. However, initialization
7837 the <code>init</code> functions: it will not invoke the next one
7838 until the previous one has returned.
7842 To ensure reproducible initialization behavior, build systems are encouraged
7843 to present multiple files belonging to the same package in lexical file name
7844 order to a compiler.
7848 <h3 id="Program_execution">Program execution</h3>
7850 A complete program is created by linking a single, unimported package
7851 called the <i>main package</i> with all the packages it imports, transitively.
7852 The main package must
7853 have package name <code>main</code> and
7854 declare a function <code>main</code> that takes no
7855 arguments and returns no value.
7863 Program execution begins by initializing the main package and then
7864 invoking the function <code>main</code>.
7865 When that function invocation returns, the program exits.
7866 It does not wait for other (non-<code>main</code>) goroutines to complete.
7869 <h2 id="Errors">Errors</h2>
7872 The predeclared type <code>error</code> is defined as
7876 type error interface {
7882 It is the conventional interface for representing an error condition,
7883 with the nil value representing no error.
7884 For instance, a function to read data from a file might be defined:
7888 func Read(f *File, b []byte) (n int, err error)
7891 <h2 id="Run_time_panics">Run-time panics</h2>
7894 Execution errors such as attempting to index an array out
7895 of bounds trigger a <i>run-time panic</i> equivalent to a call of
7896 the built-in function <a href="#Handling_panics"><code>panic</code></a>
7897 with a value of the implementation-defined interface type <code>runtime.Error</code>.
7898 That type satisfies the predeclared interface type
7899 <a href="#Errors"><code>error</code></a>.
7900 The exact error values that
7901 represent distinct run-time error conditions are unspecified.
7907 type Error interface {
7909 // and perhaps other methods
7913 <h2 id="System_considerations">System considerations</h2>
7915 <h3 id="Package_unsafe">Package <code>unsafe</code></h3>
7918 The built-in package <code>unsafe</code>, known to the compiler
7919 and accessible through the <a href="#Import_declarations">import path</a> <code>"unsafe"</code>,
7920 provides facilities for low-level programming including operations
7921 that violate the type system. A package using <code>unsafe</code>
7922 must be vetted manually for type safety and may not be portable.
7923 The package provides the following interface:
7926 <pre class="grammar">
7929 type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type
7930 type Pointer *ArbitraryType
7932 func Alignof(variable ArbitraryType) uintptr
7933 func Offsetof(selector ArbitraryType) uintptr
7934 func Sizeof(variable ArbitraryType) uintptr
7936 type IntegerType int // shorthand for an integer type; it is not a real type
7937 func Add(ptr Pointer, len IntegerType) Pointer
7938 func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType
7942 These conversions also apply to type parameters with suitable core types.
7943 Determine if we can simply use core type insted of underlying type here,
7944 of if the general conversion rules take care of this.
7948 A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code>
7949 value may not be <a href="#Address_operators">dereferenced</a>.
7950 Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be
7951 <a href="#Conversions">converted</a> to a type of underlying type <code>Pointer</code> and vice versa.
7952 The effect of converting between <code>Pointer</code> and <code>uintptr</code> is implementation-defined.
7957 bits = *(*uint64)(unsafe.Pointer(&f))
7959 type ptr unsafe.Pointer
7960 bits = *(*uint64)(ptr(&f))
7966 The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code>
7967 of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code>
7968 as if <code>v</code> was declared via <code>var v = x</code>.
7971 The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a>
7972 <code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code>
7973 or <code>*s</code>, and returns the field offset in bytes relative to the struct's address.
7974 If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable
7975 without pointer indirections through fields of the struct.
7976 For a struct <code>s</code> with field <code>f</code>:
7980 uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&s.f))
7984 Computer architectures may require memory addresses to be <i>aligned</i>;
7985 that is, for addresses of a variable to be a multiple of a factor,
7986 the variable's type's <i>alignment</i>. The function <code>Alignof</code>
7987 takes an expression denoting a variable of any type and returns the
7988 alignment of the (type of the) variable in bytes. For a variable
7993 uintptr(unsafe.Pointer(&x)) % unsafe.Alignof(x) == 0
7997 A (variable of) type <code>T</code> has <i>variable size</i> if <code>T</code>
7998 is a <a href="#Type_parameter_declarations">type parameter</a>, or if it is an
7999 array or struct type containing elements
8000 or fields of variable size. Otherwise the size is <i>constant</i>.
8001 Calls to <code>Alignof</code>, <code>Offsetof</code>, and <code>Sizeof</code>
8002 are compile-time <a href="#Constant_expressions">constant expressions</a> of
8003 type <code>uintptr</code> if their arguments (or the struct <code>s</code> in
8004 the selector expression <code>s.f</code> for <code>Offsetof</code>) are types
8009 The function <code>Add</code> adds <code>len</code> to <code>ptr</code>
8010 and returns the updated pointer <code>unsafe.Pointer(uintptr(ptr) + uintptr(len))</code>.
8011 The <code>len</code> argument must be of <a href="#Numeric_types">integer type</a> or an untyped <a href="#Constants">constant</a>.
8012 A constant <code>len</code> argument must be <a href="#Representability">representable</a> by a value of type <code>int</code>;
8013 if it is an untyped constant it is given type <code>int</code>.
8014 The rules for <a href="/pkg/unsafe#Pointer">valid uses</a> of <code>Pointer</code> still apply.
8018 The function <code>Slice</code> returns a slice whose underlying array starts at <code>ptr</code>
8019 and whose length and capacity are <code>len</code>.
8020 <code>Slice(ptr, len)</code> is equivalent to
8024 (*[len]ArbitraryType)(unsafe.Pointer(ptr))[:]
8028 except that, as a special case, if <code>ptr</code>
8029 is <code>nil</code> and <code>len</code> is zero,
8030 <code>Slice</code> returns <code>nil</code>.
8034 The <code>len</code> argument must be of <a href="#Numeric_types">integer type</a> or an untyped <a href="#Constants">constant</a>.
8035 A constant <code>len</code> argument must be non-negative and <a href="#Representability">representable</a> by a value of type <code>int</code>;
8036 if it is an untyped constant it is given type <code>int</code>.
8037 At run time, if <code>len</code> is negative,
8038 or if <code>ptr</code> is <code>nil</code> and <code>len</code> is not zero,
8039 a <a href="#Run_time_panics">run-time panic</a> occurs.
8042 <h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3>
8045 For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed:
8048 <pre class="grammar">
8053 uint32, int32, float32 4
8054 uint64, int64, float64, complex64 8
8059 The following minimal alignment properties are guaranteed:
8062 <li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1.
8065 <li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of
8066 all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1.
8069 <li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as
8070 the alignment of a variable of the array's element type.
8075 A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory.