2 "Title": "The Go Programming Language Specification",
3 "Subtitle": "Version of Oct 15, 2021",
7 <h2 id="Introduction">Introduction</h2>
10 This is a reference manual for the Go programming language. For
11 more information and other documents, see <a href="/">golang.org</a>.
15 Go is a general-purpose language designed with systems programming
16 in mind. It is strongly typed and garbage-collected and has explicit
17 support for concurrent programming. Programs are constructed from
18 <i>packages</i>, whose properties allow efficient management of
23 The grammar is compact and simple to parse, allowing for easy analysis
24 by automatic tools such as integrated development environments.
27 <h2 id="Notation">Notation</h2>
29 The syntax is specified using Extended Backus-Naur Form (EBNF):
33 Production = production_name "=" [ Expression ] "." .
34 Expression = Alternative { "|" Alternative } .
35 Alternative = Term { Term } .
36 Term = production_name | token [ "…" token ] | Group | Option | Repetition .
37 Group = "(" Expression ")" .
38 Option = "[" Expression "]" .
39 Repetition = "{" Expression "}" .
43 Productions are expressions constructed from terms and the following
44 operators, in increasing precedence:
49 [] option (0 or 1 times)
50 {} repetition (0 to n times)
54 Lower-case production names are used to identify lexical tokens.
55 Non-terminals are in CamelCase. Lexical tokens are enclosed in
56 double quotes <code>""</code> or back quotes <code>``</code>.
60 The form <code>a … b</code> represents the set of characters from
61 <code>a</code> through <code>b</code> as alternatives. The horizontal
62 ellipsis <code>…</code> is also used elsewhere in the spec to informally denote various
63 enumerations or code snippets that are not further specified. The character <code>…</code>
64 (as opposed to the three characters <code>...</code>) is not a token of the Go
68 <h2 id="Source_code_representation">Source code representation</h2>
71 Source code is Unicode text encoded in
72 <a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. The text is not
73 canonicalized, so a single accented code point is distinct from the
74 same character constructed from combining an accent and a letter;
75 those are treated as two code points. For simplicity, this document
76 will use the unqualified term <i>character</i> to refer to a Unicode code point
80 Each code point is distinct; for instance, upper and lower case letters
81 are different characters.
84 Implementation restriction: For compatibility with other tools, a
85 compiler may disallow the NUL character (U+0000) in the source text.
88 Implementation restriction: For compatibility with other tools, a
89 compiler may ignore a UTF-8-encoded byte order mark
90 (U+FEFF) if it is the first Unicode code point in the source text.
91 A byte order mark may be disallowed anywhere else in the source.
94 <h3 id="Characters">Characters</h3>
97 The following terms are used to denote specific Unicode character classes:
100 newline = /* the Unicode code point U+000A */ .
101 unicode_char = /* an arbitrary Unicode code point except newline */ .
102 unicode_letter = /* a Unicode code point classified as "Letter" */ .
103 unicode_digit = /* a Unicode code point classified as "Number, decimal digit" */ .
107 In <a href="https://www.unicode.org/versions/Unicode8.0.0/">The Unicode Standard 8.0</a>,
108 Section 4.5 "General Category" defines a set of character categories.
109 Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo
110 as Unicode letters, and those in the Number category Nd as Unicode digits.
113 <h3 id="Letters_and_digits">Letters and digits</h3>
116 The underscore character <code>_</code> (U+005F) is considered a letter.
119 letter = unicode_letter | "_" .
120 decimal_digit = "0" … "9" .
121 binary_digit = "0" | "1" .
122 octal_digit = "0" … "7" .
123 hex_digit = "0" … "9" | "A" … "F" | "a" … "f" .
126 <h2 id="Lexical_elements">Lexical elements</h2>
128 <h3 id="Comments">Comments</h3>
131 Comments serve as program documentation. There are two forms:
136 <i>Line comments</i> start with the character sequence <code>//</code>
137 and stop at the end of the line.
140 <i>General comments</i> start with the character sequence <code>/*</code>
141 and stop with the first subsequent character sequence <code>*/</code>.
146 A comment cannot start inside a <a href="#Rune_literals">rune</a> or
147 <a href="#String_literals">string literal</a>, or inside a comment.
148 A general comment containing no newlines acts like a space.
149 Any other comment acts like a newline.
152 <h3 id="Tokens">Tokens</h3>
155 Tokens form the vocabulary of the Go language.
156 There are four classes: <i>identifiers</i>, <i>keywords</i>, <i>operators
157 and punctuation</i>, and <i>literals</i>. <i>White space</i>, formed from
158 spaces (U+0020), horizontal tabs (U+0009),
159 carriage returns (U+000D), and newlines (U+000A),
160 is ignored except as it separates tokens
161 that would otherwise combine into a single token. Also, a newline or end of file
162 may trigger the insertion of a <a href="#Semicolons">semicolon</a>.
163 While breaking the input into tokens,
164 the next token is the longest sequence of characters that form a
168 <h3 id="Semicolons">Semicolons</h3>
171 The formal grammar uses semicolons <code>";"</code> as terminators in
172 a number of productions. Go programs may omit most of these semicolons
173 using the following two rules:
178 When the input is broken into tokens, a semicolon is automatically inserted
179 into the token stream immediately after a line's final token if that token is
182 <a href="#Identifiers">identifier</a>
186 <a href="#Integer_literals">integer</a>,
187 <a href="#Floating-point_literals">floating-point</a>,
188 <a href="#Imaginary_literals">imaginary</a>,
189 <a href="#Rune_literals">rune</a>, or
190 <a href="#String_literals">string</a> literal
193 <li>one of the <a href="#Keywords">keywords</a>
195 <code>continue</code>,
196 <code>fallthrough</code>, or
200 <li>one of the <a href="#Operators_and_punctuation">operators and punctuation</a>
211 To allow complex statements to occupy a single line, a semicolon
212 may be omitted before a closing <code>")"</code> or <code>"}"</code>.
217 To reflect idiomatic use, code examples in this document elide semicolons
222 <h3 id="Identifiers">Identifiers</h3>
225 Identifiers name program entities such as variables and types.
226 An identifier is a sequence of one or more letters and digits.
227 The first character in an identifier must be a letter.
230 identifier = letter { letter | unicode_digit } .
235 ThisVariableIsExported
240 Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>.
244 <h3 id="Keywords">Keywords</h3>
247 The following keywords are reserved and may not be used as identifiers.
249 <pre class="grammar">
250 break default func interface select
251 case defer go map struct
252 chan else goto package switch
253 const fallthrough if range type
254 continue for import return var
257 <h3 id="Operators_and_punctuation">Operators and punctuation</h3>
260 The following character sequences represent <a href="#Operators">operators</a>
261 (including <a href="#Assignments">assignment operators</a>) and punctuation:
263 <pre class="grammar">
264 + & += &= && == != ( )
265 - | -= |= || < <= [ ]
266 * ^ *= ^= <- > >= { }
267 / << /= <<= ++ = := , ;
268 % >> %= >>= -- ! ... . :
272 <h3 id="Integer_literals">Integer literals</h3>
275 An integer literal is a sequence of digits representing an
276 <a href="#Constants">integer constant</a>.
277 An optional prefix sets a non-decimal base: <code>0b</code> or <code>0B</code>
278 for binary, <code>0</code>, <code>0o</code>, or <code>0O</code> for octal,
279 and <code>0x</code> or <code>0X</code> for hexadecimal.
280 A single <code>0</code> is considered a decimal zero.
281 In hexadecimal literals, letters <code>a</code> through <code>f</code>
282 and <code>A</code> through <code>F</code> represent values 10 through 15.
286 For readability, an underscore character <code>_</code> may appear after
287 a base prefix or between successive digits; such underscores do not change
291 int_lit = decimal_lit | binary_lit | octal_lit | hex_lit .
292 decimal_lit = "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] .
293 binary_lit = "0" ( "b" | "B" ) [ "_" ] binary_digits .
294 octal_lit = "0" [ "o" | "O" ] [ "_" ] octal_digits .
295 hex_lit = "0" ( "x" | "X" ) [ "_" ] hex_digits .
297 decimal_digits = decimal_digit { [ "_" ] decimal_digit } .
298 binary_digits = binary_digit { [ "_" ] binary_digit } .
299 octal_digits = octal_digit { [ "_" ] octal_digit } .
300 hex_digits = hex_digit { [ "_" ] hex_digit } .
309 0O600 // second character is capital letter 'O'
313 170141183460469231731687303715884105727
314 170_141183_460469_231731_687303_715884_105727
316 _42 // an identifier, not an integer literal
317 42_ // invalid: _ must separate successive digits
318 4__2 // invalid: only one _ at a time
319 0_xBadFace // invalid: _ must separate successive digits
323 <h3 id="Floating-point_literals">Floating-point literals</h3>
326 A floating-point literal is a decimal or hexadecimal representation of a
327 <a href="#Constants">floating-point constant</a>.
331 A decimal floating-point literal consists of an integer part (decimal digits),
332 a decimal point, a fractional part (decimal digits), and an exponent part
333 (<code>e</code> or <code>E</code> followed by an optional sign and decimal digits).
334 One of the integer part or the fractional part may be elided; one of the decimal point
335 or the exponent part may be elided.
336 An exponent value exp scales the mantissa (integer and fractional part) by 10<sup>exp</sup>.
340 A hexadecimal floating-point literal consists of a <code>0x</code> or <code>0X</code>
341 prefix, an integer part (hexadecimal digits), a radix point, a fractional part (hexadecimal digits),
342 and an exponent part (<code>p</code> or <code>P</code> followed by an optional sign and decimal digits).
343 One of the integer part or the fractional part may be elided; the radix point may be elided as well,
344 but the exponent part is required. (This syntax matches the one given in IEEE 754-2008 §5.12.3.)
345 An exponent value exp scales the mantissa (integer and fractional part) by 2<sup>exp</sup>.
349 For readability, an underscore character <code>_</code> may appear after
350 a base prefix or between successive digits; such underscores do not change
355 float_lit = decimal_float_lit | hex_float_lit .
357 decimal_float_lit = decimal_digits "." [ decimal_digits ] [ decimal_exponent ] |
358 decimal_digits decimal_exponent |
359 "." decimal_digits [ decimal_exponent ] .
360 decimal_exponent = ( "e" | "E" ) [ "+" | "-" ] decimal_digits .
362 hex_float_lit = "0" ( "x" | "X" ) hex_mantissa hex_exponent .
363 hex_mantissa = [ "_" ] hex_digits "." [ hex_digits ] |
366 hex_exponent = ( "p" | "P" ) [ "+" | "-" ] decimal_digits .
384 0x1.Fp+0 // == 1.9375
386 0X_1FFFP-16 // == 0.1249847412109375
387 0x15e-2 // == 0x15e - 2 (integer subtraction)
389 0x.p1 // invalid: mantissa has no digits
390 1p-2 // invalid: p exponent requires hexadecimal mantissa
391 0x1.5e-2 // invalid: hexadecimal mantissa requires p exponent
392 1_.5 // invalid: _ must separate successive digits
393 1._5 // invalid: _ must separate successive digits
394 1.5_e1 // invalid: _ must separate successive digits
395 1.5e_1 // invalid: _ must separate successive digits
396 1.5e1_ // invalid: _ must separate successive digits
400 <h3 id="Imaginary_literals">Imaginary literals</h3>
403 An imaginary literal represents the imaginary part of a
404 <a href="#Constants">complex constant</a>.
405 It consists of an <a href="#Integer_literals">integer</a> or
406 <a href="#Floating-point_literals">floating-point</a> literal
407 followed by the lower-case letter <code>i</code>.
408 The value of an imaginary literal is the value of the respective
409 integer or floating-point literal multiplied by the imaginary unit <i>i</i>.
413 imaginary_lit = (decimal_digits | int_lit | float_lit) "i" .
417 For backward compatibility, an imaginary literal's integer part consisting
418 entirely of decimal digits (and possibly underscores) is considered a decimal
419 integer, even if it starts with a leading <code>0</code>.
424 0123i // == 123i for backward-compatibility
425 0o123i // == 0o123 * 1i == 83i
426 0xabci // == 0xabc * 1i == 2748i
434 0x1p-2i // == 0x1p-2 * 1i == 0.25i
438 <h3 id="Rune_literals">Rune literals</h3>
441 A rune literal represents a <a href="#Constants">rune constant</a>,
442 an integer value identifying a Unicode code point.
443 A rune literal is expressed as one or more characters enclosed in single quotes,
444 as in <code>'x'</code> or <code>'\n'</code>.
445 Within the quotes, any character may appear except newline and unescaped single
446 quote. A single quoted character represents the Unicode value
447 of the character itself,
448 while multi-character sequences beginning with a backslash encode
449 values in various formats.
453 The simplest form represents the single character within the quotes;
454 since Go source text is Unicode characters encoded in UTF-8, multiple
455 UTF-8-encoded bytes may represent a single integer value. For
456 instance, the literal <code>'a'</code> holds a single byte representing
457 a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while
458 <code>'ä'</code> holds two bytes (<code>0xc3</code> <code>0xa4</code>) representing
459 a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>.
463 Several backslash escapes allow arbitrary values to be encoded as
464 ASCII text. There are four ways to represent the integer value
465 as a numeric constant: <code>\x</code> followed by exactly two hexadecimal
466 digits; <code>\u</code> followed by exactly four hexadecimal digits;
467 <code>\U</code> followed by exactly eight hexadecimal digits, and a
468 plain backslash <code>\</code> followed by exactly three octal digits.
469 In each case the value of the literal is the value represented by
470 the digits in the corresponding base.
474 Although these representations all result in an integer, they have
475 different valid ranges. Octal escapes must represent a value between
476 0 and 255 inclusive. Hexadecimal escapes satisfy this condition
477 by construction. The escapes <code>\u</code> and <code>\U</code>
478 represent Unicode code points so within them some values are illegal,
479 in particular those above <code>0x10FFFF</code> and surrogate halves.
483 After a backslash, certain single-character escapes represent special values:
486 <pre class="grammar">
487 \a U+0007 alert or bell
490 \n U+000A line feed or newline
491 \r U+000D carriage return
492 \t U+0009 horizontal tab
493 \v U+000B vertical tab
495 \' U+0027 single quote (valid escape only within rune literals)
496 \" U+0022 double quote (valid escape only within string literals)
500 All other sequences starting with a backslash are illegal inside rune literals.
503 rune_lit = "'" ( unicode_value | byte_value ) "'" .
504 unicode_value = unicode_char | little_u_value | big_u_value | escaped_char .
505 byte_value = octal_byte_value | hex_byte_value .
506 octal_byte_value = `\` octal_digit octal_digit octal_digit .
507 hex_byte_value = `\` "x" hex_digit hex_digit .
508 little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit .
509 big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit
510 hex_digit hex_digit hex_digit hex_digit .
511 escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
526 '\'' // rune literal containing single quote character
527 'aa' // illegal: too many characters
528 '\xa' // illegal: too few hexadecimal digits
529 '\0' // illegal: too few octal digits
530 '\uDFFF' // illegal: surrogate half
531 '\U00110000' // illegal: invalid Unicode code point
535 <h3 id="String_literals">String literals</h3>
538 A string literal represents a <a href="#Constants">string constant</a>
539 obtained from concatenating a sequence of characters. There are two forms:
540 raw string literals and interpreted string literals.
544 Raw string literals are character sequences between back quotes, as in
545 <code>`foo`</code>. Within the quotes, any character may appear except
546 back quote. The value of a raw string literal is the
547 string composed of the uninterpreted (implicitly UTF-8-encoded) characters
549 in particular, backslashes have no special meaning and the string may
551 Carriage return characters ('\r') inside raw string literals
552 are discarded from the raw string value.
556 Interpreted string literals are character sequences between double
557 quotes, as in <code>"bar"</code>.
558 Within the quotes, any character may appear except newline and unescaped double quote.
559 The text between the quotes forms the
560 value of the literal, with backslash escapes interpreted as they
561 are in <a href="#Rune_literals">rune literals</a> (except that <code>\'</code> is illegal and
562 <code>\"</code> is legal), with the same restrictions.
563 The three-digit octal (<code>\</code><i>nnn</i>)
564 and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual
565 <i>bytes</i> of the resulting string; all other escapes represent
566 the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
567 Thus inside a string literal <code>\377</code> and <code>\xFF</code> represent
568 a single byte of value <code>0xFF</code>=255, while <code>ÿ</code>,
569 <code>\u00FF</code>, <code>\U000000FF</code> and <code>\xc3\xbf</code> represent
570 the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character
575 string_lit = raw_string_lit | interpreted_string_lit .
576 raw_string_lit = "`" { unicode_char | newline } "`" .
577 interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
581 `abc` // same as "abc"
583 \n` // same as "\\n\n\\n"
590 "\uD800" // illegal: surrogate half
591 "\U00110000" // illegal: invalid Unicode code point
595 These examples all represent the same string:
599 "日本語" // UTF-8 input text
600 `日本語` // UTF-8 input text as a raw literal
601 "\u65e5\u672c\u8a9e" // the explicit Unicode code points
602 "\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points
603 "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes
607 If the source code represents a character as two code points, such as
608 a combining form involving an accent and a letter, the result will be
609 an error if placed in a rune literal (it is not a single code
610 point), and will appear as two code points if placed in a string
615 <h2 id="Constants">Constants</h2>
617 <p>There are <i>boolean constants</i>,
618 <i>rune constants</i>,
619 <i>integer constants</i>,
620 <i>floating-point constants</i>, <i>complex constants</i>,
621 and <i>string constants</i>. Rune, integer, floating-point,
622 and complex constants are
623 collectively called <i>numeric constants</i>.
627 A constant value is represented by a
628 <a href="#Rune_literals">rune</a>,
629 <a href="#Integer_literals">integer</a>,
630 <a href="#Floating-point_literals">floating-point</a>,
631 <a href="#Imaginary_literals">imaginary</a>,
633 <a href="#String_literals">string</a> literal,
634 an identifier denoting a constant,
635 a <a href="#Constant_expressions">constant expression</a>,
636 a <a href="#Conversions">conversion</a> with a result that is a constant, or
637 the result value of some built-in functions such as
638 <code>unsafe.Sizeof</code> applied to any value,
639 <code>cap</code> or <code>len</code> applied to
640 <a href="#Length_and_capacity">some expressions</a>,
641 <code>real</code> and <code>imag</code> applied to a complex constant
642 and <code>complex</code> applied to numeric constants.
643 The boolean truth values are represented by the predeclared constants
644 <code>true</code> and <code>false</code>. The predeclared identifier
645 <a href="#Iota">iota</a> denotes an integer constant.
649 In general, complex constants are a form of
650 <a href="#Constant_expressions">constant expression</a>
651 and are discussed in that section.
655 Numeric constants represent exact values of arbitrary precision and do not overflow.
656 Consequently, there are no constants denoting the IEEE-754 negative zero, infinity,
657 and not-a-number values.
661 Constants may be <a href="#Types">typed</a> or <i>untyped</i>.
662 Literal constants, <code>true</code>, <code>false</code>, <code>iota</code>,
663 and certain <a href="#Constant_expressions">constant expressions</a>
664 containing only untyped constant operands are untyped.
668 A constant may be given a type explicitly by a <a href="#Constant_declarations">constant declaration</a>
669 or <a href="#Conversions">conversion</a>, or implicitly when used in a
670 <a href="#Variable_declarations">variable declaration</a> or an
671 <a href="#Assignments">assignment</a> or as an
672 operand in an <a href="#Expressions">expression</a>.
673 It is an error if the constant value
674 cannot be <a href="#Representability">represented</a> as a value of the respective type.
678 An untyped constant has a <i>default type</i> which is the type to which the
679 constant is implicitly converted in contexts where a typed value is required,
680 for instance, in a <a href="#Short_variable_declarations">short variable declaration</a>
681 such as <code>i := 0</code> where there is no explicit type.
682 The default type of an untyped constant is <code>bool</code>, <code>rune</code>,
683 <code>int</code>, <code>float64</code>, <code>complex128</code> or <code>string</code>
684 respectively, depending on whether it is a boolean, rune, integer, floating-point,
685 complex, or string constant.
689 Implementation restriction: Although numeric constants have arbitrary
690 precision in the language, a compiler may implement them using an
691 internal representation with limited precision. That said, every
696 <li>Represent integer constants with at least 256 bits.</li>
698 <li>Represent floating-point constants, including the parts of
699 a complex constant, with a mantissa of at least 256 bits
700 and a signed binary exponent of at least 16 bits.</li>
702 <li>Give an error if unable to represent an integer constant
705 <li>Give an error if unable to represent a floating-point or
706 complex constant due to overflow.</li>
708 <li>Round to the nearest representable constant if unable to
709 represent a floating-point or complex constant due to limits
714 These requirements apply both to literal constants and to the result
715 of evaluating <a href="#Constant_expressions">constant
720 <h2 id="Variables">Variables</h2>
723 A variable is a storage location for holding a <i>value</i>.
724 The set of permissible values is determined by the
725 variable's <i><a href="#Types">type</a></i>.
729 A <a href="#Variable_declarations">variable declaration</a>
730 or, for function parameters and results, the signature
731 of a <a href="#Function_declarations">function declaration</a>
732 or <a href="#Function_literals">function literal</a> reserves
733 storage for a named variable.
735 Calling the built-in function <a href="#Allocation"><code>new</code></a>
736 or taking the address of a <a href="#Composite_literals">composite literal</a>
737 allocates storage for a variable at run time.
738 Such an anonymous variable is referred to via a (possibly implicit)
739 <a href="#Address_operators">pointer indirection</a>.
743 <i>Structured</i> variables of <a href="#Array_types">array</a>, <a href="#Slice_types">slice</a>,
744 and <a href="#Struct_types">struct</a> types have elements and fields that may
745 be <a href="#Address_operators">addressed</a> individually. Each such element
746 acts like a variable.
750 The <i>static type</i> (or just <i>type</i>) of a variable is the
751 type given in its declaration, the type provided in the
752 <code>new</code> call or composite literal, or the type of
753 an element of a structured variable.
754 Variables of interface type also have a distinct <i>dynamic type</i>,
755 which is the concrete type of the value assigned to the variable at run time
756 (unless the value is the predeclared identifier <code>nil</code>,
758 The dynamic type may vary during execution but values stored in interface
759 variables are always <a href="#Assignability">assignable</a>
760 to the static type of the variable.
764 var x interface{} // x is nil and has static type interface{}
765 var v *T // v has value nil, static type *T
766 x = 42 // x has value 42 and dynamic type int
767 x = v // x has value (*T)(nil) and dynamic type *T
771 A variable's value is retrieved by referring to the variable in an
772 <a href="#Expressions">expression</a>; it is the most recent value
773 <a href="#Assignments">assigned</a> to the variable.
774 If a variable has not yet been assigned a value, its value is the
775 <a href="#The_zero_value">zero value</a> for its type.
779 <h2 id="Types">Types</h2>
782 A type determines a set of values together with operations and methods specific
783 to those values. A type may be denoted by a <i>type name</i>, if it has one,
784 or specified using a <i>type literal</i>, which composes a type from existing types.
788 Type = TypeName | TypeLit | "(" Type ")" .
789 TypeName = identifier | QualifiedIdent .
790 TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
791 SliceType | MapType | ChannelType .
795 The language <a href="#Predeclared_identifiers">predeclares</a> certain type names.
796 Others are introduced with <a href="#Type_declarations">type declarations</a>.
797 <i>Composite types</i>—array, struct, pointer, function,
798 interface, slice, map, and channel types—may be constructed using
803 Each type <code>T</code> has an <i>underlying type</i>: If <code>T</code>
804 is one of the predeclared boolean, numeric, or string types, or a type literal,
805 the corresponding underlying
806 type is <code>T</code> itself. Otherwise, <code>T</code>'s underlying type
807 is the underlying type of the type to which <code>T</code> refers in its
808 <a href="#Type_declarations">type declaration</a>.
826 The underlying type of <code>string</code>, <code>A1</code>, <code>A2</code>, <code>B1</code>,
827 and <code>B2</code> is <code>string</code>.
828 The underlying type of <code>[]B1</code>, <code>B3</code>, and <code>B4</code> is <code>[]B1</code>.
831 <h3 id="Method_sets">Method sets</h3>
833 A type has a (possibly empty) <i>method set</i> associated with it.
834 The method set of an <a href="#Interface_types">interface type</a> is its interface.
835 The method set of any other type <code>T</code> consists of all
836 <a href="#Method_declarations">methods</a> declared with receiver type <code>T</code>.
837 The method set of the corresponding <a href="#Pointer_types">pointer type</a> <code>*T</code>
838 is the set of all methods declared with receiver <code>*T</code> or <code>T</code>
839 (that is, it also contains the method set of <code>T</code>).
840 Further rules apply to structs containing embedded fields, as described
841 in the section on <a href="#Struct_types">struct types</a>.
842 Any other type has an empty method set.
843 In a method set, each method must have a
844 <a href="#Uniqueness_of_identifiers">unique</a>
845 non-<a href="#Blank_identifier">blank</a> <a href="#MethodName">method name</a>.
849 The method set of a type determines the interfaces that the
850 type <a href="#Interface_types">implements</a>
851 and the methods that can be <a href="#Calls">called</a>
852 using a receiver of that type.
855 <h3 id="Boolean_types">Boolean types</h3>
858 A <i>boolean type</i> represents the set of Boolean truth values
859 denoted by the predeclared constants <code>true</code>
860 and <code>false</code>. The predeclared boolean type is <code>bool</code>;
861 it is a <a href="#Type_definitions">defined type</a>.
864 <h3 id="Numeric_types">Numeric types</h3>
867 A <i>numeric type</i> represents sets of integer or floating-point values.
868 The predeclared architecture-independent numeric types are:
871 <pre class="grammar">
872 uint8 the set of all unsigned 8-bit integers (0 to 255)
873 uint16 the set of all unsigned 16-bit integers (0 to 65535)
874 uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
875 uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
877 int8 the set of all signed 8-bit integers (-128 to 127)
878 int16 the set of all signed 16-bit integers (-32768 to 32767)
879 int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
880 int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
882 float32 the set of all IEEE-754 32-bit floating-point numbers
883 float64 the set of all IEEE-754 64-bit floating-point numbers
885 complex64 the set of all complex numbers with float32 real and imaginary parts
886 complex128 the set of all complex numbers with float64 real and imaginary parts
893 The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using
894 <a href="https://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>.
898 There is also a set of predeclared numeric types with implementation-specific sizes:
901 <pre class="grammar">
902 uint either 32 or 64 bits
903 int same size as uint
904 uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value
908 To avoid portability issues all numeric types are <a href="#Type_definitions">defined
909 types</a> and thus distinct except
910 <code>byte</code>, which is an <a href="#Alias_declarations">alias</a> for <code>uint8</code>, and
911 <code>rune</code>, which is an alias for <code>int32</code>.
913 are required when different numeric types are mixed in an expression
914 or assignment. For instance, <code>int32</code> and <code>int</code>
915 are not the same type even though they may have the same size on a
916 particular architecture.
919 <h3 id="String_types">String types</h3>
922 A <i>string type</i> represents the set of string values.
923 A string value is a (possibly empty) sequence of bytes.
924 The number of bytes is called the length of the string and is never negative.
925 Strings are immutable: once created,
926 it is impossible to change the contents of a string.
927 The predeclared string type is <code>string</code>;
928 it is a <a href="#Type_definitions">defined type</a>.
932 The length of a string <code>s</code> can be discovered using
933 the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
934 The length is a compile-time constant if the string is a constant.
935 A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>
936 0 through <code>len(s)-1</code>.
937 It is illegal to take the address of such an element; if
938 <code>s[i]</code> is the <code>i</code>'th byte of a
939 string, <code>&s[i]</code> is invalid.
943 <h3 id="Array_types">Array types</h3>
946 An array is a numbered sequence of elements of a single
947 type, called the element type.
948 The number of elements is called the length of the array and is never negative.
952 ArrayType = "[" ArrayLength "]" ElementType .
953 ArrayLength = Expression .
958 The length is part of the array's type; it must evaluate to a
959 non-negative <a href="#Constants">constant</a>
960 <a href="#Representability">representable</a> by a value
961 of type <code>int</code>.
962 The length of array <code>a</code> can be discovered
963 using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
964 The elements can be addressed by integer <a href="#Index_expressions">indices</a>
965 0 through <code>len(a)-1</code>.
966 Array types are always one-dimensional but may be composed to form
967 multi-dimensional types.
972 [2*N] struct { x, y int32 }
975 [2][2][2]float64 // same as [2]([2]([2]float64))
978 <h3 id="Slice_types">Slice types</h3>
981 A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and
982 provides access to a numbered sequence of elements from that array.
983 A slice type denotes the set of all slices of arrays of its element type.
984 The number of elements is called the length of the slice and is never negative.
985 The value of an uninitialized slice is <code>nil</code>.
989 SliceType = "[" "]" ElementType .
993 The length of a slice <code>s</code> can be discovered by the built-in function
994 <a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during
995 execution. The elements can be addressed by integer <a href="#Index_expressions">indices</a>
996 0 through <code>len(s)-1</code>. The slice index of a
997 given element may be less than the index of the same element in the
1001 A slice, once initialized, is always associated with an underlying
1002 array that holds its elements. A slice therefore shares storage
1003 with its array and with other slices of the same array; by contrast,
1004 distinct arrays always represent distinct storage.
1007 The array underlying a slice may extend past the end of the slice.
1008 The <i>capacity</i> is a measure of that extent: it is the sum of
1009 the length of the slice and the length of the array beyond the slice;
1010 a slice of length up to that capacity can be created by
1011 <a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice.
1012 The capacity of a slice <code>a</code> can be discovered using the
1013 built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.
1017 A new, initialized slice value for a given element type <code>T</code> is
1018 made using the built-in function
1019 <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1020 which takes a slice type
1021 and parameters specifying the length and optionally the capacity.
1022 A slice created with <code>make</code> always allocates a new, hidden array
1023 to which the returned slice value refers. That is, executing
1027 make([]T, length, capacity)
1031 produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a>
1032 it, so these two expressions are equivalent:
1036 make([]int, 50, 100)
1041 Like arrays, slices are always one-dimensional but may be composed to construct
1042 higher-dimensional objects.
1043 With arrays of arrays, the inner arrays are, by construction, always the same length;
1044 however with slices of slices (or arrays of slices), the inner lengths may vary dynamically.
1045 Moreover, the inner slices must be initialized individually.
1048 <h3 id="Struct_types">Struct types</h3>
1051 A struct is a sequence of named elements, called fields, each of which has a
1052 name and a type. Field names may be specified explicitly (IdentifierList) or
1053 implicitly (EmbeddedField).
1054 Within a struct, non-<a href="#Blank_identifier">blank</a> field names must
1055 be <a href="#Uniqueness_of_identifiers">unique</a>.
1059 StructType = "struct" "{" { FieldDecl ";" } "}" .
1060 FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] .
1061 EmbeddedField = [ "*" ] TypeName .
1069 // A struct with 6 fields.
1073 _ float32 // padding
1080 A field declared with a type but no explicit field name is called an <i>embedded field</i>.
1081 An embedded field must be specified as
1082 a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>,
1083 and <code>T</code> itself may not be
1084 a pointer type. The unqualified type name acts as the field name.
1088 // A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4
1090 T1 // field name is T1
1091 *T2 // field name is T2
1092 P.T3 // field name is T3
1093 *P.T4 // field name is T4
1094 x, y int // field names are x and y
1099 The following declaration is illegal because field names must be unique
1105 T // conflicts with embedded field *T and *P.T
1106 *T // conflicts with embedded field T and *P.T
1107 *P.T // conflicts with embedded field T and *T
1112 A field or <a href="#Method_declarations">method</a> <code>f</code> of an
1113 embedded field in a struct <code>x</code> is called <i>promoted</i> if
1114 <code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes
1115 that field or method <code>f</code>.
1119 Promoted fields act like ordinary fields
1120 of a struct except that they cannot be used as field names in
1121 <a href="#Composite_literals">composite literals</a> of the struct.
1125 Given a struct type <code>S</code> and a <a href="#Type_definitions">defined type</a>
1126 <code>T</code>, promoted methods are included in the method set of the struct as follows:
1130 If <code>S</code> contains an embedded field <code>T</code>,
1131 the <a href="#Method_sets">method sets</a> of <code>S</code>
1132 and <code>*S</code> both include promoted methods with receiver
1133 <code>T</code>. The method set of <code>*S</code> also
1134 includes promoted methods with receiver <code>*T</code>.
1138 If <code>S</code> contains an embedded field <code>*T</code>,
1139 the method sets of <code>S</code> and <code>*S</code> both
1140 include promoted methods with receiver <code>T</code> or
1146 A field declaration may be followed by an optional string literal <i>tag</i>,
1147 which becomes an attribute for all the fields in the corresponding
1148 field declaration. An empty tag string is equivalent to an absent tag.
1149 The tags are made visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a>
1150 and take part in <a href="#Type_identity">type identity</a> for structs
1151 but are otherwise ignored.
1156 x, y float64 "" // an empty tag string is like an absent tag
1157 name string "any string is permitted as a tag"
1158 _ [4]byte "ceci n'est pas un champ de structure"
1161 // A struct corresponding to a TimeStamp protocol buffer.
1162 // The tag strings define the protocol buffer field numbers;
1163 // they follow the convention outlined by the reflect package.
1165 microsec uint64 `protobuf:"1"`
1166 serverIP6 uint64 `protobuf:"2"`
1170 <h3 id="Pointer_types">Pointer types</h3>
1173 A pointer type denotes the set of all pointers to <a href="#Variables">variables</a> of a given
1174 type, called the <i>base type</i> of the pointer.
1175 The value of an uninitialized pointer is <code>nil</code>.
1179 PointerType = "*" BaseType .
1188 <h3 id="Function_types">Function types</h3>
1191 A function type denotes the set of all functions with the same parameter
1192 and result types. The value of an uninitialized variable of function type
1193 is <code>nil</code>.
1197 FunctionType = "func" Signature .
1198 Signature = Parameters [ Result ] .
1199 Result = Parameters | Type .
1200 Parameters = "(" [ ParameterList [ "," ] ] ")" .
1201 ParameterList = ParameterDecl { "," ParameterDecl } .
1202 ParameterDecl = [ IdentifierList ] [ "..." ] Type .
1206 Within a list of parameters or results, the names (IdentifierList)
1207 must either all be present or all be absent. If present, each name
1208 stands for one item (parameter or result) of the specified type and
1209 all non-<a href="#Blank_identifier">blank</a> names in the signature
1210 must be <a href="#Uniqueness_of_identifiers">unique</a>.
1211 If absent, each type stands for one item of that type.
1212 Parameter and result
1213 lists are always parenthesized except that if there is exactly
1214 one unnamed result it may be written as an unparenthesized type.
1218 The final incoming parameter in a function signature may have
1219 a type prefixed with <code>...</code>.
1220 A function with such a parameter is called <i>variadic</i> and
1221 may be invoked with zero or more arguments for that parameter.
1227 func(a, _ int, z float32) bool
1228 func(a, b int, z float32) (bool)
1229 func(prefix string, values ...int)
1230 func(a, b int, z float64, opt ...interface{}) (success bool)
1231 func(int, int, float64) (float64, *[]int)
1232 func(n int) func(p *T)
1236 <h3 id="Interface_types">Interface types</h3>
1239 An interface type specifies a <a href="#Method_sets">method set</a> called its <i>interface</i>.
1240 A variable of interface type can store a value of any type with a method set
1241 that is any superset of the interface. Such a type is said to
1242 <i>implement the interface</i>.
1243 The value of an uninitialized variable of interface type is <code>nil</code>.
1247 InterfaceType = "interface" "{" { ( MethodSpec | InterfaceTypeName ) ";" } "}" .
1248 MethodSpec = MethodName Signature .
1249 MethodName = identifier .
1250 InterfaceTypeName = TypeName .
1254 An interface type may specify methods <i>explicitly</i> through method specifications,
1255 or it may <i>embed</i> methods of other interfaces through interface type names.
1259 // A simple File interface.
1261 Read([]byte) (int, error)
1262 Write([]byte) (int, error)
1268 The name of each explicitly specified method must be <a href="#Uniqueness_of_identifiers">unique</a>
1269 and not <a href="#Blank_identifier">blank</a>.
1275 String() string // illegal: String not unique
1276 _(x int) // illegal: method must have non-blank name
1281 More than one type may implement an interface.
1282 For instance, if two types <code>S1</code> and <code>S2</code>
1287 func (p T) Read(p []byte) (n int, err error)
1288 func (p T) Write(p []byte) (n int, err error)
1289 func (p T) Close() error
1293 (where <code>T</code> stands for either <code>S1</code> or <code>S2</code>)
1294 then the <code>File</code> interface is implemented by both <code>S1</code> and
1295 <code>S2</code>, regardless of what other methods
1296 <code>S1</code> and <code>S2</code> may have or share.
1300 A type implements any interface comprising any subset of its methods
1301 and may therefore implement several distinct interfaces. For
1302 instance, all types implement the <i>empty interface</i>:
1310 Similarly, consider this interface specification,
1311 which appears within a <a href="#Type_declarations">type declaration</a>
1312 to define an interface called <code>Locker</code>:
1316 type Locker interface {
1323 If <code>S1</code> and <code>S2</code> also implement
1327 func (p T) Lock() { … }
1328 func (p T) Unlock() { … }
1332 they implement the <code>Locker</code> interface as well
1333 as the <code>File</code> interface.
1337 An interface <code>T</code> may use a (possibly qualified) interface type
1338 name <code>E</code> in place of a method specification. This is called
1339 <i>embedding</i> interface <code>E</code> in <code>T</code>.
1340 The <a href="#Method_sets">method set</a> of <code>T</code> is the <i>union</i>
1341 of the method sets of <code>T</code>’s explicitly declared methods and of
1342 <code>T</code>’s embedded interfaces.
1346 type Reader interface {
1347 Read(p []byte) (n int, err error)
1351 type Writer interface {
1352 Write(p []byte) (n int, err error)
1356 // ReadWriter's methods are Read, Write, and Close.
1357 type ReadWriter interface {
1358 Reader // includes methods of Reader in ReadWriter's method set
1359 Writer // includes methods of Writer in ReadWriter's method set
1364 A <i>union</i> of method sets contains the (exported and non-exported)
1365 methods of each method set exactly once, and methods with the
1366 <a href="#Uniqueness_of_identifiers">same</a> names must
1367 have <a href="#Type_identity">identical</a> signatures.
1371 type ReadCloser interface {
1372 Reader // includes methods of Reader in ReadCloser's method set
1373 Close() // illegal: signatures of Reader.Close and Close are different
1378 An interface type <code>T</code> may not embed itself
1379 or any interface type that embeds <code>T</code>, recursively.
1383 // illegal: Bad cannot embed itself
1384 type Bad interface {
1388 // illegal: Bad1 cannot embed itself using Bad2
1389 type Bad1 interface {
1392 type Bad2 interface {
1397 <h3 id="Map_types">Map types</h3>
1400 A map is an unordered group of elements of one type, called the
1401 element type, indexed by a set of unique <i>keys</i> of another type,
1402 called the key type.
1403 The value of an uninitialized map is <code>nil</code>.
1407 MapType = "map" "[" KeyType "]" ElementType .
1412 The <a href="#Comparison_operators">comparison operators</a>
1413 <code>==</code> and <code>!=</code> must be fully defined
1414 for operands of the key type; thus the key type must not be a function, map, or
1416 If the key type is an interface type, these
1417 comparison operators must be defined for the dynamic key values;
1418 failure will cause a <a href="#Run_time_panics">run-time panic</a>.
1424 map[*T]struct{ x, y float64 }
1425 map[string]interface{}
1429 The number of map elements is called its length.
1430 For a map <code>m</code>, it can be discovered using the
1431 built-in function <a href="#Length_and_capacity"><code>len</code></a>
1432 and may change during execution. Elements may be added during execution
1433 using <a href="#Assignments">assignments</a> and retrieved with
1434 <a href="#Index_expressions">index expressions</a>; they may be removed with the
1435 <a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function.
1438 A new, empty map value is made using the built-in
1439 function <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1440 which takes the map type and an optional capacity hint as arguments:
1444 make(map[string]int)
1445 make(map[string]int, 100)
1449 The initial capacity does not bound its size:
1450 maps grow to accommodate the number of items
1451 stored in them, with the exception of <code>nil</code> maps.
1452 A <code>nil</code> map is equivalent to an empty map except that no elements
1455 <h3 id="Channel_types">Channel types</h3>
1458 A channel provides a mechanism for
1459 <a href="#Go_statements">concurrently executing functions</a>
1461 <a href="#Send_statements">sending</a> and
1462 <a href="#Receive_operator">receiving</a>
1463 values of a specified element type.
1464 The value of an uninitialized channel is <code>nil</code>.
1468 ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType .
1472 The optional <code><-</code> operator specifies the channel <i>direction</i>,
1473 <i>send</i> or <i>receive</i>. If no direction is given, the channel is
1474 <i>bidirectional</i>.
1475 A channel may be constrained only to send or only to receive by
1476 <a href="#Assignments">assignment</a> or
1477 explicit <a href="#Conversions">conversion</a>.
1481 chan T // can be used to send and receive values of type T
1482 chan<- float64 // can only be used to send float64s
1483 <-chan int // can only be used to receive ints
1487 The <code><-</code> operator associates with the leftmost <code>chan</code>
1492 chan<- chan int // same as chan<- (chan int)
1493 chan<- <-chan int // same as chan<- (<-chan int)
1494 <-chan <-chan int // same as <-chan (<-chan int)
1495 chan (<-chan int)
1499 A new, initialized channel
1500 value can be made using the built-in function
1501 <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1502 which takes the channel type and an optional <i>capacity</i> as arguments:
1510 The capacity, in number of elements, sets the size of the buffer in the channel.
1511 If the capacity is zero or absent, the channel is unbuffered and communication
1512 succeeds only when both a sender and receiver are ready. Otherwise, the channel
1513 is buffered and communication succeeds without blocking if the buffer
1514 is not full (sends) or not empty (receives).
1515 A <code>nil</code> channel is never ready for communication.
1519 A channel may be closed with the built-in function
1520 <a href="#Close"><code>close</code></a>.
1521 The multi-valued assignment form of the
1522 <a href="#Receive_operator">receive operator</a>
1523 reports whether a received value was sent before
1524 the channel was closed.
1528 A single channel may be used in
1529 <a href="#Send_statements">send statements</a>,
1530 <a href="#Receive_operator">receive operations</a>,
1531 and calls to the built-in functions
1532 <a href="#Length_and_capacity"><code>cap</code></a> and
1533 <a href="#Length_and_capacity"><code>len</code></a>
1534 by any number of goroutines without further synchronization.
1535 Channels act as first-in-first-out queues.
1536 For example, if one goroutine sends values on a channel
1537 and a second goroutine receives them, the values are
1538 received in the order sent.
1541 <h2 id="Properties_of_types_and_values">Properties of types and values</h2>
1543 <h3 id="Type_identity">Type identity</h3>
1546 Two types are either <i>identical</i> or <i>different</i>.
1550 A <a href="#Type_definitions">defined type</a> is always different from any other type.
1551 Otherwise, two types are identical if their <a href="#Types">underlying</a> type literals are
1552 structurally equivalent; that is, they have the same literal structure and corresponding
1553 components have identical types. In detail:
1557 <li>Two array types are identical if they have identical element types and
1558 the same array length.</li>
1560 <li>Two slice types are identical if they have identical element types.</li>
1562 <li>Two struct types are identical if they have the same sequence of fields,
1563 and if corresponding fields have the same names, and identical types,
1565 <a href="#Exported_identifiers">Non-exported</a> field names from different
1566 packages are always different.</li>
1568 <li>Two pointer types are identical if they have identical base types.</li>
1570 <li>Two function types are identical if they have the same number of parameters
1571 and result values, corresponding parameter and result types are
1572 identical, and either both functions are variadic or neither is.
1573 Parameter and result names are not required to match.</li>
1575 <li>Two interface types are identical if they have the same set of methods
1576 with the same names and identical function types.
1577 <a href="#Exported_identifiers">Non-exported</a> method names from different
1578 packages are always different. The order of the methods is irrelevant.</li>
1580 <li>Two map types are identical if they have identical key and element types.</li>
1582 <li>Two channel types are identical if they have identical element types and
1583 the same direction.</li>
1587 Given the declarations
1594 A2 = struct{ a, b int }
1596 A4 = func(A3, float64) *A0
1597 A5 = func(x int, _ float64) *[]string
1603 B2 struct{ a, b int }
1604 B3 struct{ a, c int }
1605 B4 func(int, float64) *B0
1606 B5 func(x int, y float64) *A1
1613 these types are identical:
1617 A0, A1, and []string
1618 A2 and struct{ a, b int }
1620 A4, func(int, float64) *[]string, and A5
1624 struct{ a, b *T5 } and struct{ a, b *T5 }
1625 func(x int, y float64) *[]string, func(int, float64) (result *[]string), and A5
1629 <code>B0</code> and <code>B1</code> are different because they are new types
1630 created by distinct <a href="#Type_definitions">type definitions</a>;
1631 <code>func(int, float64) *B0</code> and <code>func(x int, y float64) *[]string</code>
1632 are different because <code>B0</code> is different from <code>[]string</code>.
1636 <h3 id="Assignability">Assignability</h3>
1639 A value <code>x</code> is <i>assignable</i> to a <a href="#Variables">variable</a> of type <code>T</code>
1640 ("<code>x</code> is assignable to <code>T</code>") if one of the following conditions applies:
1645 <code>x</code>'s type is identical to <code>T</code>.
1648 <code>x</code>'s type <code>V</code> and <code>T</code> have identical
1649 <a href="#Types">underlying types</a> and at least one of <code>V</code>
1650 or <code>T</code> is not a <a href="#Type_definitions">defined</a> type.
1653 <code>T</code> is an interface type and
1654 <code>x</code> <a href="#Interface_types">implements</a> <code>T</code>.
1657 <code>x</code> is a bidirectional channel value, <code>T</code> is a channel type,
1658 <code>x</code>'s type <code>V</code> and <code>T</code> have identical element types,
1659 and at least one of <code>V</code> or <code>T</code> is not a defined type.
1662 <code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code>
1663 is a pointer, function, slice, map, channel, or interface type.
1666 <code>x</code> is an untyped <a href="#Constants">constant</a>
1667 <a href="#Representability">representable</a>
1668 by a value of type <code>T</code>.
1673 <h3 id="Representability">Representability</h3>
1676 A <a href="#Constants">constant</a> <code>x</code> is <i>representable</i>
1677 by a value of type <code>T</code> if one of the following conditions applies:
1682 <code>x</code> is in the set of values <a href="#Types">determined</a> by <code>T</code>.
1686 <code>T</code> is a floating-point type and <code>x</code> can be rounded to <code>T</code>'s
1687 precision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEE
1688 negative zero further simplified to an unsigned zero. Note that constant values never result
1689 in an IEEE negative zero, NaN, or infinity.
1693 <code>T</code> is a complex type, and <code>x</code>'s
1694 <a href="#Complex_numbers">components</a> <code>real(x)</code> and <code>imag(x)</code>
1695 are representable by values of <code>T</code>'s component type (<code>float32</code> or
1696 <code>float64</code>).
1701 x T x is representable by a value of T because
1703 'a' byte 97 is in the set of byte values
1704 97 rune rune is an alias for int32, and 97 is in the set of 32-bit integers
1705 "foo" string "foo" is in the set of string values
1706 1024 int16 1024 is in the set of 16-bit integers
1707 42.0 byte 42 is in the set of unsigned 8-bit integers
1708 1e10 uint64 10000000000 is in the set of unsigned 64-bit integers
1709 2.718281828459045 float32 2.718281828459045 rounds to 2.7182817 which is in the set of float32 values
1710 -1e-1000 float64 -1e-1000 rounds to IEEE -0.0 which is further simplified to 0.0
1711 0i int 0 is an integer value
1712 (42 + 0i) float32 42.0 (with zero imaginary part) is in the set of float32 values
1716 x T x is not representable by a value of T because
1718 0 bool 0 is not in the set of boolean values
1719 'a' string 'a' is a rune, it is not in the set of string values
1720 1024 byte 1024 is not in the set of unsigned 8-bit integers
1721 -1 uint16 -1 is not in the set of unsigned 16-bit integers
1722 1.1 int 1.1 is not an integer value
1723 42i float32 (0 + 42i) is not in the set of float32 values
1724 1e1000 float64 1e1000 overflows to IEEE +Inf after rounding
1728 <h2 id="Blocks">Blocks</h2>
1731 A <i>block</i> is a possibly empty sequence of declarations and statements
1732 within matching brace brackets.
1736 Block = "{" StatementList "}" .
1737 StatementList = { Statement ";" } .
1741 In addition to explicit blocks in the source code, there are implicit blocks:
1745 <li>The <i>universe block</i> encompasses all Go source text.</li>
1747 <li>Each <a href="#Packages">package</a> has a <i>package block</i> containing all
1748 Go source text for that package.</li>
1750 <li>Each file has a <i>file block</i> containing all Go source text
1753 <li>Each <a href="#If_statements">"if"</a>,
1754 <a href="#For_statements">"for"</a>, and
1755 <a href="#Switch_statements">"switch"</a>
1756 statement is considered to be in its own implicit block.</li>
1758 <li>Each clause in a <a href="#Switch_statements">"switch"</a>
1759 or <a href="#Select_statements">"select"</a> statement
1760 acts as an implicit block.</li>
1764 Blocks nest and influence <a href="#Declarations_and_scope">scoping</a>.
1768 <h2 id="Declarations_and_scope">Declarations and scope</h2>
1771 A <i>declaration</i> binds a non-<a href="#Blank_identifier">blank</a> identifier to a
1772 <a href="#Constant_declarations">constant</a>,
1773 <a href="#Type_declarations">type</a>,
1774 <a href="#Variable_declarations">variable</a>,
1775 <a href="#Function_declarations">function</a>,
1776 <a href="#Labeled_statements">label</a>, or
1777 <a href="#Import_declarations">package</a>.
1778 Every identifier in a program must be declared.
1779 No identifier may be declared twice in the same block, and
1780 no identifier may be declared in both the file and package block.
1784 The <a href="#Blank_identifier">blank identifier</a> may be used like any other identifier
1785 in a declaration, but it does not introduce a binding and thus is not declared.
1786 In the package block, the identifier <code>init</code> may only be used for
1787 <a href="#Package_initialization"><code>init</code> function</a> declarations,
1788 and like the blank identifier it does not introduce a new binding.
1792 Declaration = ConstDecl | TypeDecl | VarDecl .
1793 TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
1797 The <i>scope</i> of a declared identifier is the extent of source text in which
1798 the identifier denotes the specified constant, type, variable, function, label, or package.
1802 Go is lexically scoped using <a href="#Blocks">blocks</a>:
1806 <li>The scope of a <a href="#Predeclared_identifiers">predeclared identifier</a> is the universe block.</li>
1808 <li>The scope of an identifier denoting a constant, type, variable,
1809 or function (but not method) declared at top level (outside any
1810 function) is the package block.</li>
1812 <li>The scope of the package name of an imported package is the file block
1813 of the file containing the import declaration.</li>
1815 <li>The scope of an identifier denoting a method receiver, function parameter,
1816 or result variable is the function body.</li>
1818 <li>The scope of a constant or variable identifier declared
1819 inside a function begins at the end of the ConstSpec or VarSpec
1820 (ShortVarDecl for short variable declarations)
1821 and ends at the end of the innermost containing block.</li>
1823 <li>The scope of a type identifier declared inside a function
1824 begins at the identifier in the TypeSpec
1825 and ends at the end of the innermost containing block.</li>
1829 An identifier declared in a block may be redeclared in an inner block.
1830 While the identifier of the inner declaration is in scope, it denotes
1831 the entity declared by the inner declaration.
1835 The <a href="#Package_clause">package clause</a> is not a declaration; the package name
1836 does not appear in any scope. Its purpose is to identify the files belonging
1837 to the same <a href="#Packages">package</a> and to specify the default package name for import
1842 <h3 id="Label_scopes">Label scopes</h3>
1845 Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are
1846 used in the <a href="#Break_statements">"break"</a>,
1847 <a href="#Continue_statements">"continue"</a>, and
1848 <a href="#Goto_statements">"goto"</a> statements.
1849 It is illegal to define a label that is never used.
1850 In contrast to other identifiers, labels are not block scoped and do
1851 not conflict with identifiers that are not labels. The scope of a label
1852 is the body of the function in which it is declared and excludes
1853 the body of any nested function.
1857 <h3 id="Blank_identifier">Blank identifier</h3>
1860 The <i>blank identifier</i> is represented by the underscore character <code>_</code>.
1861 It serves as an anonymous placeholder instead of a regular (non-blank)
1862 identifier and has special meaning in <a href="#Declarations_and_scope">declarations</a>,
1863 as an <a href="#Operands">operand</a>, and in <a href="#Assignments">assignments</a>.
1867 <h3 id="Predeclared_identifiers">Predeclared identifiers</h3>
1870 The following identifiers are implicitly declared in the
1871 <a href="#Blocks">universe block</a>:
1873 <pre class="grammar">
1875 bool byte complex64 complex128 error float32 float64
1876 int int8 int16 int32 int64 rune string
1877 uint uint8 uint16 uint32 uint64 uintptr
1886 append cap close complex copy delete imag len
1887 make new panic print println real recover
1891 <h3 id="Exported_identifiers">Exported identifiers</h3>
1894 An identifier may be <i>exported</i> to permit access to it from another package.
1895 An identifier is exported if both:
1898 <li>the first character of the identifier's name is a Unicode upper case
1899 letter (Unicode class "Lu"); and</li>
1900 <li>the identifier is declared in the <a href="#Blocks">package block</a>
1901 or it is a <a href="#Struct_types">field name</a> or
1902 <a href="#MethodName">method name</a>.</li>
1905 All other identifiers are not exported.
1909 <h3 id="Uniqueness_of_identifiers">Uniqueness of identifiers</h3>
1912 Given a set of identifiers, an identifier is called <i>unique</i> if it is
1913 <i>different</i> from every other in the set.
1914 Two identifiers are different if they are spelled differently, or if they
1915 appear in different <a href="#Packages">packages</a> and are not
1916 <a href="#Exported_identifiers">exported</a>. Otherwise, they are the same.
1919 <h3 id="Constant_declarations">Constant declarations</h3>
1922 A constant declaration binds a list of identifiers (the names of
1923 the constants) to the values of a list of <a href="#Constant_expressions">constant expressions</a>.
1924 The number of identifiers must be equal
1925 to the number of expressions, and the <i>n</i>th identifier on
1926 the left is bound to the value of the <i>n</i>th expression on the
1931 ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1932 ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
1934 IdentifierList = identifier { "," identifier } .
1935 ExpressionList = Expression { "," Expression } .
1939 If the type is present, all constants take the type specified, and
1940 the expressions must be <a href="#Assignability">assignable</a> to that type.
1941 If the type is omitted, the constants take the
1942 individual types of the corresponding expressions.
1943 If the expression values are untyped <a href="#Constants">constants</a>,
1944 the declared constants remain untyped and the constant identifiers
1945 denote the constant values. For instance, if the expression is a
1946 floating-point literal, the constant identifier denotes a floating-point
1947 constant, even if the literal's fractional part is zero.
1951 const Pi float64 = 3.14159265358979323846
1952 const zero = 0.0 // untyped floating-point constant
1955 eof = -1 // untyped integer constant
1957 const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants
1958 const u, v float32 = 0, 3 // u = 0.0, v = 3.0
1962 Within a parenthesized <code>const</code> declaration list the
1963 expression list may be omitted from any but the first ConstSpec.
1964 Such an empty list is equivalent to the textual substitution of the
1965 first preceding non-empty expression list and its type if any.
1966 Omitting the list of expressions is therefore equivalent to
1967 repeating the previous list. The number of identifiers must be equal
1968 to the number of expressions in the previous list.
1969 Together with the <a href="#Iota"><code>iota</code> constant generator</a>
1970 this mechanism permits light-weight declaration of sequential values:
1982 numberOfDays // this constant is not exported
1987 <h3 id="Iota">Iota</h3>
1990 Within a <a href="#Constant_declarations">constant declaration</a>, the predeclared identifier
1991 <code>iota</code> represents successive untyped integer <a href="#Constants">
1992 constants</a>. Its value is the index of the respective <a href="#ConstSpec">ConstSpec</a>
1993 in that constant declaration, starting at zero.
1994 It can be used to construct a set of related constants:
1999 c0 = iota // c0 == 0
2000 c1 = iota // c1 == 1
2001 c2 = iota // c2 == 2
2005 a = 1 << iota // a == 1 (iota == 0)
2006 b = 1 << iota // b == 2 (iota == 1)
2007 c = 3 // c == 3 (iota == 2, unused)
2008 d = 1 << iota // d == 8 (iota == 3)
2012 u = iota * 42 // u == 0 (untyped integer constant)
2013 v float64 = iota * 42 // v == 42.0 (float64 constant)
2014 w = iota * 42 // w == 84 (untyped integer constant)
2017 const x = iota // x == 0
2018 const y = iota // y == 0
2022 By definition, multiple uses of <code>iota</code> in the same ConstSpec all have the same value:
2027 bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 (iota == 0)
2028 bit1, mask1 // bit1 == 2, mask1 == 1 (iota == 1)
2029 _, _ // (iota == 2, unused)
2030 bit3, mask3 // bit3 == 8, mask3 == 7 (iota == 3)
2035 This last example exploits the <a href="#Constant_declarations">implicit repetition</a>
2036 of the last non-empty expression list.
2040 <h3 id="Type_declarations">Type declarations</h3>
2043 A type declaration binds an identifier, the <i>type name</i>, to a <a href="#Types">type</a>.
2044 Type declarations come in two forms: alias declarations and type definitions.
2048 TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
2049 TypeSpec = AliasDecl | TypeDef .
2052 <h4 id="Alias_declarations">Alias declarations</h4>
2055 An alias declaration binds an identifier to the given type.
2059 AliasDecl = identifier "=" Type .
2063 Within the <a href="#Declarations_and_scope">scope</a> of
2064 the identifier, it serves as an <i>alias</i> for the type.
2069 nodeList = []*Node // nodeList and []*Node are identical types
2070 Polar = polar // Polar and polar denote identical types
2075 <h4 id="Type_definitions">Type definitions</h4>
2078 A type definition creates a new, distinct type with the same
2079 <a href="#Types">underlying type</a> and operations as the given type,
2080 and binds an identifier to it.
2084 TypeDef = identifier Type .
2088 The new type is called a <i>defined type</i>.
2089 It is <a href="#Type_identity">different</a> from any other type,
2090 including the type it is created from.
2095 Point struct{ x, y float64 } // Point and struct{ x, y float64 } are different types
2096 polar Point // polar and Point denote different types
2099 type TreeNode struct {
2100 left, right *TreeNode
2104 type Block interface {
2106 Encrypt(src, dst []byte)
2107 Decrypt(src, dst []byte)
2112 A defined type may have <a href="#Method_declarations">methods</a> associated with it.
2113 It does not inherit any methods bound to the given type,
2114 but the <a href="#Method_sets">method set</a>
2115 of an interface type or of elements of a composite type remains unchanged:
2119 // A Mutex is a data type with two methods, Lock and Unlock.
2120 type Mutex struct { /* Mutex fields */ }
2121 func (m *Mutex) Lock() { /* Lock implementation */ }
2122 func (m *Mutex) Unlock() { /* Unlock implementation */ }
2124 // NewMutex has the same composition as Mutex but its method set is empty.
2127 // The method set of PtrMutex's underlying type *Mutex remains unchanged,
2128 // but the method set of PtrMutex is empty.
2129 type PtrMutex *Mutex
2131 // The method set of *PrintableMutex contains the methods
2132 // Lock and Unlock bound to its embedded field Mutex.
2133 type PrintableMutex struct {
2137 // MyBlock is an interface type that has the same method set as Block.
2142 Type definitions may be used to define different boolean, numeric,
2143 or string types and associate methods with them:
2150 EST TimeZone = -(5 + iota)
2156 func (tz TimeZone) String() string {
2157 return fmt.Sprintf("GMT%+dh", tz)
2162 <h3 id="Variable_declarations">Variable declarations</h3>
2165 A variable declaration creates one or more <a href="#Variables">variables</a>,
2166 binds corresponding identifiers to them, and gives each a type and an initial value.
2170 VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
2171 VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
2178 var x, y float32 = -1, -2
2181 u, v, s = 2.0, 3.0, "bar"
2183 var re, im = complexSqrt(-1)
2184 var _, found = entries[name] // map lookup; only interested in "found"
2188 If a list of expressions is given, the variables are initialized
2189 with the expressions following the rules for <a href="#Assignments">assignments</a>.
2190 Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>.
2194 If a type is present, each variable is given that type.
2195 Otherwise, each variable is given the type of the corresponding
2196 initialization value in the assignment.
2197 If that value is an untyped constant, it is first implicitly
2198 <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>;
2199 if it is an untyped boolean value, it is first implicitly converted to type <code>bool</code>.
2200 The predeclared value <code>nil</code> cannot be used to initialize a variable
2201 with no explicit type.
2205 var d = math.Sin(0.5) // d is float64
2206 var i = 42 // i is int
2207 var t, ok = x.(T) // t is T, ok is bool
2208 var n = nil // illegal
2212 Implementation restriction: A compiler may make it illegal to declare a variable
2213 inside a <a href="#Function_declarations">function body</a> if the variable is
2217 <h3 id="Short_variable_declarations">Short variable declarations</h3>
2220 A <i>short variable declaration</i> uses the syntax:
2224 ShortVarDecl = IdentifierList ":=" ExpressionList .
2228 It is shorthand for a regular <a href="#Variable_declarations">variable declaration</a>
2229 with initializer expressions but no types:
2232 <pre class="grammar">
2233 "var" IdentifierList = ExpressionList .
2238 f := func() int { return 7 }
2239 ch := make(chan int)
2240 r, w, _ := os.Pipe() // os.Pipe() returns a connected pair of Files and an error, if any
2241 _, y, _ := coord(p) // coord() returns three values; only interested in y coordinate
2245 Unlike regular variable declarations, a short variable declaration may <i>redeclare</i>
2246 variables provided they were originally declared earlier in the same block
2247 (or the parameter lists if the block is the function body) with the same type,
2248 and at least one of the non-<a href="#Blank_identifier">blank</a> variables is new.
2249 As a consequence, redeclaration can only appear in a multi-variable short declaration.
2250 Redeclaration does not introduce a new variable; it just assigns a new value to the original.
2254 field1, offset := nextField(str, 0)
2255 field2, offset := nextField(str, offset) // redeclares offset
2256 a, a := 1, 2 // illegal: double declaration of a or no new variable if a was declared elsewhere
2260 Short variable declarations may appear only inside functions.
2261 In some contexts such as the initializers for
2262 <a href="#If_statements">"if"</a>,
2263 <a href="#For_statements">"for"</a>, or
2264 <a href="#Switch_statements">"switch"</a> statements,
2265 they can be used to declare local temporary variables.
2268 <h3 id="Function_declarations">Function declarations</h3>
2271 A function declaration binds an identifier, the <i>function name</i>,
2276 FunctionDecl = "func" FunctionName Signature [ FunctionBody ] .
2277 FunctionName = identifier .
2278 FunctionBody = Block .
2282 If the function's <a href="#Function_types">signature</a> declares
2283 result parameters, the function body's statement list must end in
2284 a <a href="#Terminating_statements">terminating statement</a>.
2288 func IndexRune(s string, r rune) int {
2289 for i, c := range s {
2294 // invalid: missing return statement
2299 A function declaration may omit the body. Such a declaration provides the
2300 signature for a function implemented outside Go, such as an assembly routine.
2304 func min(x int, y int) int {
2311 func flushICache(begin, end uintptr) // implemented externally
2314 <h3 id="Method_declarations">Method declarations</h3>
2317 A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>.
2318 A method declaration binds an identifier, the <i>method name</i>, to a method,
2319 and associates the method with the receiver's <i>base type</i>.
2323 MethodDecl = "func" Receiver MethodName Signature [ FunctionBody ] .
2324 Receiver = Parameters .
2328 The receiver is specified via an extra parameter section preceding the method
2329 name. That parameter section must declare a single non-variadic parameter, the receiver.
2330 Its type must be a <a href="#Type_definitions">defined</a> type <code>T</code> or a
2331 pointer to a defined type <code>T</code>. <code>T</code> is called the receiver
2332 <i>base type</i>. A receiver base type cannot be a pointer or interface type and
2333 it must be defined in the same package as the method.
2334 The method is said to be <i>bound</i> to its receiver base type and the method name
2335 is visible only within <a href="#Selectors">selectors</a> for type <code>T</code>
2340 A non-<a href="#Blank_identifier">blank</a> receiver identifier must be
2341 <a href="#Uniqueness_of_identifiers">unique</a> in the method signature.
2342 If the receiver's value is not referenced inside the body of the method,
2343 its identifier may be omitted in the declaration. The same applies in
2344 general to parameters of functions and methods.
2348 For a base type, the non-blank names of methods bound to it must be unique.
2349 If the base type is a <a href="#Struct_types">struct type</a>,
2350 the non-blank method and field names must be distinct.
2354 Given defined type <code>Point</code>, the declarations
2358 func (p *Point) Length() float64 {
2359 return math.Sqrt(p.x * p.x + p.y * p.y)
2362 func (p *Point) Scale(factor float64) {
2369 bind the methods <code>Length</code> and <code>Scale</code>,
2370 with receiver type <code>*Point</code>,
2371 to the base type <code>Point</code>.
2375 The type of a method is the type of a function with the receiver as first
2376 argument. For instance, the method <code>Scale</code> has type
2380 func(p *Point, factor float64)
2384 However, a function declared this way is not a method.
2388 <h2 id="Expressions">Expressions</h2>
2391 An expression specifies the computation of a value by applying
2392 operators and functions to operands.
2395 <h3 id="Operands">Operands</h3>
2398 Operands denote the elementary values in an expression. An operand may be a
2399 literal, a (possibly <a href="#Qualified_identifiers">qualified</a>)
2400 non-<a href="#Blank_identifier">blank</a> identifier denoting a
2401 <a href="#Constant_declarations">constant</a>,
2402 <a href="#Variable_declarations">variable</a>, or
2403 <a href="#Function_declarations">function</a>,
2404 or a parenthesized expression.
2408 The <a href="#Blank_identifier">blank identifier</a> may appear as an
2409 operand only on the left-hand side of an <a href="#Assignments">assignment</a>.
2413 Operand = Literal | OperandName | "(" Expression ")" .
2414 Literal = BasicLit | CompositeLit | FunctionLit .
2415 BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
2416 OperandName = identifier | QualifiedIdent .
2419 <h3 id="Qualified_identifiers">Qualified identifiers</h3>
2422 A qualified identifier is an identifier qualified with a package name prefix.
2423 Both the package name and the identifier must not be
2424 <a href="#Blank_identifier">blank</a>.
2428 QualifiedIdent = PackageName "." identifier .
2432 A qualified identifier accesses an identifier in a different package, which
2433 must be <a href="#Import_declarations">imported</a>.
2434 The identifier must be <a href="#Exported_identifiers">exported</a> and
2435 declared in the <a href="#Blocks">package block</a> of that package.
2439 math.Sin // denotes the Sin function in package math
2442 <h3 id="Composite_literals">Composite literals</h3>
2445 Composite literals construct values for structs, arrays, slices, and maps
2446 and create a new value each time they are evaluated.
2447 They consist of the type of the literal followed by a brace-bound list of elements.
2448 Each element may optionally be preceded by a corresponding key.
2452 CompositeLit = LiteralType LiteralValue .
2453 LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
2454 SliceType | MapType | TypeName .
2455 LiteralValue = "{" [ ElementList [ "," ] ] "}" .
2456 ElementList = KeyedElement { "," KeyedElement } .
2457 KeyedElement = [ Key ":" ] Element .
2458 Key = FieldName | Expression | LiteralValue .
2459 FieldName = identifier .
2460 Element = Expression | LiteralValue .
2464 The LiteralType's underlying type must be a struct, array, slice, or map type
2465 (the grammar enforces this constraint except when the type is given
2467 The types of the elements and keys must be <a href="#Assignability">assignable</a>
2468 to the respective field, element, and key types of the literal type;
2469 there is no additional conversion.
2470 The key is interpreted as a field name for struct literals,
2471 an index for array and slice literals, and a key for map literals.
2472 For map literals, all elements must have a key. It is an error
2473 to specify multiple elements with the same field name or
2474 constant key value. For non-constant map keys, see the section on
2475 <a href="#Order_of_evaluation">evaluation order</a>.
2479 For struct literals the following rules apply:
2482 <li>A key must be a field name declared in the struct type.
2484 <li>An element list that does not contain any keys must
2485 list an element for each struct field in the
2486 order in which the fields are declared.
2488 <li>If any element has a key, every element must have a key.
2490 <li>An element list that contains keys does not need to
2491 have an element for each struct field. Omitted fields
2492 get the zero value for that field.
2494 <li>A literal may omit the element list; such a literal evaluates
2495 to the zero value for its type.
2497 <li>It is an error to specify an element for a non-exported
2498 field of a struct belonging to a different package.
2503 Given the declarations
2506 type Point3D struct { x, y, z float64 }
2507 type Line struct { p, q Point3D }
2515 origin := Point3D{} // zero value for Point3D
2516 line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x
2520 For array and slice literals the following rules apply:
2523 <li>Each element has an associated integer index marking
2524 its position in the array.
2526 <li>An element with a key uses the key as its index. The
2527 key must be a non-negative constant
2528 <a href="#Representability">representable</a> by
2529 a value of type <code>int</code>; and if it is typed
2530 it must be of integer type.
2532 <li>An element without a key uses the previous element's index plus one.
2533 If the first element has no key, its index is zero.
2538 <a href="#Address_operators">Taking the address</a> of a composite literal
2539 generates a pointer to a unique <a href="#Variables">variable</a> initialized
2540 with the literal's value.
2544 var pointer *Point3D = &Point3D{y: 1000}
2548 Note that the <a href="#The_zero_value">zero value</a> for a slice or map
2549 type is not the same as an initialized but empty value of the same type.
2550 Consequently, taking the address of an empty slice or map composite literal
2551 does not have the same effect as allocating a new slice or map value with
2552 <a href="#Allocation">new</a>.
2556 p1 := &[]int{} // p1 points to an initialized, empty slice with value []int{} and length 0
2557 p2 := new([]int) // p2 points to an uninitialized slice with value nil and length 0
2561 The length of an array literal is the length specified in the literal type.
2562 If fewer elements than the length are provided in the literal, the missing
2563 elements are set to the zero value for the array element type.
2564 It is an error to provide elements with index values outside the index range
2565 of the array. The notation <code>...</code> specifies an array length equal
2566 to the maximum element index plus one.
2570 buffer := [10]string{} // len(buffer) == 10
2571 intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6
2572 days := [...]string{"Sat", "Sun"} // len(days) == 2
2576 A slice literal describes the entire underlying array literal.
2577 Thus the length and capacity of a slice literal are the maximum
2578 element index plus one. A slice literal has the form
2586 and is shorthand for a slice operation applied to an array:
2590 tmp := [n]T{x1, x2, … xn}
2595 Within a composite literal of array, slice, or map type <code>T</code>,
2596 elements or map keys that are themselves composite literals may elide the respective
2597 literal type if it is identical to the element or key type of <code>T</code>.
2598 Similarly, elements or keys that are addresses of composite literals may elide
2599 the <code>&T</code> when the element or key type is <code>*T</code>.
2603 [...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}}
2604 [][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}}
2605 [][]Point{{{0, 1}, {1, 2}}} // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}}
2606 map[string]Point{"orig": {0, 0}} // same as map[string]Point{"orig": Point{0, 0}}
2607 map[Point]string{{0, 0}: "orig"} // same as map[Point]string{Point{0, 0}: "orig"}
2610 [2]*Point{{1.5, -3.5}, {}} // same as [2]*Point{&Point{1.5, -3.5}, &Point{}}
2611 [2]PPoint{{1.5, -3.5}, {}} // same as [2]PPoint{PPoint(&Point{1.5, -3.5}), PPoint(&Point{})}
2615 A parsing ambiguity arises when a composite literal using the
2616 TypeName form of the LiteralType appears as an operand between the
2617 <a href="#Keywords">keyword</a> and the opening brace of the block
2618 of an "if", "for", or "switch" statement, and the composite literal
2619 is not enclosed in parentheses, square brackets, or curly braces.
2620 In this rare case, the opening brace of the literal is erroneously parsed
2621 as the one introducing the block of statements. To resolve the ambiguity,
2622 the composite literal must appear within parentheses.
2626 if x == (T{a,b,c}[i]) { … }
2627 if (x == T{a,b,c}[i]) { … }
2631 Examples of valid array, slice, and map literals:
2635 // list of prime numbers
2636 primes := []int{2, 3, 5, 7, 9, 2147483647}
2638 // vowels[ch] is true if ch is a vowel
2639 vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}
2641 // the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1}
2642 filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1}
2644 // frequencies in Hz for equal-tempered scale (A4 = 440Hz)
2645 noteFrequency := map[string]float32{
2646 "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83,
2647 "G0": 24.50, "A0": 27.50, "B0": 30.87,
2652 <h3 id="Function_literals">Function literals</h3>
2655 A function literal represents an anonymous <a href="#Function_declarations">function</a>.
2659 FunctionLit = "func" Signature FunctionBody .
2663 func(a, b int, z float64) bool { return a*b < int(z) }
2667 A function literal can be assigned to a variable or invoked directly.
2671 f := func(x, y int) int { return x + y }
2672 func(ch chan int) { ch <- ACK }(replyChan)
2676 Function literals are <i>closures</i>: they may refer to variables
2677 defined in a surrounding function. Those variables are then shared between
2678 the surrounding function and the function literal, and they survive as long
2679 as they are accessible.
2683 <h3 id="Primary_expressions">Primary expressions</h3>
2686 Primary expressions are the operands for unary and binary expressions.
2694 PrimaryExpr Selector |
2697 PrimaryExpr TypeAssertion |
2698 PrimaryExpr Arguments .
2700 Selector = "." identifier .
2701 Index = "[" Expression "]" .
2702 Slice = "[" [ Expression ] ":" [ Expression ] "]" |
2703 "[" [ Expression ] ":" Expression ":" Expression "]" .
2704 TypeAssertion = "." "(" Type ")" .
2705 Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
2722 <h3 id="Selectors">Selectors</h3>
2725 For a <a href="#Primary_expressions">primary expression</a> <code>x</code>
2726 that is not a <a href="#Package_clause">package name</a>, the
2727 <i>selector expression</i>
2735 denotes the field or method <code>f</code> of the value <code>x</code>
2736 (or sometimes <code>*x</code>; see below).
2737 The identifier <code>f</code> is called the (field or method) <i>selector</i>;
2738 it must not be the <a href="#Blank_identifier">blank identifier</a>.
2739 The type of the selector expression is the type of <code>f</code>.
2740 If <code>x</code> is a package name, see the section on
2741 <a href="#Qualified_identifiers">qualified identifiers</a>.
2745 A selector <code>f</code> may denote a field or method <code>f</code> of
2746 a type <code>T</code>, or it may refer
2747 to a field or method <code>f</code> of a nested
2748 <a href="#Struct_types">embedded field</a> of <code>T</code>.
2749 The number of embedded fields traversed
2750 to reach <code>f</code> is called its <i>depth</i> in <code>T</code>.
2751 The depth of a field or method <code>f</code>
2752 declared in <code>T</code> is zero.
2753 The depth of a field or method <code>f</code> declared in
2754 an embedded field <code>A</code> in <code>T</code> is the
2755 depth of <code>f</code> in <code>A</code> plus one.
2759 The following rules apply to selectors:
2764 For a value <code>x</code> of type <code>T</code> or <code>*T</code>
2765 where <code>T</code> is not a pointer or interface type,
2766 <code>x.f</code> denotes the field or method at the shallowest depth
2767 in <code>T</code> where there
2768 is such an <code>f</code>.
2769 If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a>
2770 with shallowest depth, the selector expression is illegal.
2774 For a value <code>x</code> of type <code>I</code> where <code>I</code>
2775 is an interface type, <code>x.f</code> denotes the actual method with name
2776 <code>f</code> of the dynamic value of <code>x</code>.
2777 If there is no method with name <code>f</code> in the
2778 <a href="#Method_sets">method set</a> of <code>I</code>, the selector
2779 expression is illegal.
2783 As an exception, if the type of <code>x</code> is a <a href="#Type_definitions">defined</a>
2784 pointer type and <code>(*x).f</code> is a valid selector expression denoting a field
2785 (but not a method), <code>x.f</code> is shorthand for <code>(*x).f</code>.
2789 In all other cases, <code>x.f</code> is illegal.
2793 If <code>x</code> is of pointer type and has the value
2794 <code>nil</code> and <code>x.f</code> denotes a struct field,
2795 assigning to or evaluating <code>x.f</code>
2796 causes a <a href="#Run_time_panics">run-time panic</a>.
2800 If <code>x</code> is of interface type and has the value
2801 <code>nil</code>, <a href="#Calls">calling</a> or
2802 <a href="#Method_values">evaluating</a> the method <code>x.f</code>
2803 causes a <a href="#Run_time_panics">run-time panic</a>.
2808 For example, given the declarations:
2834 var t T2 // with t.T0 != nil
2835 var p *T2 // with p != nil and (*p).T0 != nil
2852 q.x // (*(*q).T0).x (*q).x is a valid field selector
2854 p.M0() // ((*p).T0).M0() M0 expects *T0 receiver
2855 p.M1() // ((*p).T1).M1() M1 expects T1 receiver
2856 p.M2() // p.M2() M2 expects *T2 receiver
2857 t.M2() // (&t).M2() M2 expects *T2 receiver, see section on Calls
2861 but the following is invalid:
2865 q.M0() // (*q).M0 is valid but not a field selector
2869 <h3 id="Method_expressions">Method expressions</h3>
2872 If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
2873 <code>T.M</code> is a function that is callable as a regular function
2874 with the same arguments as <code>M</code> prefixed by an additional
2875 argument that is the receiver of the method.
2879 MethodExpr = ReceiverType "." MethodName .
2880 ReceiverType = Type .
2884 Consider a struct type <code>T</code> with two methods,
2885 <code>Mv</code>, whose receiver is of type <code>T</code>, and
2886 <code>Mp</code>, whose receiver is of type <code>*T</code>.
2893 func (tv T) Mv(a int) int { return 0 } // value receiver
2894 func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
2908 yields a function equivalent to <code>Mv</code> but
2909 with an explicit receiver as its first argument; it has signature
2913 func(tv T, a int) int
2917 That function may be called normally with an explicit receiver, so
2918 these five invocations are equivalent:
2925 f1 := T.Mv; f1(t, 7)
2926 f2 := (T).Mv; f2(t, 7)
2930 Similarly, the expression
2938 yields a function value representing <code>Mp</code> with signature
2942 func(tp *T, f float32) float32
2946 For a method with a value receiver, one can derive a function
2947 with an explicit pointer receiver, so
2955 yields a function value representing <code>Mv</code> with signature
2959 func(tv *T, a int) int
2963 Such a function indirects through the receiver to create a value
2964 to pass as the receiver to the underlying method;
2965 the method does not overwrite the value whose address is passed in
2970 The final case, a value-receiver function for a pointer-receiver method,
2971 is illegal because pointer-receiver methods are not in the method set
2976 Function values derived from methods are called with function call syntax;
2977 the receiver is provided as the first argument to the call.
2978 That is, given <code>f := T.Mv</code>, <code>f</code> is invoked
2979 as <code>f(t, 7)</code> not <code>t.f(7)</code>.
2980 To construct a function that binds the receiver, use a
2981 <a href="#Function_literals">function literal</a> or
2982 <a href="#Method_values">method value</a>.
2986 It is legal to derive a function value from a method of an interface type.
2987 The resulting function takes an explicit receiver of that interface type.
2990 <h3 id="Method_values">Method values</h3>
2993 If the expression <code>x</code> has static type <code>T</code> and
2994 <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
2995 <code>x.M</code> is called a <i>method value</i>.
2996 The method value <code>x.M</code> is a function value that is callable
2997 with the same arguments as a method call of <code>x.M</code>.
2998 The expression <code>x</code> is evaluated and saved during the evaluation of the
2999 method value; the saved copy is then used as the receiver in any calls,
3000 which may be executed later.
3004 type S struct { *T }
3006 func (t T) M() { print(t) }
3010 f := t.M // receiver *t is evaluated and stored in f
3011 g := s.M // receiver *(s.T) is evaluated and stored in g
3012 *t = 42 // does not affect stored receivers in f and g
3016 The type <code>T</code> may be an interface or non-interface type.
3020 As in the discussion of <a href="#Method_expressions">method expressions</a> above,
3021 consider a struct type <code>T</code> with two methods,
3022 <code>Mv</code>, whose receiver is of type <code>T</code>, and
3023 <code>Mp</code>, whose receiver is of type <code>*T</code>.
3030 func (tv T) Mv(a int) int { return 0 } // value receiver
3031 func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
3047 yields a function value of type
3055 These two invocations are equivalent:
3064 Similarly, the expression
3072 yields a function value of type
3076 func(float32) float32
3080 As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver
3081 using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>.
3085 As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver
3086 using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&t).Mp</code>.
3090 f := t.Mv; f(7) // like t.Mv(7)
3091 f := pt.Mp; f(7) // like pt.Mp(7)
3092 f := pt.Mv; f(7) // like (*pt).Mv(7)
3093 f := t.Mp; f(7) // like (&t).Mp(7)
3094 f := makeT().Mp // invalid: result of makeT() is not addressable
3098 Although the examples above use non-interface types, it is also legal to create a method value
3099 from a value of interface type.
3103 var i interface { M(int) } = myVal
3104 f := i.M; f(7) // like i.M(7)
3108 <h3 id="Index_expressions">Index expressions</h3>
3111 A primary expression of the form
3119 denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>.
3120 The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively.
3121 The following rules apply:
3125 If <code>a</code> is not a map:
3128 <li>the index <code>x</code> must be of integer type or an untyped constant</li>
3129 <li>a constant index must be non-negative and
3130 <a href="#Representability">representable</a> by a value of type <code>int</code></li>
3131 <li>a constant index that is untyped is given type <code>int</code></li>
3132 <li>the index <code>x</code> is <i>in range</i> if <code>0 <= x < len(a)</code>,
3133 otherwise it is <i>out of range</i></li>
3137 For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>:
3140 <li>a <a href="#Constants">constant</a> index must be in range</li>
3141 <li>if <code>x</code> is out of range at run time,
3142 a <a href="#Run_time_panics">run-time panic</a> occurs</li>
3143 <li><code>a[x]</code> is the array element at index <code>x</code> and the type of
3144 <code>a[x]</code> is the element type of <code>A</code></li>
3148 For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type:
3151 <li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li>
3155 For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>:
3158 <li>if <code>x</code> is out of range at run time,
3159 a <a href="#Run_time_panics">run-time panic</a> occurs</li>
3160 <li><code>a[x]</code> is the slice element at index <code>x</code> and the type of
3161 <code>a[x]</code> is the element type of <code>S</code></li>
3165 For <code>a</code> of <a href="#String_types">string type</a>:
3168 <li>a <a href="#Constants">constant</a> index must be in range
3169 if the string <code>a</code> is also constant</li>
3170 <li>if <code>x</code> is out of range at run time,
3171 a <a href="#Run_time_panics">run-time panic</a> occurs</li>
3172 <li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of
3173 <code>a[x]</code> is <code>byte</code></li>
3174 <li><code>a[x]</code> may not be assigned to</li>
3178 For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>:
3181 <li><code>x</code>'s type must be
3182 <a href="#Assignability">assignable</a>
3183 to the key type of <code>M</code></li>
3184 <li>if the map contains an entry with key <code>x</code>,
3185 <code>a[x]</code> is the map element with key <code>x</code>
3186 and the type of <code>a[x]</code> is the element type of <code>M</code></li>
3187 <li>if the map is <code>nil</code> or does not contain such an entry,
3188 <code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
3189 for the element type of <code>M</code></li>
3193 Otherwise <code>a[x]</code> is illegal.
3197 An index expression on a map <code>a</code> of type <code>map[K]V</code>
3198 used in an <a href="#Assignments">assignment</a> or initialization of the special form
3208 yields an additional untyped boolean value. The value of <code>ok</code> is
3209 <code>true</code> if the key <code>x</code> is present in the map, and
3210 <code>false</code> otherwise.
3214 Assigning to an element of a <code>nil</code> map causes a
3215 <a href="#Run_time_panics">run-time panic</a>.
3219 <h3 id="Slice_expressions">Slice expressions</h3>
3222 Slice expressions construct a substring or slice from a string, array, pointer
3223 to array, or slice. There are two variants: a simple form that specifies a low
3224 and high bound, and a full form that also specifies a bound on the capacity.
3227 <h4>Simple slice expressions</h4>
3230 For a string, array, pointer to array, or slice <code>a</code>, the primary expression
3238 constructs a substring or slice. The <i>indices</i> <code>low</code> and
3239 <code>high</code> select which elements of operand <code>a</code> appear
3240 in the result. The result has indices starting at 0 and length equal to
3241 <code>high</code> - <code>low</code>.
3242 After slicing the array <code>a</code>
3246 a := [5]int{1, 2, 3, 4, 5}
3251 the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements
3261 For convenience, any of the indices may be omitted. A missing <code>low</code>
3262 index defaults to zero; a missing <code>high</code> index defaults to the length of the
3267 a[2:] // same as a[2 : len(a)]
3268 a[:3] // same as a[0 : 3]
3269 a[:] // same as a[0 : len(a)]
3273 If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for
3274 <code>(*a)[low : high]</code>.
3278 For arrays or strings, the indices are <i>in range</i> if
3279 <code>0</code> <= <code>low</code> <= <code>high</code> <= <code>len(a)</code>,
3280 otherwise they are <i>out of range</i>.
3281 For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length.
3282 A <a href="#Constants">constant</a> index must be non-negative and
3283 <a href="#Representability">representable</a> by a value of type
3284 <code>int</code>; for arrays or constant strings, constant indices must also be in range.
3285 If both indices are constant, they must satisfy <code>low <= high</code>.
3286 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3290 Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice,
3291 the result of the slice operation is a non-constant value of the same type as the operand.
3292 For untyped string operands the result is a non-constant value of type <code>string</code>.
3293 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>
3294 and the result of the slice operation is a slice with the same element type as the array.
3298 If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result
3299 is a <code>nil</code> slice. Otherwise, if the result is a slice, it shares its underlying
3300 array with the operand.
3305 s1 := a[3:7] // underlying array of s1 is array a; &s1[2] == &a[5]
3306 s2 := s1[1:4] // underlying array of s2 is underlying array of s1 which is array a; &s2[1] == &a[5]
3307 s2[1] = 42 // s2[1] == s1[2] == a[5] == 42; they all refer to the same underlying array element
3311 <h4>Full slice expressions</h4>
3314 For an array, pointer to array, or slice <code>a</code> (but not a string), the primary expression
3322 constructs a slice of the same type, and with the same length and elements as the simple slice
3323 expression <code>a[low : high]</code>. Additionally, it controls the resulting slice's capacity
3324 by setting it to <code>max - low</code>. Only the first index may be omitted; it defaults to 0.
3325 After slicing the array <code>a</code>
3329 a := [5]int{1, 2, 3, 4, 5}
3334 the slice <code>t</code> has type <code>[]int</code>, length 2, capacity 4, and elements
3343 As for simple slice expressions, if <code>a</code> is a pointer to an array,
3344 <code>a[low : high : max]</code> is shorthand for <code>(*a)[low : high : max]</code>.
3345 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>.
3349 The indices are <i>in range</i> if <code>0 <= low <= high <= max <= cap(a)</code>,
3350 otherwise they are <i>out of range</i>.
3351 A <a href="#Constants">constant</a> index must be non-negative and
3352 <a href="#Representability">representable</a> by a value of type
3353 <code>int</code>; for arrays, constant indices must also be in range.
3354 If multiple indices are constant, the constants that are present must be in range relative to each
3356 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3359 <h3 id="Type_assertions">Type assertions</h3>
3362 For an expression <code>x</code> of <a href="#Interface_types">interface type</a>
3363 and a type <code>T</code>, the primary expression
3371 asserts that <code>x</code> is not <code>nil</code>
3372 and that the value stored in <code>x</code> is of type <code>T</code>.
3373 The notation <code>x.(T)</code> is called a <i>type assertion</i>.
3376 More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
3377 that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a>
3378 to the type <code>T</code>.
3379 In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>;
3380 otherwise the type assertion is invalid since it is not possible for <code>x</code>
3381 to store a value of type <code>T</code>.
3382 If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
3383 of <code>x</code> implements the interface <code>T</code>.
3386 If the type assertion holds, the value of the expression is the value
3387 stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false,
3388 a <a href="#Run_time_panics">run-time panic</a> occurs.
3389 In other words, even though the dynamic type of <code>x</code>
3390 is known only at run time, the type of <code>x.(T)</code> is
3391 known to be <code>T</code> in a correct program.
3395 var x interface{} = 7 // x has dynamic type int and value 7
3396 i := x.(int) // i has type int and value 7
3398 type I interface { m() }
3401 s := y.(string) // illegal: string does not implement I (missing method m)
3402 r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader
3408 A type assertion used in an <a href="#Assignments">assignment</a> or initialization of the special form
3415 var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool
3419 yields an additional untyped boolean value. The value of <code>ok</code> is <code>true</code>
3420 if the assertion holds. Otherwise it is <code>false</code> and the value of <code>v</code> is
3421 the <a href="#The_zero_value">zero value</a> for type <code>T</code>.
3422 No <a href="#Run_time_panics">run-time panic</a> occurs in this case.
3426 <h3 id="Calls">Calls</h3>
3429 Given an expression <code>f</code> of function type
3438 calls <code>f</code> with arguments <code>a1, a2, … an</code>.
3439 Except for one special case, arguments must be single-valued expressions
3440 <a href="#Assignability">assignable</a> to the parameter types of
3441 <code>F</code> and are evaluated before the function is called.
3442 The type of the expression is the result type
3444 A method invocation is similar but the method itself
3445 is specified as a selector upon a value of the receiver type for
3450 math.Atan2(x, y) // function call
3452 pt.Scale(3.5) // method call with receiver pt
3456 In a function call, the function value and arguments are evaluated in
3457 <a href="#Order_of_evaluation">the usual order</a>.
3458 After they are evaluated, the parameters of the call are passed by value to the function
3459 and the called function begins execution.
3460 The return parameters of the function are passed by value
3461 back to the caller when the function returns.
3465 Calling a <code>nil</code> function value
3466 causes a <a href="#Run_time_panics">run-time panic</a>.
3470 As a special case, if the return values of a function or method
3471 <code>g</code> are equal in number and individually
3472 assignable to the parameters of another function or method
3473 <code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code>
3474 will invoke <code>f</code> after binding the return values of
3475 <code>g</code> to the parameters of <code>f</code> in order. The call
3476 of <code>f</code> must contain no parameters other than the call of <code>g</code>,
3477 and <code>g</code> must have at least one return value.
3478 If <code>f</code> has a final <code>...</code> parameter, it is
3479 assigned the return values of <code>g</code> that remain after
3480 assignment of regular parameters.
3484 func Split(s string, pos int) (string, string) {
3485 return s[0:pos], s[pos:]
3488 func Join(s, t string) string {
3492 if Join(Split(value, len(value)/2)) != value {
3493 log.Panic("test fails")
3498 A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a>
3499 of (the type of) <code>x</code> contains <code>m</code> and the
3500 argument list can be assigned to the parameter list of <code>m</code>.
3501 If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&x</code>'s method
3502 set contains <code>m</code>, <code>x.m()</code> is shorthand
3503 for <code>(&x).m()</code>:
3512 There is no distinct method type and there are no method literals.
3515 <h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3>
3518 If <code>f</code> is <a href="#Function_types">variadic</a> with a final
3519 parameter <code>p</code> of type <code>...T</code>, then within <code>f</code>
3520 the type of <code>p</code> is equivalent to type <code>[]T</code>.
3521 If <code>f</code> is invoked with no actual arguments for <code>p</code>,
3522 the value passed to <code>p</code> is <code>nil</code>.
3523 Otherwise, the value passed is a new slice
3524 of type <code>[]T</code> with a new underlying array whose successive elements
3525 are the actual arguments, which all must be <a href="#Assignability">assignable</a>
3526 to <code>T</code>. The length and capacity of the slice is therefore
3527 the number of arguments bound to <code>p</code> and may differ for each
3532 Given the function and calls
3535 func Greeting(prefix string, who ...string)
3537 Greeting("hello:", "Joe", "Anna", "Eileen")
3541 within <code>Greeting</code>, <code>who</code> will have the value
3542 <code>nil</code> in the first call, and
3543 <code>[]string{"Joe", "Anna", "Eileen"}</code> in the second.
3547 If the final argument is assignable to a slice type <code>[]T</code> and
3548 is followed by <code>...</code>, it is passed unchanged as the value
3549 for a <code>...T</code> parameter. In this case no new slice is created.
3553 Given the slice <code>s</code> and call
3557 s := []string{"James", "Jasmine"}
3558 Greeting("goodbye:", s...)
3562 within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code>
3563 with the same underlying array.
3567 <h3 id="Operators">Operators</h3>
3570 Operators combine operands into expressions.
3574 Expression = UnaryExpr | Expression binary_op Expression .
3575 UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
3577 binary_op = "||" | "&&" | rel_op | add_op | mul_op .
3578 rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" .
3579 add_op = "+" | "-" | "|" | "^" .
3580 mul_op = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" .
3582 unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-" .
3586 Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>.
3587 For other binary operators, the operand types must be <a href="#Type_identity">identical</a>
3588 unless the operation involves shifts or untyped <a href="#Constants">constants</a>.
3589 For operations involving constants only, see the section on
3590 <a href="#Constant_expressions">constant expressions</a>.
3594 Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a>
3595 and the other operand is not, the constant is implicitly <a href="#Conversions">converted</a>
3596 to the type of the other operand.
3600 The right operand in a shift expression must have integer type
3601 or be an untyped constant <a href="#Representability">representable</a> by a
3602 value of type <code>uint</code>.
3603 If the left operand of a non-constant shift expression is an untyped constant,
3604 it is first implicitly converted to the type it would assume if the shift expression were
3605 replaced by its left operand alone.
3612 // The results of the following examples are given for 64-bit ints.
3613 var i = 1<<s // 1 has type int
3614 var j int32 = 1<<s // 1 has type int32; j == 0
3615 var k = uint64(1<<s) // 1 has type uint64; k == 1<<33
3616 var m int = 1.0<<s // 1.0 has type int; m == 1<<33
3617 var n = 1.0<<s == j // 1.0 has type int32; n == true
3618 var o = 1<<s == 2<<s // 1 and 2 have type int; o == false
3619 var p = 1<<s == 1<<33 // 1 has type int; p == true
3620 var u = 1.0<<s // illegal: 1.0 has type float64, cannot shift
3621 var u1 = 1.0<<s != 0 // illegal: 1.0 has type float64, cannot shift
3622 var u2 = 1<<s != 1.0 // illegal: 1 has type float64, cannot shift
3623 var v float32 = 1<<s // illegal: 1 has type float32, cannot shift
3624 var w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression; w == 1<<33
3625 var x = a[1.0<<s] // panics: 1.0 has type int, but 1<<33 overflows array bounds
3626 var b = make([]byte, 1.0<<s) // 1.0 has type int; len(b) == 1<<33
3628 // The results of the following examples are given for 32-bit ints,
3629 // which means the shifts will overflow.
3630 var mm int = 1.0<<s // 1.0 has type int; mm == 0
3631 var oo = 1<<s == 2<<s // 1 and 2 have type int; oo == true
3632 var pp = 1<<s == 1<<33 // illegal: 1 has type int, but 1<<33 overflows int
3633 var xx = a[1.0<<s] // 1.0 has type int; xx == a[0]
3634 var bb = make([]byte, 1.0<<s) // 1.0 has type int; len(bb) == 0
3637 <h4 id="Operator_precedence">Operator precedence</h4>
3639 Unary operators have the highest precedence.
3640 As the <code>++</code> and <code>--</code> operators form
3641 statements, not expressions, they fall
3642 outside the operator hierarchy.
3643 As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>.
3645 There are five precedence levels for binary operators.
3646 Multiplication operators bind strongest, followed by addition
3647 operators, comparison operators, <code>&&</code> (logical AND),
3648 and finally <code>||</code> (logical OR):
3651 <pre class="grammar">
3653 5 * / % << >> & &^
3655 3 == != < <= > >=
3661 Binary operators of the same precedence associate from left to right.
3662 For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>.
3671 x == y+1 && <-chanInt > 0
3675 <h3 id="Arithmetic_operators">Arithmetic operators</h3>
3677 Arithmetic operators apply to numeric values and yield a result of the same
3678 type as the first operand. The four standard arithmetic operators (<code>+</code>,
3679 <code>-</code>, <code>*</code>, <code>/</code>) apply to integer,
3680 floating-point, and complex types; <code>+</code> also applies to strings.
3681 The bitwise logical and shift operators apply to integers only.
3684 <pre class="grammar">
3685 + sum integers, floats, complex values, strings
3686 - difference integers, floats, complex values
3687 * product integers, floats, complex values
3688 / quotient integers, floats, complex values
3689 % remainder integers
3691 & bitwise AND integers
3692 | bitwise OR integers
3693 ^ bitwise XOR integers
3694 &^ bit clear (AND NOT) integers
3696 << left shift integer << integer >= 0
3697 >> right shift integer >> integer >= 0
3701 <h4 id="Integer_operators">Integer operators</h4>
3704 For two integer values <code>x</code> and <code>y</code>, the integer quotient
3705 <code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following
3710 x = q*y + r and |r| < |y|
3714 with <code>x / y</code> truncated towards zero
3715 (<a href="https://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>).
3727 The one exception to this rule is that if the dividend <code>x</code> is
3728 the most negative value for the int type of <code>x</code>, the quotient
3729 <code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>)
3730 due to two's-complement <a href="#Integer_overflow">integer overflow</a>:
3738 int64 -9223372036854775808
3742 If the divisor is a <a href="#Constants">constant</a>, it must not be zero.
3743 If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3744 If the dividend is non-negative and the divisor is a constant power of 2,
3745 the division may be replaced by a right shift, and computing the remainder may
3746 be replaced by a bitwise AND operation:
3750 x x / 4 x % 4 x >> 2 x & 3
3756 The shift operators shift the left operand by the shift count specified by the
3757 right operand, which must be non-negative. If the shift count is negative at run time,
3758 a <a href="#Run_time_panics">run-time panic</a> occurs.
3759 The shift operators implement arithmetic shifts if the left operand is a signed
3760 integer and logical shifts if it is an unsigned integer.
3761 There is no upper limit on the shift count. Shifts behave
3762 as if the left operand is shifted <code>n</code> times by 1 for a shift
3763 count of <code>n</code>.
3764 As a result, <code>x << 1</code> is the same as <code>x*2</code>
3765 and <code>x >> 1</code> is the same as
3766 <code>x/2</code> but truncated towards negative infinity.
3770 For integer operands, the unary operators
3771 <code>+</code>, <code>-</code>, and <code>^</code> are defined as
3775 <pre class="grammar">
3777 -x negation is 0 - x
3778 ^x bitwise complement is m ^ x with m = "all bits set to 1" for unsigned x
3779 and m = -1 for signed x
3783 <h4 id="Integer_overflow">Integer overflow</h4>
3786 For unsigned integer values, the operations <code>+</code>,
3787 <code>-</code>, <code>*</code>, and <code><<</code> are
3788 computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of
3789 the <a href="#Numeric_types">unsigned integer</a>'s type.
3790 Loosely speaking, these unsigned integer operations
3791 discard high bits upon overflow, and programs may rely on "wrap around".
3794 For signed integers, the operations <code>+</code>,
3795 <code>-</code>, <code>*</code>, <code>/</code>, and <code><<</code> may legally
3796 overflow and the resulting value exists and is deterministically defined
3797 by the signed integer representation, the operation, and its operands.
3798 Overflow does not cause a <a href="#Run_time_panics">run-time panic</a>.
3799 A compiler may not optimize code under the assumption that overflow does
3800 not occur. For instance, it may not assume that <code>x < x + 1</code> is always true.
3804 <h4 id="Floating_point_operators">Floating-point operators</h4>
3807 For floating-point and complex numbers,
3808 <code>+x</code> is the same as <code>x</code>,
3809 while <code>-x</code> is the negation of <code>x</code>.
3810 The result of a floating-point or complex division by zero is not specified beyond the
3811 IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a>
3812 occurs is implementation-specific.
3816 An implementation may combine multiple floating-point operations into a single
3817 fused operation, possibly across statements, and produce a result that differs
3818 from the value obtained by executing and rounding the instructions individually.
3819 An explicit floating-point type <a href="#Conversions">conversion</a> rounds to
3820 the precision of the target type, preventing fusion that would discard that rounding.
3824 For instance, some architectures provide a "fused multiply and add" (FMA) instruction
3825 that computes <code>x*y + z</code> without rounding the intermediate result <code>x*y</code>.
3826 These examples show when a Go implementation can use that instruction:
3830 // FMA allowed for computing r, because x*y is not explicitly rounded:
3834 *p = x*y; r = *p + z
3835 r = x*y + float64(z)
3837 // FMA disallowed for computing r, because it would omit rounding of x*y:
3838 r = float64(x*y) + z
3839 r = z; r += float64(x*y)
3840 t = float64(x*y); r = t + z
3843 <h4 id="String_concatenation">String concatenation</h4>
3846 Strings can be concatenated using the <code>+</code> operator
3847 or the <code>+=</code> assignment operator:
3851 s := "hi" + string(c)
3852 s += " and good bye"
3856 String addition creates a new string by concatenating the operands.
3860 <h3 id="Comparison_operators">Comparison operators</h3>
3863 Comparison operators compare two operands and yield an untyped boolean value.
3866 <pre class="grammar">
3872 >= greater or equal
3876 In any comparison, the first operand
3877 must be <a href="#Assignability">assignable</a>
3878 to the type of the second operand, or vice versa.
3881 The equality operators <code>==</code> and <code>!=</code> apply
3882 to operands that are <i>comparable</i>.
3883 The ordering operators <code><</code>, <code><=</code>, <code>></code>, and <code>>=</code>
3884 apply to operands that are <i>ordered</i>.
3885 These terms and the result of the comparisons are defined as follows:
3890 Boolean values are comparable.
3891 Two boolean values are equal if they are either both
3892 <code>true</code> or both <code>false</code>.
3896 Integer values are comparable and ordered, in the usual way.
3900 Floating-point values are comparable and ordered,
3901 as defined by the IEEE-754 standard.
3905 Complex values are comparable.
3906 Two complex values <code>u</code> and <code>v</code> are
3907 equal if both <code>real(u) == real(v)</code> and
3908 <code>imag(u) == imag(v)</code>.
3912 String values are comparable and ordered, lexically byte-wise.
3916 Pointer values are comparable.
3917 Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>.
3918 Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal.
3922 Channel values are comparable.
3923 Two channel values are equal if they were created by the same call to
3924 <a href="#Making_slices_maps_and_channels"><code>make</code></a>
3925 or if both have value <code>nil</code>.
3929 Interface values are comparable.
3930 Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types
3931 and equal dynamic values or if both have value <code>nil</code>.
3935 A value <code>x</code> of non-interface type <code>X</code> and
3936 a value <code>t</code> of interface type <code>T</code> are comparable when values
3937 of type <code>X</code> are comparable and
3938 <code>X</code> implements <code>T</code>.
3939 They are equal if <code>t</code>'s dynamic type is identical to <code>X</code>
3940 and <code>t</code>'s dynamic value is equal to <code>x</code>.
3944 Struct values are comparable if all their fields are comparable.
3945 Two struct values are equal if their corresponding
3946 non-<a href="#Blank_identifier">blank</a> fields are equal.
3950 Array values are comparable if values of the array element type are comparable.
3951 Two array values are equal if their corresponding elements are equal.
3956 A comparison of two interface values with identical dynamic types
3957 causes a <a href="#Run_time_panics">run-time panic</a> if values
3958 of that type are not comparable. This behavior applies not only to direct interface
3959 value comparisons but also when comparing arrays of interface values
3960 or structs with interface-valued fields.
3964 Slice, map, and function values are not comparable.
3965 However, as a special case, a slice, map, or function value may
3966 be compared to the predeclared identifier <code>nil</code>.
3967 Comparison of pointer, channel, and interface values to <code>nil</code>
3968 is also allowed and follows from the general rules above.
3972 const c = 3 < 4 // c is the untyped boolean constant true
3977 // The result of a comparison is an untyped boolean.
3978 // The usual assignment rules apply.
3979 b3 = x == y // b3 has type bool
3980 b4 bool = x == y // b4 has type bool
3981 b5 MyBool = x == y // b5 has type MyBool
3985 <h3 id="Logical_operators">Logical operators</h3>
3988 Logical operators apply to <a href="#Boolean_types">boolean</a> values
3989 and yield a result of the same type as the operands.
3990 The right operand is evaluated conditionally.
3993 <pre class="grammar">
3994 && conditional AND p && q is "if p then q else false"
3995 || conditional OR p || q is "if p then true else q"
4000 <h3 id="Address_operators">Address operators</h3>
4003 For an operand <code>x</code> of type <code>T</code>, the address operation
4004 <code>&x</code> generates a pointer of type <code>*T</code> to <code>x</code>.
4005 The operand must be <i>addressable</i>,
4006 that is, either a variable, pointer indirection, or slice indexing
4007 operation; or a field selector of an addressable struct operand;
4008 or an array indexing operation of an addressable array.
4009 As an exception to the addressability requirement, <code>x</code> may also be a
4010 (possibly parenthesized)
4011 <a href="#Composite_literals">composite literal</a>.
4012 If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>,
4013 then the evaluation of <code>&x</code> does too.
4017 For an operand <code>x</code> of pointer type <code>*T</code>, the pointer
4018 indirection <code>*x</code> denotes the <a href="#Variables">variable</a> of type <code>T</code> pointed
4019 to by <code>x</code>.
4020 If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code>
4021 will cause a <a href="#Run_time_panics">run-time panic</a>.
4032 *x // causes a run-time panic
4033 &*x // causes a run-time panic
4037 <h3 id="Receive_operator">Receive operator</h3>
4040 For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>,
4041 the value of the receive operation <code><-ch</code> is the value received
4042 from the channel <code>ch</code>. The channel direction must permit receive operations,
4043 and the type of the receive operation is the element type of the channel.
4044 The expression blocks until a value is available.
4045 Receiving from a <code>nil</code> channel blocks forever.
4046 A receive operation on a <a href="#Close">closed</a> channel can always proceed
4047 immediately, yielding the element type's <a href="#The_zero_value">zero value</a>
4048 after any previously sent values have been received.
4055 <-strobe // wait until clock pulse and discard received value
4059 A receive expression used in an <a href="#Assignments">assignment</a> or initialization of the special form
4066 var x, ok T = <-ch
4070 yields an additional untyped boolean result reporting whether the
4071 communication succeeded. The value of <code>ok</code> is <code>true</code>
4072 if the value received was delivered by a successful send operation to the
4073 channel, or <code>false</code> if it is a zero value generated because the
4074 channel is closed and empty.
4078 <h3 id="Conversions">Conversions</h3>
4081 A conversion changes the <a href="#Types">type</a> of an expression
4082 to the type specified by the conversion.
4083 A conversion may appear literally in the source, or it may be <i>implied</i>
4084 by the context in which an expression appears.
4088 An <i>explicit</i> conversion is an expression of the form <code>T(x)</code>
4089 where <code>T</code> is a type and <code>x</code> is an expression
4090 that can be converted to type <code>T</code>.
4094 Conversion = Type "(" Expression [ "," ] ")" .
4098 If the type starts with the operator <code>*</code> or <code><-</code>,
4099 or if the type starts with the keyword <code>func</code>
4100 and has no result list, it must be parenthesized when
4101 necessary to avoid ambiguity:
4105 *Point(p) // same as *(Point(p))
4106 (*Point)(p) // p is converted to *Point
4107 <-chan int(c) // same as <-(chan int(c))
4108 (<-chan int)(c) // c is converted to <-chan int
4109 func()(x) // function signature func() x
4110 (func())(x) // x is converted to func()
4111 (func() int)(x) // x is converted to func() int
4112 func() int(x) // x is converted to func() int (unambiguous)
4116 A <a href="#Constants">constant</a> value <code>x</code> can be converted to
4117 type <code>T</code> if <code>x</code> is <a href="#Representability">representable</a>
4118 by a value of <code>T</code>.
4119 As a special case, an integer constant <code>x</code> can be explicitly converted to a
4120 <a href="#String_types">string type</a> using the
4121 <a href="#Conversions_to_and_from_a_string_type">same rule</a>
4122 as for non-constant <code>x</code>.
4126 Converting a constant yields a typed constant as result.
4130 uint(iota) // iota value of type uint
4131 float32(2.718281828) // 2.718281828 of type float32
4132 complex128(1) // 1.0 + 0.0i of type complex128
4133 float32(0.49999999) // 0.5 of type float32
4134 float64(-1e-1000) // 0.0 of type float64
4135 string('x') // "x" of type string
4136 string(0x266c) // "♬" of type string
4137 MyString("foo" + "bar") // "foobar" of type MyString
4138 string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant
4139 (*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
4140 int(1.2) // illegal: 1.2 cannot be represented as an int
4141 string(65.0) // illegal: 65.0 is not an integer constant
4145 A non-constant value <code>x</code> can be converted to type <code>T</code>
4146 in any of these cases:
4151 <code>x</code> is <a href="#Assignability">assignable</a>
4155 ignoring struct tags (see below),
4156 <code>x</code>'s type and <code>T</code> have <a href="#Type_identity">identical</a>
4157 <a href="#Types">underlying types</a>.
4160 ignoring struct tags (see below),
4161 <code>x</code>'s type and <code>T</code> are pointer types
4162 that are not <a href="#Type_definitions">defined types</a>,
4163 and their pointer base types have identical underlying types.
4166 <code>x</code>'s type and <code>T</code> are both integer or floating
4170 <code>x</code>'s type and <code>T</code> are both complex types.
4173 <code>x</code> is an integer or a slice of bytes or runes
4174 and <code>T</code> is a string type.
4177 <code>x</code> is a string and <code>T</code> is a slice of bytes or runes.
4180 <code>x</code> is a slice, <code>T</code> is a pointer to an array,
4181 and the slice and array types have <a href="#Type_identity">identical</a> element types.
4186 <a href="#Struct_types">Struct tags</a> are ignored when comparing struct types
4187 for identity for the purpose of conversion:
4191 type Person struct {
4200 Name string `json:"name"`
4202 Street string `json:"street"`
4203 City string `json:"city"`
4207 var person = (*Person)(data) // ignoring tags, the underlying types are identical
4211 Specific rules apply to (non-constant) conversions between numeric types or
4212 to and from a string type.
4213 These conversions may change the representation of <code>x</code>
4214 and incur a run-time cost.
4215 All other conversions only change the type but not the representation
4220 There is no linguistic mechanism to convert between pointers and integers.
4221 The package <a href="#Package_unsafe"><code>unsafe</code></a>
4222 implements this functionality under
4223 restricted circumstances.
4226 <h4>Conversions between numeric types</h4>
4229 For the conversion of non-constant numeric values, the following rules apply:
4234 When converting between integer types, if the value is a signed integer, it is
4235 sign extended to implicit infinite precision; otherwise it is zero extended.
4236 It is then truncated to fit in the result type's size.
4237 For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>.
4238 The conversion always yields a valid value; there is no indication of overflow.
4241 When converting a floating-point number to an integer, the fraction is discarded
4242 (truncation towards zero).
4245 When converting an integer or floating-point number to a floating-point type,
4246 or a complex number to another complex type, the result value is rounded
4247 to the precision specified by the destination type.
4248 For instance, the value of a variable <code>x</code> of type <code>float32</code>
4249 may be stored using additional precision beyond that of an IEEE-754 32-bit number,
4250 but float32(x) represents the result of rounding <code>x</code>'s value to
4251 32-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits
4252 of precision, but <code>float32(x + 0.1)</code> does not.
4257 In all non-constant conversions involving floating-point or complex values,
4258 if the result type cannot represent the value the conversion
4259 succeeds but the result value is implementation-dependent.
4262 <h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4>
4266 Converting a signed or unsigned integer value to a string type yields a
4267 string containing the UTF-8 representation of the integer. Values outside
4268 the range of valid Unicode code points are converted to <code>"\uFFFD"</code>.
4272 string(-1) // "\ufffd" == "\xef\xbf\xbd"
4273 string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8"
4274 type MyString string
4275 MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5"
4280 Converting a slice of bytes to a string type yields
4281 a string whose successive bytes are the elements of the slice.
4284 string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
4285 string([]byte{}) // ""
4286 string([]byte(nil)) // ""
4289 string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
4294 Converting a slice of runes to a string type yields
4295 a string that is the concatenation of the individual rune values
4296 converted to strings.
4299 string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
4300 string([]rune{}) // ""
4301 string([]rune(nil)) // ""
4304 string(MyRunes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
4309 Converting a value of a string type to a slice of bytes type
4310 yields a slice whose successive elements are the bytes of the string.
4313 []byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
4314 []byte("") // []byte{}
4316 MyBytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
4321 Converting a value of a string type to a slice of runes type
4322 yields a slice containing the individual Unicode code points of the string.
4325 []rune(MyString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4}
4326 []rune("") // []rune{}
4328 MyRunes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4}
4333 <h4 id="Conversions_from_slice_to_array_pointer">Conversions from slice to array pointer</h4>
4336 Converting a slice to an array pointer yields a pointer to the underlying array of the slice.
4337 If the <a href="#Length_and_capacity">length</a> of the slice is less than the length of the array,
4338 a <a href="#Run_time_panics">run-time panic</a> occurs.
4342 s := make([]byte, 2, 4)
4343 s0 := (*[0]byte)(s) // s0 != nil
4344 s1 := (*[1]byte)(s[1:]) // &s1[0] == &s[1]
4345 s2 := (*[2]byte)(s) // &s2[0] == &s[0]
4346 s4 := (*[4]byte)(s) // panics: len([4]byte) > len(s)
4349 t0 := (*[0]string)(t) // t0 == nil
4350 t1 := (*[1]string)(t) // panics: len([1]string) > len(t)
4352 u := make([]byte, 0)
4353 u0 := (*[0]byte)(u) // u0 != nil
4356 <h3 id="Constant_expressions">Constant expressions</h3>
4359 Constant expressions may contain only <a href="#Constants">constant</a>
4360 operands and are evaluated at compile time.
4364 Untyped boolean, numeric, and string constants may be used as operands
4365 wherever it is legal to use an operand of boolean, numeric, or string type,
4370 A constant <a href="#Comparison_operators">comparison</a> always yields
4371 an untyped boolean constant. If the left operand of a constant
4372 <a href="#Operators">shift expression</a> is an untyped constant, the
4373 result is an integer constant; otherwise it is a constant of the same
4374 type as the left operand, which must be of
4375 <a href="#Numeric_types">integer type</a>.
4379 Any other operation on untyped constants results in an untyped constant of the
4380 same kind; that is, a boolean, integer, floating-point, complex, or string
4382 If the untyped operands of a binary operation (other than a shift) are of
4383 different kinds, the result is of the operand's kind that appears later in this
4384 list: integer, rune, floating-point, complex.
4385 For example, an untyped integer constant divided by an
4386 untyped complex constant yields an untyped complex constant.
4390 const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant)
4391 const b = 15 / 4 // b == 3 (untyped integer constant)
4392 const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant)
4393 const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division)
4394 const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division)
4395 const d = 1 << 3.0 // d == 8 (untyped integer constant)
4396 const e = 1.0 << 3 // e == 8 (untyped integer constant)
4397 const f = int32(1) << 33 // illegal (constant 8589934592 overflows int32)
4398 const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant)
4399 const h = "foo" > "bar" // h == true (untyped boolean constant)
4400 const j = true // j == true (untyped boolean constant)
4401 const k = 'w' + 1 // k == 'x' (untyped rune constant)
4402 const l = "hi" // l == "hi" (untyped string constant)
4403 const m = string(k) // m == "x" (type string)
4404 const Σ = 1 - 0.707i // (untyped complex constant)
4405 const Δ = Σ + 2.0e-4 // (untyped complex constant)
4406 const Φ = iota*1i - 1/1i // (untyped complex constant)
4410 Applying the built-in function <code>complex</code> to untyped
4411 integer, rune, or floating-point constants yields
4412 an untyped complex constant.
4416 const ic = complex(0, c) // ic == 3.75i (untyped complex constant)
4417 const iΘ = complex(0, Θ) // iΘ == 1i (type complex128)
4421 Constant expressions are always evaluated exactly; intermediate values and the
4422 constants themselves may require precision significantly larger than supported
4423 by any predeclared type in the language. The following are legal declarations:
4427 const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (untyped integer constant)
4428 const Four int8 = Huge >> 98 // Four == 4 (type int8)
4432 The divisor of a constant division or remainder operation must not be zero:
4436 3.14 / 0.0 // illegal: division by zero
4440 The values of <i>typed</i> constants must always be accurately
4441 <a href="#Representability">representable</a> by values
4442 of the constant type. The following constant expressions are illegal:
4446 uint(-1) // -1 cannot be represented as a uint
4447 int(3.14) // 3.14 cannot be represented as an int
4448 int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64
4449 Four * 300 // operand 300 cannot be represented as an int8 (type of Four)
4450 Four * 100 // product 400 cannot be represented as an int8 (type of Four)
4454 The mask used by the unary bitwise complement operator <code>^</code> matches
4455 the rule for non-constants: the mask is all 1s for unsigned constants
4456 and -1 for signed and untyped constants.
4460 ^1 // untyped integer constant, equal to -2
4461 uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8
4462 ^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)
4463 int8(^1) // same as int8(-2)
4464 ^int8(1) // same as -1 ^ int8(1) = -2
4468 Implementation restriction: A compiler may use rounding while
4469 computing untyped floating-point or complex constant expressions; see
4470 the implementation restriction in the section
4471 on <a href="#Constants">constants</a>. This rounding may cause a
4472 floating-point constant expression to be invalid in an integer
4473 context, even if it would be integral when calculated using infinite
4474 precision, and vice versa.
4478 <h3 id="Order_of_evaluation">Order of evaluation</h3>
4481 At package level, <a href="#Package_initialization">initialization dependencies</a>
4482 determine the evaluation order of individual initialization expressions in
4483 <a href="#Variable_declarations">variable declarations</a>.
4484 Otherwise, when evaluating the <a href="#Operands">operands</a> of an
4485 expression, assignment, or
4486 <a href="#Return_statements">return statement</a>,
4487 all function calls, method calls, and
4488 communication operations are evaluated in lexical left-to-right
4493 For example, in the (function-local) assignment
4496 y[f()], ok = g(h(), i()+x[j()], <-c), k()
4499 the function calls and communication happen in the order
4500 <code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>,
4501 <code><-c</code>, <code>g()</code>, and <code>k()</code>.
4502 However, the order of those events compared to the evaluation
4503 and indexing of <code>x</code> and the evaluation
4504 of <code>y</code> is not specified.
4509 f := func() int { a++; return a }
4510 x := []int{a, f()} // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified
4511 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
4512 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
4516 At package level, initialization dependencies override the left-to-right rule
4517 for individual initialization expressions, but not for operands within each
4522 var a, b, c = f() + v(), g(), sqr(u()) + v()
4524 func f() int { return c }
4525 func g() int { return a }
4526 func sqr(x int) int { return x*x }
4528 // functions u and v are independent of all other variables and functions
4532 The function calls happen in the order
4533 <code>u()</code>, <code>sqr()</code>, <code>v()</code>,
4534 <code>f()</code>, <code>v()</code>, and <code>g()</code>.
4538 Floating-point operations within a single expression are evaluated according to
4539 the associativity of the operators. Explicit parentheses affect the evaluation
4540 by overriding the default associativity.
4541 In the expression <code>x + (y + z)</code> the addition <code>y + z</code>
4542 is performed before adding <code>x</code>.
4545 <h2 id="Statements">Statements</h2>
4548 Statements control execution.
4553 Declaration | LabeledStmt | SimpleStmt |
4554 GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
4555 FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
4558 SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
4561 <h3 id="Terminating_statements">Terminating statements</h3>
4564 A <i>terminating statement</i> interrupts the regular flow of control in
4565 a <a href="#Blocks">block</a>. The following statements are terminating:
4570 A <a href="#Return_statements">"return"</a> or
4571 <a href="#Goto_statements">"goto"</a> statement.
4572 <!-- ul below only for regular layout -->
4577 A call to the built-in function
4578 <a href="#Handling_panics"><code>panic</code></a>.
4579 <!-- ul below only for regular layout -->
4584 A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement.
4585 <!-- ul below only for regular layout -->
4590 An <a href="#If_statements">"if" statement</a> in which:
4592 <li>the "else" branch is present, and</li>
4593 <li>both branches are terminating statements.</li>
4598 A <a href="#For_statements">"for" statement</a> in which:
4600 <li>there are no "break" statements referring to the "for" statement, and</li>
4601 <li>the loop condition is absent, and</li>
4602 <li>the "for" statement does not use a range clause.</li>
4607 A <a href="#Switch_statements">"switch" statement</a> in which:
4609 <li>there are no "break" statements referring to the "switch" statement,</li>
4610 <li>there is a default case, and</li>
4611 <li>the statement lists in each case, including the default, end in a terminating
4612 statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough"
4618 A <a href="#Select_statements">"select" statement</a> in which:
4620 <li>there are no "break" statements referring to the "select" statement, and</li>
4621 <li>the statement lists in each case, including the default if present,
4622 end in a terminating statement.</li>
4627 A <a href="#Labeled_statements">labeled statement</a> labeling
4628 a terminating statement.
4633 All other statements are not terminating.
4637 A <a href="#Blocks">statement list</a> ends in a terminating statement if the list
4638 is not empty and its final non-empty statement is terminating.
4642 <h3 id="Empty_statements">Empty statements</h3>
4645 The empty statement does nothing.
4653 <h3 id="Labeled_statements">Labeled statements</h3>
4656 A labeled statement may be the target of a <code>goto</code>,
4657 <code>break</code> or <code>continue</code> statement.
4661 LabeledStmt = Label ":" Statement .
4662 Label = identifier .
4666 Error: log.Panic("error encountered")
4670 <h3 id="Expression_statements">Expression statements</h3>
4673 With the exception of specific built-in functions,
4674 function and method <a href="#Calls">calls</a> and
4675 <a href="#Receive_operator">receive operations</a>
4676 can appear in statement context. Such statements may be parenthesized.
4680 ExpressionStmt = Expression .
4684 The following built-in functions are not permitted in statement context:
4688 append cap complex imag len make new real
4689 unsafe.Add unsafe.Alignof unsafe.Offsetof unsafe.Sizeof unsafe.Slice
4697 len("foo") // illegal if len is the built-in function
4701 <h3 id="Send_statements">Send statements</h3>
4704 A send statement sends a value on a channel.
4705 The channel expression must be of <a href="#Channel_types">channel type</a>,
4706 the channel direction must permit send operations,
4707 and the type of the value to be sent must be <a href="#Assignability">assignable</a>
4708 to the channel's element type.
4712 SendStmt = Channel "<-" Expression .
4713 Channel = Expression .
4717 Both the channel and the value expression are evaluated before communication
4718 begins. Communication blocks until the send can proceed.
4719 A send on an unbuffered channel can proceed if a receiver is ready.
4720 A send on a buffered channel can proceed if there is room in the buffer.
4721 A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>.
4722 A send on a <code>nil</code> channel blocks forever.
4726 ch <- 3 // send value 3 to channel ch
4730 <h3 id="IncDec_statements">IncDec statements</h3>
4733 The "++" and "--" statements increment or decrement their operands
4734 by the untyped <a href="#Constants">constant</a> <code>1</code>.
4735 As with an assignment, the operand must be <a href="#Address_operators">addressable</a>
4736 or a map index expression.
4740 IncDecStmt = Expression ( "++" | "--" ) .
4744 The following <a href="#Assignments">assignment statements</a> are semantically
4748 <pre class="grammar">
4749 IncDec statement Assignment
4755 <h3 id="Assignments">Assignments</h3>
4758 Assignment = ExpressionList assign_op ExpressionList .
4760 assign_op = [ add_op | mul_op ] "=" .
4764 Each left-hand side operand must be <a href="#Address_operators">addressable</a>,
4765 a map index expression, or (for <code>=</code> assignments only) the
4766 <a href="#Blank_identifier">blank identifier</a>.
4767 Operands may be parenthesized.
4774 (k) = <-ch // same as: k = <-ch
4778 An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code>
4779 <code>y</code> where <i>op</i> is a binary <a href="#Arithmetic_operators">arithmetic operator</a>
4780 is equivalent to <code>x</code> <code>=</code> <code>x</code> <i>op</i>
4781 <code>(y)</code> but evaluates <code>x</code>
4782 only once. The <i>op</i><code>=</code> construct is a single token.
4783 In assignment operations, both the left- and right-hand expression lists
4784 must contain exactly one single-valued expression, and the left-hand
4785 expression must not be the blank identifier.
4790 i &^= 1<<n
4794 A tuple assignment assigns the individual elements of a multi-valued
4795 operation to a list of variables. There are two forms. In the
4796 first, the right hand operand is a single multi-valued expression
4797 such as a function call, a <a href="#Channel_types">channel</a> or
4798 <a href="#Map_types">map</a> operation, or a <a href="#Type_assertions">type assertion</a>.
4799 The number of operands on the left
4800 hand side must match the number of values. For instance, if
4801 <code>f</code> is a function returning two values,
4809 assigns the first value to <code>x</code> and the second to <code>y</code>.
4810 In the second form, the number of operands on the left must equal the number
4811 of expressions on the right, each of which must be single-valued, and the
4812 <i>n</i>th expression on the right is assigned to the <i>n</i>th
4813 operand on the left:
4817 one, two, three = '一', '二', '三'
4821 The <a href="#Blank_identifier">blank identifier</a> provides a way to
4822 ignore right-hand side values in an assignment:
4826 _ = x // evaluate x but ignore it
4827 x, _ = f() // evaluate f() but ignore second result value
4831 The assignment proceeds in two phases.
4832 First, the operands of <a href="#Index_expressions">index expressions</a>
4833 and <a href="#Address_operators">pointer indirections</a>
4834 (including implicit pointer indirections in <a href="#Selectors">selectors</a>)
4835 on the left and the expressions on the right are all
4836 <a href="#Order_of_evaluation">evaluated in the usual order</a>.
4837 Second, the assignments are carried out in left-to-right order.
4841 a, b = b, a // exchange a and b
4845 i, x[i] = 1, 2 // set i = 1, x[0] = 2
4848 x[i], i = 2, 1 // set x[0] = 2, i = 1
4850 x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end)
4852 x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5.
4854 type Point struct { x, y int }
4856 x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7
4860 for i, x[i] = range x { // set i, x[2] = 0, x[0]
4863 // after this loop, i == 0 and x == []int{3, 5, 3}
4867 In assignments, each value must be <a href="#Assignability">assignable</a>
4868 to the type of the operand to which it is assigned, with the following special cases:
4873 Any typed value may be assigned to the blank identifier.
4877 If an untyped constant
4878 is assigned to a variable of interface type or the blank identifier,
4879 the constant is first implicitly <a href="#Conversions">converted</a> to its
4880 <a href="#Constants">default type</a>.
4884 If an untyped boolean value is assigned to a variable of interface type or
4885 the blank identifier, it is first implicitly converted to type <code>bool</code>.
4889 <h3 id="If_statements">If statements</h3>
4892 "If" statements specify the conditional execution of two branches
4893 according to the value of a boolean expression. If the expression
4894 evaluates to true, the "if" branch is executed, otherwise, if
4895 present, the "else" branch is executed.
4899 IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
4909 The expression may be preceded by a simple statement, which
4910 executes before the expression is evaluated.
4914 if x := f(); x < y {
4916 } else if x > z {
4924 <h3 id="Switch_statements">Switch statements</h3>
4927 "Switch" statements provide multi-way execution.
4928 An expression or type is compared to the "cases"
4929 inside the "switch" to determine which branch
4934 SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4938 There are two forms: expression switches and type switches.
4939 In an expression switch, the cases contain expressions that are compared
4940 against the value of the switch expression.
4941 In a type switch, the cases contain types that are compared against the
4942 type of a specially annotated switch expression.
4943 The switch expression is evaluated exactly once in a switch statement.
4946 <h4 id="Expression_switches">Expression switches</h4>
4949 In an expression switch,
4950 the switch expression is evaluated and
4951 the case expressions, which need not be constants,
4952 are evaluated left-to-right and top-to-bottom; the first one that equals the
4954 triggers execution of the statements of the associated case;
4955 the other cases are skipped.
4956 If no case matches and there is a "default" case,
4957 its statements are executed.
4958 There can be at most one default case and it may appear anywhere in the
4960 A missing switch expression is equivalent to the boolean value
4965 ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
4966 ExprCaseClause = ExprSwitchCase ":" StatementList .
4967 ExprSwitchCase = "case" ExpressionList | "default" .
4971 If the switch expression evaluates to an untyped constant, it is first implicitly
4972 <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>.
4973 The predeclared untyped value <code>nil</code> cannot be used as a switch expression.
4974 The switch expression type must be <a href="#Comparison_operators">comparable</a>.
4978 If a case expression is untyped, it is first implicitly <a href="#Conversions">converted</a>
4979 to the type of the switch expression.
4980 For each (possibly converted) case expression <code>x</code> and the value <code>t</code>
4981 of the switch expression, <code>x == t</code> must be a valid <a href="#Comparison_operators">comparison</a>.
4985 In other words, the switch expression is treated as if it were used to declare and
4986 initialize a temporary variable <code>t</code> without explicit type; it is that
4987 value of <code>t</code> against which each case expression <code>x</code> is tested
4992 In a case or default clause, the last non-empty statement
4993 may be a (possibly <a href="#Labeled_statements">labeled</a>)
4994 <a href="#Fallthrough_statements">"fallthrough" statement</a> to
4995 indicate that control should flow from the end of this clause to
4996 the first statement of the next clause.
4997 Otherwise control flows to the end of the "switch" statement.
4998 A "fallthrough" statement may appear as the last statement of all
4999 but the last clause of an expression switch.
5003 The switch expression may be preceded by a simple statement, which
5004 executes before the expression is evaluated.
5010 case 0, 1, 2, 3: s1()
5011 case 4, 5, 6, 7: s2()
5014 switch x := f(); { // missing switch expression means "true"
5015 case x < 0: return -x
5027 Implementation restriction: A compiler may disallow multiple case
5028 expressions evaluating to the same constant.
5029 For instance, the current compilers disallow duplicate integer,
5030 floating point, or string constants in case expressions.
5033 <h4 id="Type_switches">Type switches</h4>
5036 A type switch compares types rather than values. It is otherwise similar
5037 to an expression switch. It is marked by a special switch expression that
5038 has the form of a <a href="#Type_assertions">type assertion</a>
5039 using the keyword <code>type</code> rather than an actual type:
5049 Cases then match actual types <code>T</code> against the dynamic type of the
5050 expression <code>x</code>. As with type assertions, <code>x</code> must be of
5051 <a href="#Interface_types">interface type</a>, and each non-interface type
5052 <code>T</code> listed in a case must implement the type of <code>x</code>.
5053 The types listed in the cases of a type switch must all be
5054 <a href="#Type_identity">different</a>.
5058 TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
5059 TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
5060 TypeCaseClause = TypeSwitchCase ":" StatementList .
5061 TypeSwitchCase = "case" TypeList | "default" .
5062 TypeList = Type { "," Type } .
5066 The TypeSwitchGuard may include a
5067 <a href="#Short_variable_declarations">short variable declaration</a>.
5068 When that form is used, the variable is declared at the end of the
5069 TypeSwitchCase in the <a href="#Blocks">implicit block</a> of each clause.
5070 In clauses with a case listing exactly one type, the variable
5071 has that type; otherwise, the variable has the type of the expression
5072 in the TypeSwitchGuard.
5076 Instead of a type, a case may use the predeclared identifier
5077 <a href="#Predeclared_identifiers"><code>nil</code></a>;
5078 that case is selected when the expression in the TypeSwitchGuard
5079 is a <code>nil</code> interface value.
5080 There may be at most one <code>nil</code> case.
5084 Given an expression <code>x</code> of type <code>interface{}</code>,
5085 the following type switch:
5089 switch i := x.(type) {
5091 printString("x is nil") // type of i is type of x (interface{})
5093 printInt(i) // type of i is int
5095 printFloat64(i) // type of i is float64
5096 case func(int) float64:
5097 printFunction(i) // type of i is func(int) float64
5099 printString("type is bool or string") // type of i is type of x (interface{})
5101 printString("don't know the type") // type of i is type of x (interface{})
5110 v := x // x is evaluated exactly once
5112 i := v // type of i is type of x (interface{})
5113 printString("x is nil")
5114 } else if i, isInt := v.(int); isInt {
5115 printInt(i) // type of i is int
5116 } else if i, isFloat64 := v.(float64); isFloat64 {
5117 printFloat64(i) // type of i is float64
5118 } else if i, isFunc := v.(func(int) float64); isFunc {
5119 printFunction(i) // type of i is func(int) float64
5121 _, isBool := v.(bool)
5122 _, isString := v.(string)
5123 if isBool || isString {
5124 i := v // type of i is type of x (interface{})
5125 printString("type is bool or string")
5127 i := v // type of i is type of x (interface{})
5128 printString("don't know the type")
5134 The type switch guard may be preceded by a simple statement, which
5135 executes before the guard is evaluated.
5139 The "fallthrough" statement is not permitted in a type switch.
5142 <h3 id="For_statements">For statements</h3>
5145 A "for" statement specifies repeated execution of a block. There are three forms:
5146 The iteration may be controlled by a single condition, a "for" clause, or a "range" clause.
5150 ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
5151 Condition = Expression .
5154 <h4 id="For_condition">For statements with single condition</h4>
5157 In its simplest form, a "for" statement specifies the repeated execution of
5158 a block as long as a boolean condition evaluates to true.
5159 The condition is evaluated before each iteration.
5160 If the condition is absent, it is equivalent to the boolean value
5170 <h4 id="For_clause">For statements with <code>for</code> clause</h4>
5173 A "for" statement with a ForClause is also controlled by its condition, but
5174 additionally it may specify an <i>init</i>
5175 and a <i>post</i> statement, such as an assignment,
5176 an increment or decrement statement. The init statement may be a
5177 <a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not.
5178 Variables declared by the init statement are re-used in each iteration.
5182 ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
5183 InitStmt = SimpleStmt .
5184 PostStmt = SimpleStmt .
5188 for i := 0; i < 10; i++ {
5194 If non-empty, the init statement is executed once before evaluating the
5195 condition for the first iteration;
5196 the post statement is executed after each execution of the block (and
5197 only if the block was executed).
5198 Any element of the ForClause may be empty but the
5199 <a href="#Semicolons">semicolons</a> are
5200 required unless there is only a condition.
5201 If the condition is absent, it is equivalent to the boolean value
5206 for cond { S() } is the same as for ; cond ; { S() }
5207 for { S() } is the same as for true { S() }
5210 <h4 id="For_range">For statements with <code>range</code> clause</h4>
5213 A "for" statement with a "range" clause
5214 iterates through all entries of an array, slice, string or map,
5215 or values received on a channel. For each entry it assigns <i>iteration values</i>
5216 to corresponding <i>iteration variables</i> if present and then executes the block.
5220 RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .
5224 The expression on the right in the "range" clause is called the <i>range expression</i>,
5225 which may be an array, pointer to an array, slice, string, map, or channel permitting
5226 <a href="#Receive_operator">receive operations</a>.
5227 As with an assignment, if present the operands on the left must be
5228 <a href="#Address_operators">addressable</a> or map index expressions; they
5229 denote the iteration variables. If the range expression is a channel, at most
5230 one iteration variable is permitted, otherwise there may be up to two.
5231 If the last iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
5232 the range clause is equivalent to the same clause without that identifier.
5236 The range expression <code>x</code> is evaluated once before beginning the loop,
5237 with one exception: if at most one iteration variable is present and
5238 <code>len(x)</code> is <a href="#Length_and_capacity">constant</a>,
5239 the range expression is not evaluated.
5243 Function calls on the left are evaluated once per iteration.
5244 For each iteration, iteration values are produced as follows
5245 if the respective iteration variables are present:
5248 <pre class="grammar">
5249 Range expression 1st value 2nd value
5251 array or slice a [n]E, *[n]E, or []E index i int a[i] E
5252 string s string type index i int see below rune
5253 map m map[K]V key k K m[k] V
5254 channel c chan E, <-chan E element e E
5259 For an array, pointer to array, or slice value <code>a</code>, the index iteration
5260 values are produced in increasing order, starting at element index 0.
5261 If at most one iteration variable is present, the range loop produces
5262 iteration values from 0 up to <code>len(a)-1</code> and does not index into the array
5263 or slice itself. For a <code>nil</code> slice, the number of iterations is 0.
5267 For a string value, the "range" clause iterates over the Unicode code points
5268 in the string starting at byte index 0. On successive iterations, the index value will be the
5269 index of the first byte of successive UTF-8-encoded code points in the string,
5270 and the second value, of type <code>rune</code>, will be the value of
5271 the corresponding code point. If the iteration encounters an invalid
5272 UTF-8 sequence, the second value will be <code>0xFFFD</code>,
5273 the Unicode replacement character, and the next iteration will advance
5274 a single byte in the string.
5278 The iteration order over maps is not specified
5279 and is not guaranteed to be the same from one iteration to the next.
5280 If a map entry that has not yet been reached is removed during iteration,
5281 the corresponding iteration value will not be produced. If a map entry is
5282 created during iteration, that entry may be produced during the iteration or
5283 may be skipped. The choice may vary for each entry created and from one
5284 iteration to the next.
5285 If the map is <code>nil</code>, the number of iterations is 0.
5289 For channels, the iteration values produced are the successive values sent on
5290 the channel until the channel is <a href="#Close">closed</a>. If the channel
5291 is <code>nil</code>, the range expression blocks forever.
5296 The iteration values are assigned to the respective
5297 iteration variables as in an <a href="#Assignments">assignment statement</a>.
5301 The iteration variables may be declared by the "range" clause using a form of
5302 <a href="#Short_variable_declarations">short variable declaration</a>
5304 In this case their types are set to the types of the respective iteration values
5305 and their <a href="#Declarations_and_scope">scope</a> is the block of the "for"
5306 statement; they are re-used in each iteration.
5307 If the iteration variables are declared outside the "for" statement,
5308 after execution their values will be those of the last iteration.
5312 var testdata *struct {
5315 for i, _ := range testdata.a {
5316 // testdata.a is never evaluated; len(testdata.a) is constant
5317 // i ranges from 0 to 6
5322 for i, s := range a {
5324 // type of s is string
5330 var val interface{} // element type of m is assignable to val
5331 m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}
5332 for key, val = range m {
5335 // key == last map key encountered in iteration
5338 var ch chan Work = producer()
5348 <h3 id="Go_statements">Go statements</h3>
5351 A "go" statement starts the execution of a function call
5352 as an independent concurrent thread of control, or <i>goroutine</i>,
5353 within the same address space.
5357 GoStmt = "go" Expression .
5361 The expression must be a function or method call; it cannot be parenthesized.
5362 Calls of built-in functions are restricted as for
5363 <a href="#Expression_statements">expression statements</a>.
5367 The function value and parameters are
5368 <a href="#Calls">evaluated as usual</a>
5369 in the calling goroutine, but
5370 unlike with a regular call, program execution does not wait
5371 for the invoked function to complete.
5372 Instead, the function begins executing independently
5374 When the function terminates, its goroutine also terminates.
5375 If the function has any return values, they are discarded when the
5381 go func(ch chan<- bool) { for { sleep(10); ch <- true }} (c)
5385 <h3 id="Select_statements">Select statements</h3>
5388 A "select" statement chooses which of a set of possible
5389 <a href="#Send_statements">send</a> or
5390 <a href="#Receive_operator">receive</a>
5391 operations will proceed.
5392 It looks similar to a
5393 <a href="#Switch_statements">"switch"</a> statement but with the
5394 cases all referring to communication operations.
5398 SelectStmt = "select" "{" { CommClause } "}" .
5399 CommClause = CommCase ":" StatementList .
5400 CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
5401 RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
5402 RecvExpr = Expression .
5406 A case with a RecvStmt may assign the result of a RecvExpr to one or
5407 two variables, which may be declared using a
5408 <a href="#Short_variable_declarations">short variable declaration</a>.
5409 The RecvExpr must be a (possibly parenthesized) receive operation.
5410 There can be at most one default case and it may appear anywhere
5411 in the list of cases.
5415 Execution of a "select" statement proceeds in several steps:
5420 For all the cases in the statement, the channel operands of receive operations
5421 and the channel and right-hand-side expressions of send statements are
5422 evaluated exactly once, in source order, upon entering the "select" statement.
5423 The result is a set of channels to receive from or send to,
5424 and the corresponding values to send.
5425 Any side effects in that evaluation will occur irrespective of which (if any)
5426 communication operation is selected to proceed.
5427 Expressions on the left-hand side of a RecvStmt with a short variable declaration
5428 or assignment are not yet evaluated.
5432 If one or more of the communications can proceed,
5433 a single one that can proceed is chosen via a uniform pseudo-random selection.
5434 Otherwise, if there is a default case, that case is chosen.
5435 If there is no default case, the "select" statement blocks until
5436 at least one of the communications can proceed.
5440 Unless the selected case is the default case, the respective communication
5441 operation is executed.
5445 If the selected case is a RecvStmt with a short variable declaration or
5446 an assignment, the left-hand side expressions are evaluated and the
5447 received value (or values) are assigned.
5451 The statement list of the selected case is executed.
5456 Since communication on <code>nil</code> channels can never proceed,
5457 a select with only <code>nil</code> channels and no default case blocks forever.
5462 var c, c1, c2, c3, c4 chan int
5466 print("received ", i1, " from c1\n")
5468 print("sent ", i2, " to c2\n")
5469 case i3, ok := (<-c3): // same as: i3, ok := <-c3
5471 print("received ", i3, " from c3\n")
5473 print("c3 is closed\n")
5475 case a[f()] = <-c4:
5477 // case t := <-c4
5480 print("no communication\n")
5483 for { // send random sequence of bits to c
5485 case c <- 0: // note: no statement, no fallthrough, no folding of cases
5490 select {} // block forever
5494 <h3 id="Return_statements">Return statements</h3>
5497 A "return" statement in a function <code>F</code> terminates the execution
5498 of <code>F</code>, and optionally provides one or more result values.
5499 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
5500 are executed before <code>F</code> returns to its caller.
5504 ReturnStmt = "return" [ ExpressionList ] .
5508 In a function without a result type, a "return" statement must not
5509 specify any result values.
5518 There are three ways to return values from a function with a result
5523 <li>The return value or values may be explicitly listed
5524 in the "return" statement. Each expression must be single-valued
5525 and <a href="#Assignability">assignable</a>
5526 to the corresponding element of the function's result type.
5528 func simpleF() int {
5532 func complexF1() (re float64, im float64) {
5537 <li>The expression list in the "return" statement may be a single
5538 call to a multi-valued function. The effect is as if each value
5539 returned from that function were assigned to a temporary
5540 variable with the type of the respective value, followed by a
5541 "return" statement listing these variables, at which point the
5542 rules of the previous case apply.
5544 func complexF2() (re float64, im float64) {
5549 <li>The expression list may be empty if the function's result
5550 type specifies names for its <a href="#Function_types">result parameters</a>.
5551 The result parameters act as ordinary local variables
5552 and the function may assign values to them as necessary.
5553 The "return" statement returns the values of these variables.
5555 func complexF3() (re float64, im float64) {
5561 func (devnull) Write(p []byte) (n int, _ error) {
5570 Regardless of how they are declared, all the result values are initialized to
5571 the <a href="#The_zero_value">zero values</a> for their type upon entry to the
5572 function. A "return" statement that specifies results sets the result parameters before
5573 any deferred functions are executed.
5577 Implementation restriction: A compiler may disallow an empty expression list
5578 in a "return" statement if a different entity (constant, type, or variable)
5579 with the same name as a result parameter is in
5580 <a href="#Declarations_and_scope">scope</a> at the place of the return.
5584 func f(n int) (res int, err error) {
5585 if _, err := f(n-1); err != nil {
5586 return // invalid return statement: err is shadowed
5592 <h3 id="Break_statements">Break statements</h3>
5595 A "break" statement terminates execution of the innermost
5596 <a href="#For_statements">"for"</a>,
5597 <a href="#Switch_statements">"switch"</a>, or
5598 <a href="#Select_statements">"select"</a> statement
5599 within the same function.
5603 BreakStmt = "break" [ Label ] .
5607 If there is a label, it must be that of an enclosing
5608 "for", "switch", or "select" statement,
5609 and that is the one whose execution terminates.
5614 for i = 0; i < n; i++ {
5615 for j = 0; j < m; j++ {
5628 <h3 id="Continue_statements">Continue statements</h3>
5631 A "continue" statement begins the next iteration of the
5632 innermost <a href="#For_statements">"for" loop</a> at its post statement.
5633 The "for" loop must be within the same function.
5637 ContinueStmt = "continue" [ Label ] .
5641 If there is a label, it must be that of an enclosing
5642 "for" statement, and that is the one whose execution
5648 for y, row := range rows {
5649 for x, data := range row {
5650 if data == endOfRow {
5653 row[x] = data + bias(x, y)
5658 <h3 id="Goto_statements">Goto statements</h3>
5661 A "goto" statement transfers control to the statement with the corresponding label
5662 within the same function.
5666 GotoStmt = "goto" Label .
5674 Executing the "goto" statement must not cause any variables to come into
5675 <a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto.
5676 For instance, this example:
5686 is erroneous because the jump to label <code>L</code> skips
5687 the creation of <code>v</code>.
5691 A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block.
5692 For instance, this example:
5709 is erroneous because the label <code>L1</code> is inside
5710 the "for" statement's block but the <code>goto</code> is not.
5713 <h3 id="Fallthrough_statements">Fallthrough statements</h3>
5716 A "fallthrough" statement transfers control to the first statement of the
5717 next case clause in an <a href="#Expression_switches">expression "switch" statement</a>.
5718 It may be used only as the final non-empty statement in such a clause.
5722 FallthroughStmt = "fallthrough" .
5726 <h3 id="Defer_statements">Defer statements</h3>
5729 A "defer" statement invokes a function whose execution is deferred
5730 to the moment the surrounding function returns, either because the
5731 surrounding function executed a <a href="#Return_statements">return statement</a>,
5732 reached the end of its <a href="#Function_declarations">function body</a>,
5733 or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>.
5737 DeferStmt = "defer" Expression .
5741 The expression must be a function or method call; it cannot be parenthesized.
5742 Calls of built-in functions are restricted as for
5743 <a href="#Expression_statements">expression statements</a>.
5747 Each time a "defer" statement
5748 executes, the function value and parameters to the call are
5749 <a href="#Calls">evaluated as usual</a>
5750 and saved anew but the actual function is not invoked.
5751 Instead, deferred functions are invoked immediately before
5752 the surrounding function returns, in the reverse order
5753 they were deferred. That is, if the surrounding function
5754 returns through an explicit <a href="#Return_statements">return statement</a>,
5755 deferred functions are executed <i>after</i> any result parameters are set
5756 by that return statement but <i>before</i> the function returns to its caller.
5757 If a deferred function value evaluates
5758 to <code>nil</code>, execution <a href="#Handling_panics">panics</a>
5759 when the function is invoked, not when the "defer" statement is executed.
5763 For instance, if the deferred function is
5764 a <a href="#Function_literals">function literal</a> and the surrounding
5765 function has <a href="#Function_types">named result parameters</a> that
5766 are in scope within the literal, the deferred function may access and modify
5767 the result parameters before they are returned.
5768 If the deferred function has any return values, they are discarded when
5769 the function completes.
5770 (See also the section on <a href="#Handling_panics">handling panics</a>.)
5775 defer unlock(l) // unlocking happens before surrounding function returns
5777 // prints 3 2 1 0 before surrounding function returns
5778 for i := 0; i <= 3; i++ {
5783 func f() (result int) {
5785 // result is accessed after it was set to 6 by the return statement
5792 <h2 id="Built-in_functions">Built-in functions</h2>
5795 Built-in functions are
5796 <a href="#Predeclared_identifiers">predeclared</a>.
5797 They are called like any other function but some of them
5798 accept a type instead of an expression as the first argument.
5802 The built-in functions do not have standard Go types,
5803 so they can only appear in <a href="#Calls">call expressions</a>;
5804 they cannot be used as function values.
5807 <h3 id="Close">Close</h3>
5810 For a channel <code>c</code>, the built-in function <code>close(c)</code>
5811 records that no more values will be sent on the channel.
5812 It is an error if <code>c</code> is a receive-only channel.
5813 Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>.
5814 Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>.
5815 After calling <code>close</code>, and after any previously
5816 sent values have been received, receive operations will return
5817 the zero value for the channel's type without blocking.
5818 The multi-valued <a href="#Receive_operator">receive operation</a>
5819 returns a received value along with an indication of whether the channel is closed.
5823 <h3 id="Length_and_capacity">Length and capacity</h3>
5826 The built-in functions <code>len</code> and <code>cap</code> take arguments
5827 of various types and return a result of type <code>int</code>.
5828 The implementation guarantees that the result always fits into an <code>int</code>.
5831 <pre class="grammar">
5832 Call Argument type Result
5834 len(s) string type string length in bytes
5835 [n]T, *[n]T array length (== n)
5837 map[K]T map length (number of defined keys)
5838 chan T number of elements queued in channel buffer
5840 cap(s) [n]T, *[n]T array length (== n)
5842 chan T channel buffer capacity
5846 The capacity of a slice is the number of elements for which there is
5847 space allocated in the underlying array.
5848 At any time the following relationship holds:
5852 0 <= len(s) <= cap(s)
5856 The length of a <code>nil</code> slice, map or channel is 0.
5857 The capacity of a <code>nil</code> slice or channel is 0.
5861 The expression <code>len(s)</code> is <a href="#Constants">constant</a> if
5862 <code>s</code> is a string constant. The expressions <code>len(s)</code> and
5863 <code>cap(s)</code> are constants if the type of <code>s</code> is an array
5864 or pointer to an array and the expression <code>s</code> does not contain
5865 <a href="#Receive_operator">channel receives</a> or (non-constant)
5866 <a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated.
5867 Otherwise, invocations of <code>len</code> and <code>cap</code> are not
5868 constant and <code>s</code> is evaluated.
5873 c1 = imag(2i) // imag(2i) = 2.0 is a constant
5874 c2 = len([10]float64{2}) // [10]float64{2} contains no function calls
5875 c3 = len([10]float64{c1}) // [10]float64{c1} contains no function calls
5876 c4 = len([10]float64{imag(2i)}) // imag(2i) is a constant and no function call is issued
5877 c5 = len([10]float64{imag(z)}) // invalid: imag(z) is a (non-constant) function call
5882 <h3 id="Allocation">Allocation</h3>
5885 The built-in function <code>new</code> takes a type <code>T</code>,
5886 allocates storage for a <a href="#Variables">variable</a> of that type
5887 at run time, and returns a value of type <code>*T</code>
5888 <a href="#Pointer_types">pointing</a> to it.
5889 The variable is initialized as described in the section on
5890 <a href="#The_zero_value">initial values</a>.
5893 <pre class="grammar">
5902 type S struct { a int; b float64 }
5907 allocates storage for a variable of type <code>S</code>,
5908 initializes it (<code>a=0</code>, <code>b=0.0</code>),
5909 and returns a value of type <code>*S</code> containing the address
5913 <h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3>
5916 The built-in function <code>make</code> takes a type <code>T</code>,
5917 which must be a slice, map or channel type,
5918 optionally followed by a type-specific list of expressions.
5919 It returns a value of type <code>T</code> (not <code>*T</code>).
5920 The memory is initialized as described in the section on
5921 <a href="#The_zero_value">initial values</a>.
5924 <pre class="grammar">
5927 make(T, n) slice slice of type T with length n and capacity n
5928 make(T, n, m) slice slice of type T with length n and capacity m
5930 make(T) map map of type T
5931 make(T, n) map map of type T with initial space for approximately n elements
5933 make(T) channel unbuffered channel of type T
5934 make(T, n) channel buffered channel of type T, buffer size n
5939 Each of the size arguments <code>n</code> and <code>m</code> must be of integer type
5940 or an untyped <a href="#Constants">constant</a>.
5941 A constant size argument must be non-negative and <a href="#Representability">representable</a>
5942 by a value of type <code>int</code>; if it is an untyped constant it is given type <code>int</code>.
5943 If both <code>n</code> and <code>m</code> are provided and are constant, then
5944 <code>n</code> must be no larger than <code>m</code>.
5945 If <code>n</code> is negative or larger than <code>m</code> at run time,
5946 a <a href="#Run_time_panics">run-time panic</a> occurs.
5950 s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100
5951 s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000
5952 s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type int
5953 s := make([]int, 10, 0) // illegal: len(s) > cap(s)
5954 c := make(chan int, 10) // channel with a buffer size of 10
5955 m := make(map[string]int, 100) // map with initial space for approximately 100 elements
5959 Calling <code>make</code> with a map type and size hint <code>n</code> will
5960 create a map with initial space to hold <code>n</code> map elements.
5961 The precise behavior is implementation-dependent.
5965 <h3 id="Appending_and_copying_slices">Appending to and copying slices</h3>
5968 The built-in functions <code>append</code> and <code>copy</code> assist in
5969 common slice operations.
5970 For both functions, the result is independent of whether the memory referenced
5971 by the arguments overlaps.
5975 The <a href="#Function_types">variadic</a> function <code>append</code>
5976 appends zero or more values <code>x</code>
5977 to <code>s</code> of type <code>S</code>, which must be a slice type, and
5978 returns the resulting slice, also of type <code>S</code>.
5979 The values <code>x</code> are passed to a parameter of type <code>...T</code>
5980 where <code>T</code> is the <a href="#Slice_types">element type</a> of
5981 <code>S</code> and the respective
5982 <a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply.
5983 As a special case, <code>append</code> also accepts a first argument
5984 assignable to type <code>[]byte</code> with a second argument of
5985 string type followed by <code>...</code>. This form appends the
5986 bytes of the string.
5989 <pre class="grammar">
5990 append(s S, x ...T) S // T is the element type of S
5994 If the capacity of <code>s</code> is not large enough to fit the additional
5995 values, <code>append</code> allocates a new, sufficiently large underlying
5996 array that fits both the existing slice elements and the additional values.
5997 Otherwise, <code>append</code> re-uses the underlying array.
6002 s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2}
6003 s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7}
6004 s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
6005 s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
6008 t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"}
6011 b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' }
6015 The function <code>copy</code> copies slice elements from
6016 a source <code>src</code> to a destination <code>dst</code> and returns the
6017 number of elements copied.
6018 Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be
6019 <a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>.
6020 The number of elements copied is the minimum of
6021 <code>len(src)</code> and <code>len(dst)</code>.
6022 As a special case, <code>copy</code> also accepts a destination argument assignable
6023 to type <code>[]byte</code> with a source argument of a string type.
6024 This form copies the bytes from the string into the byte slice.
6027 <pre class="grammar">
6028 copy(dst, src []T) int
6029 copy(dst []byte, src string) int
6037 var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7}
6038 var s = make([]int, 6)
6039 var b = make([]byte, 5)
6040 n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5}
6041 n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5}
6042 n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello")
6046 <h3 id="Deletion_of_map_elements">Deletion of map elements</h3>
6049 The built-in function <code>delete</code> removes the element with key
6050 <code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The
6051 type of <code>k</code> must be <a href="#Assignability">assignable</a>
6052 to the key type of <code>m</code>.
6055 <pre class="grammar">
6056 delete(m, k) // remove element m[k] from map m
6060 If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code>
6061 does not exist, <code>delete</code> is a no-op.
6065 <h3 id="Complex_numbers">Manipulating complex numbers</h3>
6068 Three functions assemble and disassemble complex numbers.
6069 The built-in function <code>complex</code> constructs a complex
6070 value from a floating-point real and imaginary part, while
6071 <code>real</code> and <code>imag</code>
6072 extract the real and imaginary parts of a complex value.
6075 <pre class="grammar">
6076 complex(realPart, imaginaryPart floatT) complexT
6077 real(complexT) floatT
6078 imag(complexT) floatT
6082 The type of the arguments and return value correspond.
6083 For <code>complex</code>, the two arguments must be of the same
6084 floating-point type and the return type is the complex type
6085 with the corresponding floating-point constituents:
6086 <code>complex64</code> for <code>float32</code> arguments, and
6087 <code>complex128</code> for <code>float64</code> arguments.
6088 If one of the arguments evaluates to an untyped constant, it is first implicitly
6089 <a href="#Conversions">converted</a> to the type of the other argument.
6090 If both arguments evaluate to untyped constants, they must be non-complex
6091 numbers or their imaginary parts must be zero, and the return value of
6092 the function is an untyped complex constant.
6096 For <code>real</code> and <code>imag</code>, the argument must be
6097 of complex type, and the return type is the corresponding floating-point
6098 type: <code>float32</code> for a <code>complex64</code> argument, and
6099 <code>float64</code> for a <code>complex128</code> argument.
6100 If the argument evaluates to an untyped constant, it must be a number,
6101 and the return value of the function is an untyped floating-point constant.
6105 The <code>real</code> and <code>imag</code> functions together form the inverse of
6106 <code>complex</code>, so for a value <code>z</code> of a complex type <code>Z</code>,
6107 <code>z == Z(complex(real(z), imag(z)))</code>.
6111 If the operands of these functions are all constants, the return
6112 value is a constant.
6116 var a = complex(2, -2) // complex128
6117 const b = complex(1.0, -1.4) // untyped complex constant 1 - 1.4i
6118 x := float32(math.Cos(math.Pi/2)) // float32
6119 var c64 = complex(5, -x) // complex64
6120 var s int = complex(1, 0) // untyped complex constant 1 + 0i can be converted to int
6121 _ = complex(1, 2<<s) // illegal: 2 assumes floating-point type, cannot shift
6122 var rl = real(c64) // float32
6123 var im = imag(a) // float64
6124 const c = imag(b) // untyped constant -1.4
6125 _ = imag(3 << s) // illegal: 3 assumes complex type, cannot shift
6128 <h3 id="Handling_panics">Handling panics</h3>
6130 <p> Two built-in functions, <code>panic</code> and <code>recover</code>,
6131 assist in reporting and handling <a href="#Run_time_panics">run-time panics</a>
6132 and program-defined error conditions.
6135 <pre class="grammar">
6136 func panic(interface{})
6137 func recover() interface{}
6141 While executing a function <code>F</code>,
6142 an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a>
6143 terminates the execution of <code>F</code>.
6144 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
6145 are then executed as usual.
6146 Next, any deferred functions run by <code>F's</code> caller are run,
6147 and so on up to any deferred by the top-level function in the executing goroutine.
6148 At that point, the program is terminated and the error
6149 condition is reported, including the value of the argument to <code>panic</code>.
6150 This termination sequence is called <i>panicking</i>.
6155 panic("unreachable")
6156 panic(Error("cannot parse"))
6160 The <code>recover</code> function allows a program to manage behavior
6161 of a panicking goroutine.
6162 Suppose a function <code>G</code> defers a function <code>D</code> that calls
6163 <code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code>
6165 When the running of deferred functions reaches <code>D</code>,
6166 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>.
6167 If <code>D</code> returns normally, without starting a new
6168 <code>panic</code>, the panicking sequence stops. In that case,
6169 the state of functions called between <code>G</code> and the call to <code>panic</code>
6170 is discarded, and normal execution resumes.
6171 Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s
6172 execution terminates by returning to its caller.
6176 The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds:
6180 <code>panic</code>'s argument was <code>nil</code>;
6183 the goroutine is not panicking;
6186 <code>recover</code> was not called directly by a deferred function.
6191 The <code>protect</code> function in the example below invokes
6192 the function argument <code>g</code> and protects callers from
6193 run-time panics raised by <code>g</code>.
6197 func protect(g func()) {
6199 log.Println("done") // Println executes normally even if there is a panic
6200 if x := recover(); x != nil {
6201 log.Printf("run time panic: %v", x)
6204 log.Println("start")
6210 <h3 id="Bootstrapping">Bootstrapping</h3>
6213 Current implementations provide several built-in functions useful during
6214 bootstrapping. These functions are documented for completeness but are not
6215 guaranteed to stay in the language. They do not return a result.
6218 <pre class="grammar">
6221 print prints all arguments; formatting of arguments is implementation-specific
6222 println like print but prints spaces between arguments and a newline at the end
6226 Implementation restriction: <code>print</code> and <code>println</code> need not
6227 accept arbitrary argument types, but printing of boolean, numeric, and string
6228 <a href="#Types">types</a> must be supported.
6231 <h2 id="Packages">Packages</h2>
6234 Go programs are constructed by linking together <i>packages</i>.
6235 A package in turn is constructed from one or more source files
6236 that together declare constants, types, variables and functions
6237 belonging to the package and which are accessible in all files
6238 of the same package. Those elements may be
6239 <a href="#Exported_identifiers">exported</a> and used in another package.
6242 <h3 id="Source_file_organization">Source file organization</h3>
6245 Each source file consists of a package clause defining the package
6246 to which it belongs, followed by a possibly empty set of import
6247 declarations that declare packages whose contents it wishes to use,
6248 followed by a possibly empty set of declarations of functions,
6249 types, variables, and constants.
6253 SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
6256 <h3 id="Package_clause">Package clause</h3>
6259 A package clause begins each source file and defines the package
6260 to which the file belongs.
6264 PackageClause = "package" PackageName .
6265 PackageName = identifier .
6269 The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>.
6277 A set of files sharing the same PackageName form the implementation of a package.
6278 An implementation may require that all source files for a package inhabit the same directory.
6281 <h3 id="Import_declarations">Import declarations</h3>
6284 An import declaration states that the source file containing the declaration
6285 depends on functionality of the <i>imported</i> package
6286 (<a href="#Program_initialization_and_execution">§Program initialization and execution</a>)
6287 and enables access to <a href="#Exported_identifiers">exported</a> identifiers
6289 The import names an identifier (PackageName) to be used for access and an ImportPath
6290 that specifies the package to be imported.
6294 ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
6295 ImportSpec = [ "." | PackageName ] ImportPath .
6296 ImportPath = string_lit .
6300 The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a>
6301 to access exported identifiers of the package within the importing source file.
6302 It is declared in the <a href="#Blocks">file block</a>.
6303 If the PackageName is omitted, it defaults to the identifier specified in the
6304 <a href="#Package_clause">package clause</a> of the imported package.
6305 If an explicit period (<code>.</code>) appears instead of a name, all the
6306 package's exported identifiers declared in that package's
6307 <a href="#Blocks">package block</a> will be declared in the importing source
6308 file's file block and must be accessed without a qualifier.
6312 The interpretation of the ImportPath is implementation-dependent but
6313 it is typically a substring of the full file name of the compiled
6314 package and may be relative to a repository of installed packages.
6318 Implementation restriction: A compiler may restrict ImportPaths to
6319 non-empty strings using only characters belonging to
6320 <a href="https://www.unicode.org/versions/Unicode6.3.0/">Unicode's</a>
6321 L, M, N, P, and S general categories (the Graphic characters without
6322 spaces) and may also exclude the characters
6323 <code>!"#$%&'()*,:;<=>?[\]^`{|}</code>
6324 and the Unicode replacement character U+FFFD.
6328 Assume we have compiled a package containing the package clause
6329 <code>package math</code>, which exports function <code>Sin</code>, and
6330 installed the compiled package in the file identified by
6331 <code>"lib/math"</code>.
6332 This table illustrates how <code>Sin</code> is accessed in files
6333 that import the package after the
6334 various types of import declaration.
6337 <pre class="grammar">
6338 Import declaration Local name of Sin
6340 import "lib/math" math.Sin
6341 import m "lib/math" m.Sin
6342 import . "lib/math" Sin
6346 An import declaration declares a dependency relation between
6347 the importing and imported package.
6348 It is illegal for a package to import itself, directly or indirectly,
6349 or to directly import a package without
6350 referring to any of its exported identifiers. To import a package solely for
6351 its side-effects (initialization), use the <a href="#Blank_identifier">blank</a>
6352 identifier as explicit package name:
6360 <h3 id="An_example_package">An example package</h3>
6363 Here is a complete Go package that implements a concurrent prime sieve.
6371 // Send the sequence 2, 3, 4, … to channel 'ch'.
6372 func generate(ch chan<- int) {
6374 ch <- i // Send 'i' to channel 'ch'.
6378 // Copy the values from channel 'src' to channel 'dst',
6379 // removing those divisible by 'prime'.
6380 func filter(src <-chan int, dst chan<- int, prime int) {
6381 for i := range src { // Loop over values received from 'src'.
6383 dst <- i // Send 'i' to channel 'dst'.
6388 // The prime sieve: Daisy-chain filter processes together.
6390 ch := make(chan int) // Create a new channel.
6391 go generate(ch) // Start generate() as a subprocess.
6394 fmt.Print(prime, "\n")
6395 ch1 := make(chan int)
6396 go filter(ch, ch1, prime)
6406 <h2 id="Program_initialization_and_execution">Program initialization and execution</h2>
6408 <h3 id="The_zero_value">The zero value</h3>
6410 When storage is allocated for a <a href="#Variables">variable</a>,
6411 either through a declaration or a call of <code>new</code>, or when
6412 a new value is created, either through a composite literal or a call
6413 of <code>make</code>,
6414 and no explicit initialization is provided, the variable or value is
6415 given a default value. Each element of such a variable or value is
6416 set to the <i>zero value</i> for its type: <code>false</code> for booleans,
6417 <code>0</code> for numeric types, <code>""</code>
6418 for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps.
6419 This initialization is done recursively, so for instance each element of an
6420 array of structs will have its fields zeroed if no value is specified.
6423 These two simple declarations are equivalent:
6436 type T struct { i int; f float64; next *T }
6441 the following holds:
6451 The same would also be true after
6458 <h3 id="Package_initialization">Package initialization</h3>
6461 Within a package, package-level variable initialization proceeds stepwise,
6462 with each step selecting the variable earliest in <i>declaration order</i>
6463 which has no dependencies on uninitialized variables.
6467 More precisely, a package-level variable is considered <i>ready for
6468 initialization</i> if it is not yet initialized and either has
6469 no <a href="#Variable_declarations">initialization expression</a> or
6470 its initialization expression has no <i>dependencies</i> on uninitialized variables.
6471 Initialization proceeds by repeatedly initializing the next package-level
6472 variable that is earliest in declaration order and ready for initialization,
6473 until there are no variables ready for initialization.
6477 If any variables are still uninitialized when this
6478 process ends, those variables are part of one or more initialization cycles,
6479 and the program is not valid.
6483 Multiple variables on the left-hand side of a variable declaration initialized
6484 by single (multi-valued) expression on the right-hand side are initialized
6485 together: If any of the variables on the left-hand side is initialized, all
6486 those variables are initialized in the same step.
6491 var a, b = f() // a and b are initialized together, before x is initialized
6495 For the purpose of package initialization, <a href="#Blank_identifier">blank</a>
6496 variables are treated like any other variables in declarations.
6500 The declaration order of variables declared in multiple files is determined
6501 by the order in which the files are presented to the compiler: Variables
6502 declared in the first file are declared before any of the variables declared
6503 in the second file, and so on.
6507 Dependency analysis does not rely on the actual values of the
6508 variables, only on lexical <i>references</i> to them in the source,
6509 analyzed transitively. For instance, if a variable <code>x</code>'s
6510 initialization expression refers to a function whose body refers to
6511 variable <code>y</code> then <code>x</code> depends on <code>y</code>.
6517 A reference to a variable or function is an identifier denoting that
6518 variable or function.
6522 A reference to a method <code>m</code> is a
6523 <a href="#Method_values">method value</a> or
6524 <a href="#Method_expressions">method expression</a> of the form
6525 <code>t.m</code>, where the (static) type of <code>t</code> is
6526 not an interface type, and the method <code>m</code> is in the
6527 <a href="#Method_sets">method set</a> of <code>t</code>.
6528 It is immaterial whether the resulting function value
6529 <code>t.m</code> is invoked.
6533 A variable, function, or method <code>x</code> depends on a variable
6534 <code>y</code> if <code>x</code>'s initialization expression or body
6535 (for functions and methods) contains a reference to <code>y</code>
6536 or to a function or method that depends on <code>y</code>.
6541 For example, given the declarations
6549 d = 3 // == 5 after initialization has finished
6559 the initialization order is <code>d</code>, <code>b</code>, <code>c</code>, <code>a</code>.
6560 Note that the order of subexpressions in initialization expressions is irrelevant:
6561 <code>a = c + b</code> and <code>a = b + c</code> result in the same initialization
6562 order in this example.
6566 Dependency analysis is performed per package; only references referring
6567 to variables, functions, and (non-interface) methods declared in the current
6568 package are considered. If other, hidden, data dependencies exists between
6569 variables, the initialization order between those variables is unspecified.
6573 For instance, given the declarations
6577 var x = I(T{}).ab() // x has an undetected, hidden dependency on a and b
6578 var _ = sideEffect() // unrelated to x, a, or b
6582 type I interface { ab() []int }
6584 func (T) ab() []int { return []int{a, b} }
6588 the variable <code>a</code> will be initialized after <code>b</code> but
6589 whether <code>x</code> is initialized before <code>b</code>, between
6590 <code>b</code> and <code>a</code>, or after <code>a</code>, and
6591 thus also the moment at which <code>sideEffect()</code> is called (before
6592 or after <code>x</code> is initialized) is not specified.
6596 Variables may also be initialized using functions named <code>init</code>
6597 declared in the package block, with no arguments and no result parameters.
6605 Multiple such functions may be defined per package, even within a single
6606 source file. In the package block, the <code>init</code> identifier can
6607 be used only to declare <code>init</code> functions, yet the identifier
6608 itself is not <a href="#Declarations_and_scope">declared</a>. Thus
6609 <code>init</code> functions cannot be referred to from anywhere
6614 A package with no imports is initialized by assigning initial values
6615 to all its package-level variables followed by calling all <code>init</code>
6616 functions in the order they appear in the source, possibly in multiple files,
6617 as presented to the compiler.
6618 If a package has imports, the imported packages are initialized
6619 before initializing the package itself. If multiple packages import
6620 a package, the imported package will be initialized only once.
6621 The importing of packages, by construction, guarantees that there
6622 can be no cyclic initialization dependencies.
6626 Package initialization—variable initialization and the invocation of
6627 <code>init</code> functions—happens in a single goroutine,
6628 sequentially, one package at a time.
6629 An <code>init</code> function may launch other goroutines, which can run
6630 concurrently with the initialization code. However, initialization
6632 the <code>init</code> functions: it will not invoke the next one
6633 until the previous one has returned.
6637 To ensure reproducible initialization behavior, build systems are encouraged
6638 to present multiple files belonging to the same package in lexical file name
6639 order to a compiler.
6643 <h3 id="Program_execution">Program execution</h3>
6645 A complete program is created by linking a single, unimported package
6646 called the <i>main package</i> with all the packages it imports, transitively.
6647 The main package must
6648 have package name <code>main</code> and
6649 declare a function <code>main</code> that takes no
6650 arguments and returns no value.
6658 Program execution begins by initializing the main package and then
6659 invoking the function <code>main</code>.
6660 When that function invocation returns, the program exits.
6661 It does not wait for other (non-<code>main</code>) goroutines to complete.
6664 <h2 id="Errors">Errors</h2>
6667 The predeclared type <code>error</code> is defined as
6671 type error interface {
6677 It is the conventional interface for representing an error condition,
6678 with the nil value representing no error.
6679 For instance, a function to read data from a file might be defined:
6683 func Read(f *File, b []byte) (n int, err error)
6686 <h2 id="Run_time_panics">Run-time panics</h2>
6689 Execution errors such as attempting to index an array out
6690 of bounds trigger a <i>run-time panic</i> equivalent to a call of
6691 the built-in function <a href="#Handling_panics"><code>panic</code></a>
6692 with a value of the implementation-defined interface type <code>runtime.Error</code>.
6693 That type satisfies the predeclared interface type
6694 <a href="#Errors"><code>error</code></a>.
6695 The exact error values that
6696 represent distinct run-time error conditions are unspecified.
6702 type Error interface {
6704 // and perhaps other methods
6708 <h2 id="System_considerations">System considerations</h2>
6710 <h3 id="Package_unsafe">Package <code>unsafe</code></h3>
6713 The built-in package <code>unsafe</code>, known to the compiler
6714 and accessible through the <a href="#Import_declarations">import path</a> <code>"unsafe"</code>,
6715 provides facilities for low-level programming including operations
6716 that violate the type system. A package using <code>unsafe</code>
6717 must be vetted manually for type safety and may not be portable.
6718 The package provides the following interface:
6721 <pre class="grammar">
6724 type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type
6725 type Pointer *ArbitraryType
6727 func Alignof(variable ArbitraryType) uintptr
6728 func Offsetof(selector ArbitraryType) uintptr
6729 func Sizeof(variable ArbitraryType) uintptr
6731 type IntegerType int // shorthand for an integer type; it is not a real type
6732 func Add(ptr Pointer, len IntegerType) Pointer
6733 func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType
6737 A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code>
6738 value may not be <a href="#Address_operators">dereferenced</a>.
6739 Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to
6740 a type of underlying type <code>Pointer</code> and vice versa.
6741 The effect of converting between <code>Pointer</code> and <code>uintptr</code> is implementation-defined.
6746 bits = *(*uint64)(unsafe.Pointer(&f))
6748 type ptr unsafe.Pointer
6749 bits = *(*uint64)(ptr(&f))
6755 The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code>
6756 of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code>
6757 as if <code>v</code> was declared via <code>var v = x</code>.
6760 The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a>
6761 <code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code>
6762 or <code>*s</code>, and returns the field offset in bytes relative to the struct's address.
6763 If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable
6764 without pointer indirections through fields of the struct.
6765 For a struct <code>s</code> with field <code>f</code>:
6769 uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&s.f))
6773 Computer architectures may require memory addresses to be <i>aligned</i>;
6774 that is, for addresses of a variable to be a multiple of a factor,
6775 the variable's type's <i>alignment</i>. The function <code>Alignof</code>
6776 takes an expression denoting a variable of any type and returns the
6777 alignment of the (type of the) variable in bytes. For a variable
6782 uintptr(unsafe.Pointer(&x)) % unsafe.Alignof(x) == 0
6786 Calls to <code>Alignof</code>, <code>Offsetof</code>, and
6787 <code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>.
6791 The function <code>Add</code> adds <code>len</code> to <code>ptr</code>
6792 and returns the updated pointer <code>unsafe.Pointer(uintptr(ptr) + uintptr(len))</code>.
6793 The <code>len</code> argument must be of integer type or an untyped <a href="#Constants">constant</a>.
6794 A constant <code>len</code> argument must be <a href="#Representability">representable</a> by a value of type <code>int</code>;
6795 if it is an untyped constant it is given type <code>int</code>.
6796 The rules for <a href="/pkg/unsafe#Pointer">valid uses</a> of <code>Pointer</code> still apply.
6800 The function <code>Slice</code> returns a slice whose underlying array starts at <code>ptr</code>
6801 and whose length and capacity are <code>len</code>.
6802 <code>Slice(ptr, len)</code> is equivalent to
6806 (*[len]ArbitraryType)(unsafe.Pointer(ptr))[:]
6810 except that, as a special case, if <code>ptr</code>
6811 is <code>nil</code> and <code>len</code> is zero,
6812 <code>Slice</code> returns <code>nil</code>.
6816 The <code>len</code> argument must be of integer type or an untyped <a href="#Constants">constant</a>.
6817 A constant <code>len</code> argument must be non-negative and <a href="#Representability">representable</a> by a value of type <code>int</code>;
6818 if it is an untyped constant it is given type <code>int</code>.
6819 At run time, if <code>len</code> is negative,
6820 or if <code>ptr</code> is <code>nil</code> and <code>len</code> is not zero,
6821 a <a href="#Run_time_panics">run-time panic</a> occurs.
6824 <h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3>
6827 For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed:
6830 <pre class="grammar">
6835 uint32, int32, float32 4
6836 uint64, int64, float64, complex64 8
6841 The following minimal alignment properties are guaranteed:
6844 <li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1.
6847 <li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of
6848 all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1.
6851 <li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as
6852 the alignment of a variable of the array's element type.
6857 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.