codekingpro/portable-devtools
114k
1<!--{2 "Title": "The Go Programming Language Specification",3 "Subtitle": "Language version go1.26 (Jan 12, 2026)",4 "Path": "/ref/spec"5}-->6 7<h2 id="Introduction">Introduction</h2>8 9<p>10This is the reference manual for the Go programming language.11For more information and other documents, see <a href="/">go.dev</a>.12</p>13 14<p>15Go is a general-purpose language designed with systems programming16in mind. It is strongly typed and garbage-collected and has explicit17support for concurrent programming. Programs are constructed from18<i>packages</i>, whose properties allow efficient management of19dependencies.20</p>21 22<p>23The syntax is compact and simple to parse, allowing for easy analysis24by automatic tools such as integrated development environments.25</p>26 27<h2 id="Notation">Notation</h2>28<p>29The syntax is specified using a30<a href="https://en.wikipedia.org/wiki/Wirth_syntax_notation">variant</a>31of Extended Backus-Naur Form (EBNF):32</p>33 34<pre class="grammar">35Syntax = { Production } .36Production = production_name "=" [ Expression ] "." .37Expression = Term { "|" Term } .38Term = Factor { Factor } .39Factor = production_name | token [ "…" token ] | Group | Option | Repetition .40Group = "(" Expression ")" .41Option = "[" Expression "]" .42Repetition = "{" Expression "}" .43</pre>44 45<p>46Productions are expressions constructed from terms and the following47operators, in increasing precedence:48</p>49<pre class="grammar">50| alternation51() grouping52[] option (0 or 1 times)53{} repetition (0 to n times)54</pre>55 56<p>57Lowercase production names are used to identify lexical (terminal) tokens.58Non-terminals are in CamelCase. Lexical tokens are enclosed in59double quotes <code>""</code> or back quotes <code>``</code>.60</p>61 62<p>63The form <code>a … b</code> represents the set of characters from64<code>a</code> through <code>b</code> as alternatives. The horizontal65ellipsis <code>…</code> is also used elsewhere in the spec to informally denote various66enumerations or code snippets that are not further specified. The character <code>…</code>67(as opposed to the three characters <code>...</code>) is not a token of the Go68language.69</p>70 71<p>72A link of the form [<a href="#Language_versions">Go 1.xx</a>] indicates that a described73language feature (or some aspect of it) was changed or added with language version 1.xx and74thus requires at minimum that language version to build.75For details, see the <a href="#Language_versions">linked section</a>76in the <a href="#Appendix">appendix</a>.77</p>78 79<h2 id="Source_code_representation">Source code representation</h2>80 81<p>82Source code is Unicode text encoded in83<a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. The text is not84canonicalized, so a single accented code point is distinct from the85same character constructed from combining an accent and a letter;86those are treated as two code points. For simplicity, this document87will use the unqualified term <i>character</i> to refer to a Unicode code point88in the source text.89</p>90<p>91Each code point is distinct; for instance, uppercase and lowercase letters92are different characters.93</p>94<p>95Implementation restriction: For compatibility with other tools, a96compiler may disallow the NUL character (U+0000) in the source text.97</p>98<p>99Implementation restriction: For compatibility with other tools, a100compiler may ignore a UTF-8-encoded byte order mark101(U+FEFF) if it is the first Unicode code point in the source text.102A byte order mark may be disallowed anywhere else in the source.103</p>104 105<h3 id="Characters">Characters</h3>106 107<p>108The following terms are used to denote specific Unicode character categories:109</p>110<pre class="ebnf">111newline = /* the Unicode code point U+000A */ .112unicode_char = /* an arbitrary Unicode code point except newline */ .113unicode_letter = /* a Unicode code point categorized as "Letter" */ .114unicode_digit = /* a Unicode code point categorized as "Number, decimal digit" */ .115</pre>116 117<p>118In <a href="https://www.unicode.org/versions/Unicode8.0.0/">The Unicode Standard 8.0</a>,119Section 4.5 "General Category" defines a set of character categories.120Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo121as Unicode letters, and those in the Number category Nd as Unicode digits.122</p>123 124<h3 id="Letters_and_digits">Letters and digits</h3>125 126<p>127The underscore character <code>_</code> (U+005F) is considered a lowercase letter.128</p>129<pre class="ebnf">130letter = unicode_letter | "_" .131decimal_digit = "0" … "9" .132binary_digit = "0" | "1" .133octal_digit = "0" … "7" .134hex_digit = "0" … "9" | "A" … "F" | "a" … "f" .135</pre>136 137<h2 id="Lexical_elements">Lexical elements</h2>138 139<h3 id="Comments">Comments</h3>140 141<p>142Comments serve as program documentation. There are two forms:143</p>144 145<ol>146<li>147<i>Line comments</i> start with the character sequence <code>//</code>148and stop at the end of the line.149</li>150<li>151<i>General comments</i> start with the character sequence <code>/*</code>152and stop with the first subsequent character sequence <code>*/</code>.153</li>154</ol>155 156<p>157A comment cannot start inside a <a href="#Rune_literals">rune</a> or158<a href="#String_literals">string literal</a>, or inside a comment.159A general comment containing no newlines acts like a space.160Any other comment acts like a newline.161</p>162 163<h3 id="Tokens">Tokens</h3>164 165<p>166Tokens form the vocabulary of the Go language.167There are four classes: <i>identifiers</i>, <i>keywords</i>, <i>operators168and punctuation</i>, and <i>literals</i>. <i>White space</i>, formed from169spaces (U+0020), horizontal tabs (U+0009),170carriage returns (U+000D), and newlines (U+000A),171is ignored except as it separates tokens172that would otherwise combine into a single token. Also, a newline or end of file173may trigger the insertion of a <a href="#Semicolons">semicolon</a>.174While breaking the input into tokens,175the next token is the longest sequence of characters that form a176valid token.177</p>178 179<h3 id="Semicolons">Semicolons</h3>180 181<p>182The formal syntax uses semicolons <code>";"</code> as terminators in183a number of productions. Go programs may omit most of these semicolons184using the following two rules:185</p>186 187<ol>188<li>189When the input is broken into tokens, a semicolon is automatically inserted190into the token stream immediately after a line's final token if that token is191<ul>192 <li>an193 <a href="#Identifiers">identifier</a>194 </li>195 196 <li>an197 <a href="#Integer_literals">integer</a>,198 <a href="#Floating-point_literals">floating-point</a>,199 <a href="#Imaginary_literals">imaginary</a>,200 <a href="#Rune_literals">rune</a>, or201 <a href="#String_literals">string</a> literal202 </li>203 204 <li>one of the <a href="#Keywords">keywords</a>205 <code>break</code>,206 <code>continue</code>,207 <code>fallthrough</code>, or208 <code>return</code>209 </li>210 211 <li>one of the <a href="#Operators_and_punctuation">operators and punctuation</a>212 <code>++</code>,213 <code>--</code>,214 <code>)</code>,215 <code>]</code>, or216 <code>}</code>217 </li>218</ul>219</li>220 221<li>222To allow complex statements to occupy a single line, a semicolon223may be omitted before a closing <code>")"</code> or <code>"}"</code>.224</li>225</ol>226 227<p>228To reflect idiomatic use, code examples in this document elide semicolons229using these rules.230</p>231 232 233<h3 id="Identifiers">Identifiers</h3>234 235<p>236Identifiers name program entities such as variables and types.237An identifier is a sequence of one or more letters and digits.238The first character in an identifier must be a letter.239</p>240<pre class="ebnf">241identifier = letter { letter | unicode_digit } .242</pre>243<pre>244a245_x9246ThisVariableIsExported247αβ248</pre>249 250<p>251Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>.252</p>253 254 255<h3 id="Keywords">Keywords</h3>256 257<p>258The following keywords are reserved and may not be used as identifiers.259</p>260<pre class="grammar">261break default func interface select262case defer go map struct263chan else goto package switch264const fallthrough if range type265continue for import return var266</pre>267 268<h3 id="Operators_and_punctuation">Operators and punctuation</h3>269 270<p>271The following character sequences represent <a href="#Operators">operators</a>272(including <a href="#Assignment_statements">assignment operators</a>) and punctuation273[<a href="#Go_1.18">Go 1.18</a>]:274</p>275<pre class="grammar">276+ & += &= && == != ( )277- | -= |= || < <= [ ]278* ^ *= ^= <- > >= { }279/ << /= <<= ++ = := , ;280% >> %= >>= -- ! ... . :281 &^ &^= ~282</pre>283 284<h3 id="Integer_literals">Integer literals</h3>285 286<p>287An integer literal is a sequence of digits representing an288<a href="#Constants">integer constant</a>.289An optional prefix sets a non-decimal base: <code>0b</code> or <code>0B</code>290for binary, <code>0</code>, <code>0o</code>, or <code>0O</code> for octal,291and <code>0x</code> or <code>0X</code> for hexadecimal292[<a href="#Go_1.13">Go 1.13</a>].293A single <code>0</code> is considered a decimal zero.294In hexadecimal literals, letters <code>a</code> through <code>f</code>295and <code>A</code> through <code>F</code> represent values 10 through 15.296</p>297 298<p>299For readability, an underscore character <code>_</code> may appear after300a base prefix or between successive digits; such underscores do not change301the literal's value.302</p>303<pre class="ebnf">304int_lit = decimal_lit | binary_lit | octal_lit | hex_lit .305decimal_lit = "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] .306binary_lit = "0" ( "b" | "B" ) [ "_" ] binary_digits .307octal_lit = "0" [ "o" | "O" ] [ "_" ] octal_digits .308hex_lit = "0" ( "x" | "X" ) [ "_" ] hex_digits .309 310decimal_digits = decimal_digit { [ "_" ] decimal_digit } .311binary_digits = binary_digit { [ "_" ] binary_digit } .312octal_digits = octal_digit { [ "_" ] octal_digit } .313hex_digits = hex_digit { [ "_" ] hex_digit } .314</pre>315 316<pre>317423184_231906003200_6003210o6003220O600 // second character is capital letter 'O'3230xBadFace3240xBad_Face3250x_67_7a_2f_cc_40_c6326170141183460469231731687303715884105727327170_141183_460469_231731_687303_715884_105727328 329_42 // an identifier, not an integer literal33042_ // invalid: _ must separate successive digits3314__2 // invalid: only one _ at a time3320_xBadFace // invalid: _ must separate successive digits333</pre>334 335 336<h3 id="Floating-point_literals">Floating-point literals</h3>337 338<p>339A floating-point literal is a decimal or hexadecimal representation of a340<a href="#Constants">floating-point constant</a>.341</p>342 343<p>344A decimal floating-point literal consists of an integer part (decimal digits),345a decimal point, a fractional part (decimal digits), and an exponent part346(<code>e</code> or <code>E</code> followed by an optional sign and decimal digits).347One of the integer part or the fractional part may be elided; one of the decimal point348or the exponent part may be elided.349An exponent value exp scales the mantissa (integer and fractional part) by 10<sup>exp</sup>.350</p>351 352<p>353A hexadecimal floating-point literal consists of a <code>0x</code> or <code>0X</code>354prefix, an integer part (hexadecimal digits), a radix point, a fractional part (hexadecimal digits),355and an exponent part (<code>p</code> or <code>P</code> followed by an optional sign and decimal digits).356One of the integer part or the fractional part may be elided; the radix point may be elided as well,357but the exponent part is required. (This syntax matches the one given in IEEE 754-2008 §5.12.3.)358An exponent value exp scales the mantissa (integer and fractional part) by 2<sup>exp</sup>359[<a href="#Go_1.13">Go 1.13</a>].360</p>361 362<p>363For readability, an underscore character <code>_</code> may appear after364a base prefix or between successive digits; such underscores do not change365the literal value.366</p>367 368<pre class="ebnf">369float_lit = decimal_float_lit | hex_float_lit .370 371decimal_float_lit = decimal_digits "." [ decimal_digits ] [ decimal_exponent ] |372 decimal_digits decimal_exponent |373 "." decimal_digits [ decimal_exponent ] .374decimal_exponent = ( "e" | "E" ) [ "+" | "-" ] decimal_digits .375 376hex_float_lit = "0" ( "x" | "X" ) hex_mantissa hex_exponent .377hex_mantissa = [ "_" ] hex_digits "." [ hex_digits ] |378 [ "_" ] hex_digits |379 "." hex_digits .380hex_exponent = ( "p" | "P" ) [ "+" | "-" ] decimal_digits .381</pre>382 383<pre>3840.38572.40386072.40 // == 72.403872.718283881.e+03896.67428e-113901E6391.25392.12345E+53931_5. // == 15.03940.15e+0_2 // == 15.0395 3960x1p-2 // == 0.253970x2.p10 // == 2048.03980x1.Fp+0 // == 1.93753990X.8p-0 // == 0.54000X_1FFFP-16 // == 0.12498474121093754010x15e-2 // == 0x15e - 2 (integer subtraction)402 4030x.p1 // invalid: mantissa has no digits4041p-2 // invalid: p exponent requires hexadecimal mantissa4050x1.5e-2 // invalid: hexadecimal mantissa requires p exponent4061_.5 // invalid: _ must separate successive digits4071._5 // invalid: _ must separate successive digits4081.5_e1 // invalid: _ must separate successive digits4091.5e_1 // invalid: _ must separate successive digits4101.5e1_ // invalid: _ must separate successive digits411</pre>412 413 414<h3 id="Imaginary_literals">Imaginary literals</h3>415 416<p>417An imaginary literal represents the imaginary part of a418<a href="#Constants">complex constant</a>.419It consists of an <a href="#Integer_literals">integer</a> or420<a href="#Floating-point_literals">floating-point</a> literal421followed by the lowercase letter <code>i</code>.422The value of an imaginary literal is the value of the respective423integer or floating-point literal multiplied by the imaginary unit <i>i</i>424[<a href="#Go_1.13">Go 1.13</a>]425</p>426 427<pre class="ebnf">428imaginary_lit = (decimal_digits | int_lit | float_lit) "i" .429</pre>430 431<p>432For backward compatibility, an imaginary literal's integer part consisting433entirely of decimal digits (and possibly underscores) is considered a decimal434integer, even if it starts with a leading <code>0</code>.435</p>436 437<pre>4380i4390123i // == 123i for backward-compatibility4400o123i // == 0o123 * 1i == 83i4410xabci // == 0xabc * 1i == 2748i4420.i4432.71828i4441.e+0i4456.67428e-11i4461E6i447.25i448.12345E+5i4490x1p-2i // == 0x1p-2 * 1i == 0.25i450</pre>451 452 453<h3 id="Rune_literals">Rune literals</h3>454 455<p>456A rune literal represents a <a href="#Constants">rune constant</a>,457an integer value identifying a Unicode code point.458A rune literal is expressed as one or more characters enclosed in single quotes,459as in <code>'x'</code> or <code>'\n'</code>.460Within the quotes, any character may appear except newline and unescaped single461quote. A single quoted character represents the Unicode value462of the character itself,463while multi-character sequences beginning with a backslash encode464values in various formats.465</p>466 467<p>468The simplest form represents the single character within the quotes;469since Go source text is Unicode characters encoded in UTF-8, multiple470UTF-8-encoded bytes may represent a single integer value. For471instance, the literal <code>'a'</code> holds a single byte representing472a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while473<code>'ä'</code> holds two bytes (<code>0xc3</code> <code>0xa4</code>) representing474a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>.475</p>476 477<p>478Several backslash escapes allow arbitrary values to be encoded as479ASCII text. There are four ways to represent the integer value480as a numeric constant: <code>\x</code> followed by exactly two hexadecimal481digits; <code>\u</code> followed by exactly four hexadecimal digits;482<code>\U</code> followed by exactly eight hexadecimal digits, and a483plain backslash <code>\</code> followed by exactly three octal digits.484In each case the value of the literal is the value represented by485the digits in the corresponding base.486</p>487 488<p>489Although these representations all result in an integer, they have490different valid ranges. Octal escapes must represent a value between4910 and 255 inclusive. Hexadecimal escapes satisfy this condition492by construction. The escapes <code>\u</code> and <code>\U</code>493represent Unicode code points so within them some values are illegal,494in particular those above <code>0x10FFFF</code> and surrogate halves.495</p>496 497<p>498After a backslash, certain single-character escapes represent special values:499</p>500 501<pre class="grammar">502\a U+0007 alert or bell503\b U+0008 backspace504\f U+000C form feed505\n U+000A line feed or newline506\r U+000D carriage return507\t U+0009 horizontal tab508\v U+000B vertical tab509\\ U+005C backslash510\' U+0027 single quote (valid escape only within rune literals)511\" U+0022 double quote (valid escape only within string literals)512</pre>513 514<p>515An unrecognized character following a backslash in a rune literal is illegal.516</p>517 518<pre class="ebnf">519rune_lit = "'" ( unicode_value | byte_value ) "'" .520unicode_value = unicode_char | little_u_value | big_u_value | escaped_char .521byte_value = octal_byte_value | hex_byte_value .522octal_byte_value = `\` octal_digit octal_digit octal_digit .523hex_byte_value = `\` "x" hex_digit hex_digit .524little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit .525big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit526 hex_digit hex_digit hex_digit hex_digit .527escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .528</pre>529 530<pre>531'a'532'ä'533'本'534'\t'535'\000'536'\007'537'\377'538'\x07'539'\xff'540'\u12e4'541'\U00101234'542'\'' // rune literal containing single quote character543'aa' // illegal: too many characters544'\k' // illegal: k is not recognized after a backslash545'\xa' // illegal: too few hexadecimal digits546'\0' // illegal: too few octal digits547'\400' // illegal: octal value over 255548'\uDFFF' // illegal: surrogate half549'\U00110000' // illegal: invalid Unicode code point550</pre>551 552 553<h3 id="String_literals">String literals</h3>554 555<p>556A string literal represents a <a href="#Constants">string constant</a>557obtained from concatenating a sequence of characters. There are two forms:558raw string literals and interpreted string literals.559</p>560 561<p>562Raw string literals are character sequences between back quotes, as in563<code>`foo`</code>. Within the quotes, any character may appear except564back quote. The value of a raw string literal is the565string composed of the uninterpreted (implicitly UTF-8-encoded) characters566between the quotes;567in particular, backslashes have no special meaning and the string may568contain newlines.569Carriage return characters ('\r') inside raw string literals570are discarded from the raw string value.571</p>572 573<p>574Interpreted string literals are character sequences between double575quotes, as in <code>"bar"</code>.576Within the quotes, any character may appear except newline and unescaped double quote.577The text between the quotes forms the578value of the literal, with backslash escapes interpreted as they579are in <a href="#Rune_literals">rune literals</a> (except that <code>\'</code> is illegal and580<code>\"</code> is legal), with the same restrictions.581The three-digit octal (<code>\</code><i>nnn</i>)582and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual583<i>bytes</i> of the resulting string; all other escapes represent584the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.585Thus inside a string literal <code>\377</code> and <code>\xFF</code> represent586a single byte of value <code>0xFF</code>=255, while <code>ÿ</code>,587<code>\u00FF</code>, <code>\U000000FF</code> and <code>\xc3\xbf</code> represent588the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character589U+00FF.590</p>591 592<pre class="ebnf">593string_lit = raw_string_lit | interpreted_string_lit .594raw_string_lit = "`" { unicode_char | newline } "`" .595interpreted_string_lit = `"` { unicode_value | byte_value } `"` .596</pre>597 598<pre>599`abc` // same as "abc"600`\n601\n` // same as "\\n\n\\n"602"\n"603"\"" // same as `"`604"Hello, world!\n"605"日本語"606"\u65e5本\U00008a9e"607"\xff\u00FF"608"\uD800" // illegal: surrogate half609"\U00110000" // illegal: invalid Unicode code point610</pre>611 612<p>613These examples all represent the same string:614</p>615 616<pre>617"日本語" // UTF-8 input text618`日本語` // UTF-8 input text as a raw literal619"\u65e5\u672c\u8a9e" // the explicit Unicode code points620"\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points621"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes622</pre>623 624<p>625If the source code represents a character as two code points, such as626a combining form involving an accent and a letter, the result will be627an error if placed in a rune literal (it is not a single code628point), and will appear as two code points if placed in a string629literal.630</p>631 632 633<h2 id="Constants">Constants</h2>634 635<p>There are <i>boolean constants</i>,636<i>rune constants</i>,637<i>integer constants</i>,638<i>floating-point constants</i>, <i>complex constants</i>,639and <i>string constants</i>. Rune, integer, floating-point,640and complex constants are641collectively called <i>numeric constants</i>.642</p>643 644<p>645A constant value is represented by a646<a href="#Rune_literals">rune</a>,647<a href="#Integer_literals">integer</a>,648<a href="#Floating-point_literals">floating-point</a>,649<a href="#Imaginary_literals">imaginary</a>,650or651<a href="#String_literals">string</a> literal,652an identifier denoting a constant,653a <a href="#Constant_expressions">constant expression</a>,654a <a href="#Conversions">conversion</a> with a result that is a constant, or655the result value of some built-in functions such as656<code>min</code> or <code>max</code> applied to constant arguments,657<code>unsafe.Sizeof</code> applied to <a href="#Package_unsafe">certain values</a>,658<code>cap</code> or <code>len</code> applied to659<a href="#Length_and_capacity">some expressions</a>,660<code>real</code> and <code>imag</code> applied to a complex constant661and <code>complex</code> applied to numeric constants.662The boolean truth values are represented by the predeclared constants663<code>true</code> and <code>false</code>. The predeclared identifier664<a href="#Iota">iota</a> denotes an integer constant.665</p>666 667<p>668In general, complex constants are a form of669<a href="#Constant_expressions">constant expression</a>670and are discussed in that section.671</p>672 673<p>674Numeric constants represent exact values of arbitrary precision and do not overflow.675Consequently, there are no constants denoting the IEEE 754 negative zero, infinity,676and not-a-number values.677</p>678 679<p>680Constants may be <a href="#Types">typed</a> or <i>untyped</i>.681Literal constants, <code>true</code>, <code>false</code>, <code>iota</code>,682and certain <a href="#Constant_expressions">constant expressions</a>683containing only untyped constant operands are untyped.684</p>685 686<p>687A constant may be given a type explicitly by a <a href="#Constant_declarations">constant declaration</a>688or <a href="#Conversions">conversion</a>, or implicitly when used in a689<a href="#Variable_declarations">variable declaration</a> or an690<a href="#Assignment_statements">assignment statement</a> or as an691operand in an <a href="#Expressions">expression</a>.692It is an error if the constant value693cannot be <a href="#Representability">represented</a> as a value of the respective type.694If the type is a type parameter, the constant is converted into a non-constant695value of the type parameter.696</p>697 698<p>699An untyped constant has a <i>default type</i> which is the type to which the700constant is implicitly converted in contexts where a typed value is required,701for instance, in a <a href="#Short_variable_declarations">short variable declaration</a>702such as <code>i := 0</code> where there is no explicit type.703The default type of an untyped constant is <code>bool</code>, <code>rune</code>,704<code>int</code>, <code>float64</code>, <code>complex128</code>, or <code>string</code>705respectively, depending on whether it is a boolean, rune, integer, floating-point,706complex, or string constant.707</p>708 709<p>710Implementation restriction: Although numeric constants have arbitrary711precision in the language, a compiler may implement them using an712internal representation with limited precision. That said, every713implementation must:714</p>715 716<ul>717 <li>Represent integer constants with at least 256 bits.</li>718 719 <li>Represent floating-point constants, including the parts of720 a complex constant, with a mantissa of at least 256 bits721 and a signed binary exponent of at least 16 bits.</li>722 723 <li>Give an error if unable to represent an integer constant724 precisely.</li>725 726 <li>Give an error if unable to represent a floating-point or727 complex constant due to overflow.</li>728 729 <li>Round to the nearest representable constant if unable to730 represent a floating-point or complex constant due to limits731 on precision.</li>732</ul>733 734<p>735These requirements apply both to literal constants and to the result736of evaluating <a href="#Constant_expressions">constant737expressions</a>.738</p>739 740 741<h2 id="Variables">Variables</h2>742 743<p>744A variable is a storage location for holding a <i>value</i>.745The set of permissible values is determined by the746variable's <i><a href="#Types">type</a></i>.747</p>748 749<p>750A <a href="#Variable_declarations">variable declaration</a>751or, for function parameters and results, the signature752of a <a href="#Function_declarations">function declaration</a>753or <a href="#Function_literals">function literal</a> reserves754storage for a named variable.755 756Calling the built-in function <a href="#Allocation"><code>new</code></a>757or taking the address of a <a href="#Composite_literals">composite literal</a>758allocates storage for a variable at run time.759Such an anonymous variable is referred to via a (possibly implicit)760<a href="#Address_operators">pointer indirection</a>.761</p>762 763<p>764<i>Structured</i> variables of <a href="#Array_types">array</a>, <a href="#Slice_types">slice</a>,765and <a href="#Struct_types">struct</a> types have elements and fields that may766be <a href="#Address_operators">addressed</a> individually. Each such element767acts like a variable.768</p>769 770<p>771The <i>static type</i> (or just <i>type</i>) of a variable is the772type given in its declaration, the type provided in the773<code>new</code> call or composite literal, or the type of774an element of a structured variable.775Variables of interface type also have a distinct <i>dynamic type</i>,776which is the (non-interface) type of the value assigned to the variable at run time777(unless the value is the predeclared identifier <code>nil</code>,778which has no type).779The dynamic type may vary during execution but values stored in interface780variables are always <a href="#Assignability">assignable</a>781to the static type of the variable.782</p>783 784<pre>785var x interface{} // x is nil and has static type interface{}786var v *T // v has value nil, static type *T787x = 42 // x has value 42 and dynamic type int788x = v // x has value (*T)(nil) and dynamic type *T789</pre>790 791<p>792A variable's value is retrieved by referring to the variable in an793<a href="#Expressions">expression</a>; it is the most recent value794<a href="#Assignment_statements">assigned</a> to the variable.795If a variable has not yet been assigned a value, its value is the796<a href="#The_zero_value">zero value</a> for its type.797</p>798 799<h2 id="Types">Types</h2>800 801<p>802A type determines a set of values together with operations and methods specific803to those values. A type may be denoted by a <i>type name</i>, if it has one, which must be804followed by <a href="#Instantiations">type arguments</a> if the type is generic.805A type may also be specified using a <i>type literal</i>, which composes a type806from existing types.807</p>808 809<pre class="ebnf">810Type = TypeName [ TypeArgs ] | TypeLit | "(" Type ")" .811TypeName = identifier | QualifiedIdent .812TypeArgs = "[" TypeList [ "," ] "]" .813TypeList = Type { "," Type } .814TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |815 SliceType | MapType | ChannelType .816</pre>817 818<p>819The language <a href="#Predeclared_identifiers">predeclares</a> certain type names.820Others are introduced with <a href="#Type_declarations">type declarations</a>821or <a href="#Type_parameter_declarations">type parameter lists</a>.822<i>Composite types</i>—array, struct, pointer, function,823interface, slice, map, and channel types—may be constructed using824type literals.825</p>826 827<p>828Predeclared types, defined types, and type parameters are called <i>named types</i>.829An alias denotes a named type if the type given in the alias declaration is a named type.830</p>831 832<h3 id="Boolean_types">Boolean types</h3>833 834<p>835A <i>boolean type</i> represents the set of Boolean truth values836denoted by the predeclared constants <code>true</code>837and <code>false</code>. The predeclared boolean type is <code>bool</code>;838it is a <a href="#Type_definitions">defined type</a>.839</p>840 841<h3 id="Numeric_types">Numeric types</h3>842 843<p>844An <i>integer</i>, <i>floating-point</i>, or <i>complex</i> type845represents the set of integer, floating-point, or complex values, respectively.846They are collectively called <i>numeric types</i>.847The predeclared architecture-independent numeric types are:848</p>849 850<pre class="grammar">851uint8 the set of all unsigned 8-bit integers (0 to 255)852uint16 the set of all unsigned 16-bit integers (0 to 65535)853uint32 the set of all unsigned 32-bit integers (0 to 4294967295)854uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)855 856int8 the set of all signed 8-bit integers (-128 to 127)857int16 the set of all signed 16-bit integers (-32768 to 32767)858int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)859int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)860 861float32 the set of all IEEE 754 32-bit floating-point numbers862float64 the set of all IEEE 754 64-bit floating-point numbers863 864complex64 the set of all complex numbers with float32 real and imaginary parts865complex128 the set of all complex numbers with float64 real and imaginary parts866 867byte alias for uint8868rune alias for int32869</pre>870 871<p>872The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using873<a href="https://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>.874</p>875 876<p>877There is also a set of predeclared integer types with implementation-specific sizes:878</p>879 880<pre class="grammar">881uint either 32 or 64 bits882int same size as uint883uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value884</pre>885 886<p>887To avoid portability issues all numeric types are <a href="#Type_definitions">defined888types</a> and thus distinct except889<code>byte</code>, which is an <a href="#Alias_declarations">alias</a> for <code>uint8</code>, and890<code>rune</code>, which is an alias for <code>int32</code>.891Explicit conversions892are required when different numeric types are mixed in an expression893or assignment. For instance, <code>int32</code> and <code>int</code>894are not the same type even though they may have the same size on a895particular architecture.896</p>897 898<h3 id="String_types">String types</h3>899 900<p>901A <i>string type</i> represents the set of string values.902A string value is a (possibly empty) sequence of bytes.903The number of bytes is called the length of the string and is never negative.904Strings are immutable: once created,905it is impossible to change the contents of a string.906The predeclared string type is <code>string</code>;907it is a <a href="#Type_definitions">defined type</a>.908</p>909 910<p>911The length of a string <code>s</code> can be discovered using912the built-in function <a href="#Length_and_capacity"><code>len</code></a>.913The length is a compile-time constant if the string is a constant.914A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>9150 through <code>len(s)-1</code>.916It is illegal to take the address of such an element; if917<code>s[i]</code> is the <code>i</code>'th byte of a918string, <code>&s[i]</code> is invalid.919</p>920 921 922<h3 id="Array_types">Array types</h3>923 924<p>925An array is a numbered sequence of elements of a single926type, called the element type.927The number of elements is called the length of the array and is never negative.928</p>929 930<pre class="ebnf">931ArrayType = "[" ArrayLength "]" ElementType .932ArrayLength = Expression .933ElementType = Type .934</pre>935 936<p>937The length is part of the array's type; it must evaluate to a938non-negative <a href="#Constants">constant</a>939<a href="#Representability">representable</a> by a value940of type <code>int</code>.941The length of array <code>a</code> can be discovered942using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.943The elements can be addressed by integer <a href="#Index_expressions">indices</a>9440 through <code>len(a)-1</code>.945Array types are always one-dimensional but may be composed to form946multi-dimensional types.947</p>948 949<pre>950[32]byte951[2*N] struct { x, y int32 }952[1000]*float64953[3][5]int954[2][2][2]float64 // same as [2]([2]([2]float64))955</pre>956 957<p>958An array type <code>T</code> may not have an element of type <code>T</code>,959or of a type containing <code>T</code> as a component, directly or indirectly,960if those containing types are only array or struct types.961</p>962 963<pre>964// invalid array types965type (966 T1 [10]T1 // element type of T1 is T1967 T2 [10]struct{ f T2 } // T2 contains T2 as component of a struct968 T3 [10]T4 // T3 contains T3 as component of a struct in T4969 T4 struct{ f T3 } // T4 contains T4 as component of array T3 in a struct970)971 972// valid array types973type (974 T5 [10]*T5 // T5 contains T5 as component of a pointer975 T6 [10]func() T6 // T6 contains T6 as component of a function type976 T7 [10]struct{ f []T7 } // T7 contains T7 as component of a slice in a struct977)978</pre>979 980<h3 id="Slice_types">Slice types</h3>981 982<p>983A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and984provides access to a numbered sequence of elements from that array.985A slice type denotes the set of all slices of arrays of its element type.986The number of elements is called the length of the slice and is never negative.987The value of an uninitialized slice is <code>nil</code>.988</p>989 990<pre class="ebnf">991SliceType = "[" "]" ElementType .992</pre>993 994<p>995The length of a slice <code>s</code> can be discovered by the built-in function996<a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during997execution. The elements can be addressed by integer <a href="#Index_expressions">indices</a>9980 through <code>len(s)-1</code>. The slice index of a999given element may be less than the index of the same element in the1000underlying array.1001</p>1002<p>1003A slice, once initialized, is always associated with an underlying1004array that holds its elements. A slice therefore shares storage1005with its array and with other slices of the same array; by contrast,1006distinct arrays always represent distinct storage.1007</p>1008<p>1009The array underlying a slice may extend past the end of the slice.1010The <i>capacity</i> is a measure of that extent: it is the sum of1011the length of the slice and the length of the array beyond the slice;1012a slice of length up to that capacity can be created by1013<a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice.1014The capacity of a slice <code>a</code> can be discovered using the1015built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.1016</p>1017 1018<p>1019A new, initialized slice value for a given element type <code>T</code> may be1020made using the built-in function1021<a href="#Making_slices_maps_and_channels"><code>make</code></a>,1022which takes a slice type1023and parameters specifying the length and optionally the capacity.1024A slice created with <code>make</code> always allocates a new, hidden array1025to which the returned slice value refers. That is, executing1026</p>1027 1028<pre>1029make([]T, length, capacity)1030</pre>1031 1032<p>1033produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a>1034it, so these two expressions are equivalent:1035</p>1036 1037<pre>1038make([]int, 50, 100)1039new([100]int)[0:50]1040</pre>1041 1042<p>1043Like arrays, slices are always one-dimensional but may be composed to construct1044higher-dimensional objects.1045With arrays of arrays, the inner arrays are, by construction, always the same length;1046however with slices of slices (or arrays of slices), the inner lengths may vary dynamically.1047Moreover, the inner slices must be initialized individually.1048</p>1049 1050<h3 id="Struct_types">Struct types</h3>1051 1052<p>1053A struct is a sequence of named elements, called fields, each of which has a1054name and a type. Field names may be specified explicitly (IdentifierList) or1055implicitly (EmbeddedField).1056Within a struct, non-<a href="#Blank_identifier">blank</a> field names must1057be <a href="#Uniqueness_of_identifiers">unique</a>.1058</p>1059 1060<pre class="ebnf">1061StructType = "struct" "{" { FieldDecl ";" } "}" .1062FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] .1063EmbeddedField = [ "*" ] TypeName [ TypeArgs ] .1064Tag = string_lit .1065</pre>1066 1067<pre>1068// An empty struct.1069struct {}1070 1071// A struct with 6 fields.1072struct {1073 x, y int1074 u float321075 _ float32 // padding1076 A *[]int1077 F func()1078}1079</pre>1080 1081<p>1082A field declared with a type but no explicit field name is called an <i>embedded field</i>.1083An embedded field must be specified as1084a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>,1085and <code>T</code> itself may not be1086a pointer type or type parameter. The unqualified type name acts as the field name.1087</p>1088 1089<pre>1090// A struct with four embedded fields of types T1, *T2, P.T3 and *P.T41091struct {1092 T1 // field name is T11093 *T2 // field name is T21094 P.T3 // field name is T31095 *P.T4 // field name is T41096 x, y int // field names are x and y1097}1098</pre>1099 1100<p>1101The following declaration is illegal because field names must be unique1102in a struct type:1103</p>1104 1105<pre>1106struct {1107 T // conflicts with embedded field *T and *P.T1108 *T // conflicts with embedded field T and *P.T1109 *P.T // conflicts with embedded field T and *T1110}1111</pre>1112 1113<p>1114A field or <a href="#Method_declarations">method</a> <code>f</code> of an1115embedded field in a struct <code>x</code> is called <i>promoted</i> if1116<code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes1117that field or method <code>f</code>.1118</p>1119 1120<p>1121Promoted fields act like ordinary fields1122of a struct except that they cannot be used as field names in1123<a href="#Composite_literals">composite literals</a> of the struct.1124</p>1125 1126<p>1127Given a struct type <code>S</code> and a type name1128<code>T</code>, promoted methods are included in the method set of the struct as follows:1129</p>1130<ul>1131 <li>1132 If <code>S</code> contains an embedded field <code>T</code>,1133 the <a href="#Method_sets">method sets</a> of <code>S</code>1134 and <code>*S</code> both include promoted methods with receiver1135 <code>T</code>. The method set of <code>*S</code> also1136 includes promoted methods with receiver <code>*T</code>.1137 </li>1138 1139 <li>1140 If <code>S</code> contains an embedded field <code>*T</code>,1141 the method sets of <code>S</code> and <code>*S</code> both1142 include promoted methods with receiver <code>T</code> or1143 <code>*T</code>.1144 </li>1145</ul>1146 1147<p>1148A field declaration may be followed by an optional string literal <i>tag</i>,1149which becomes an attribute for all the fields in the corresponding1150field declaration. An empty tag string is equivalent to an absent tag.1151The tags are made visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a>1152and take part in <a href="#Type_identity">type identity</a> for structs1153but are otherwise ignored.1154</p>1155 1156<pre>1157struct {1158 x, y float64 "" // an empty tag string is like an absent tag1159 name string "any string is permitted as a tag"1160 _ [4]byte "ceci n'est pas un champ de structure"1161}1162 1163// A struct corresponding to a TimeStamp protocol buffer.1164// The tag strings define the protocol buffer field numbers;1165// they follow the convention outlined by the reflect package.1166struct {1167 microsec uint64 `protobuf:"1"`1168 serverIP6 uint64 `protobuf:"2"`1169}1170</pre>1171 1172<p>1173A struct type <code>T</code> may not contain a field of type <code>T</code>,1174or of a type containing <code>T</code> as a component, directly or indirectly,1175if those containing types are only array or struct types.1176</p>1177 1178<pre>1179// invalid struct types1180type (1181 T1 struct{ T1 } // T1 contains a field of T11182 T2 struct{ f [10]T2 } // T2 contains T2 as component of an array1183 T3 struct{ T4 } // T3 contains T3 as component of an array in struct T41184 T4 struct{ f [10]T3 } // T4 contains T4 as component of struct T3 in an array1185)1186 1187// valid struct types1188type (1189 T5 struct{ f *T5 } // T5 contains T5 as component of a pointer1190 T6 struct{ f func() T6 } // T6 contains T6 as component of a function type1191 T7 struct{ f [10][]T7 } // T7 contains T7 as component of a slice in an array1192)1193</pre>1194 1195<h3 id="Pointer_types">Pointer types</h3>1196 1197<p>1198A pointer type denotes the set of all pointers to <a href="#Variables">variables</a> of a given1199type, called the <i>base type</i> of the pointer.1200The <a href="#Representation_of_values">value</a> of an uninitialized pointer is <code>nil</code>.