1<!--{2 "Title": "The Go Programming Language Specification",3 "Subtitle": "Language version go1.27 (May 26, 2026)",4 "Path": "/ref/spec"5}-->67<h2 id="Introduction">Introduction</h2>89<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>1314<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>2122<p>23The syntax is compact and simple to parse, allowing for easy analysis24by automatic tools such as integrated development environments.25</p>2627<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>3334<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>4445<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>5556<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>6162<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>7071<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>7879<h2 id="Source_code_representation">Source code representation</h2>8081<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>104105<h3 id="Characters">Characters</h3>106107<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>116117<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>123124<h3 id="Letters_and_digits">Letters and digits</h3>125126<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>136137<h2 id="Lexical_elements">Lexical elements</h2>138139<h3 id="Comments">Comments</h3>140141<p>142Comments serve as program documentation. There are two forms:143</p>144145<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>155156<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>162163<h3 id="Tokens">Tokens</h3>164165<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>178179<h3 id="Semicolons">Semicolons</h3>180181<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>186187<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>195196 <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>203204 <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>210211 <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>220221<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>226227<p>228To reflect idiomatic use, code examples in this document elide semicolons229using these rules.230</p>231232233<h3 id="Identifiers">Identifiers</h3>234235<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>249250<p>251Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>.252</p>253254255<h3 id="Keywords">Keywords</h3>256257<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>267268<h3 id="Operators_and_punctuation">Operators and punctuation</h3>269270<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>283284<h3 id="Integer_literals">Integer literals</h3>285286<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>297298<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 .309310decimal_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>315316<pre>317423184_231906003200_6003210o6003220O600 // second character is capital letter 'O'3230xBadFace3240xBad_Face3250x_67_7a_2f_cc_40_c6326170141183460469231731687303715884105727327170_141183_460469_231731_687303_715884_105727328329_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>334335336<h3 id="Floating-point_literals">Floating-point literals</h3>337338<p>339A floating-point literal is a decimal or hexadecimal representation of a340<a href="#Constants">floating-point constant</a>.341</p>342343<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>351352<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>361362<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>367368<pre class="ebnf">369float_lit = decimal_float_lit | hex_float_lit .370371decimal_float_lit = decimal_digits "." [ decimal_digits ] [ decimal_exponent ] |372 decimal_digits decimal_exponent |373 "." decimal_digits [ decimal_exponent ] .374decimal_exponent = ( "e" | "E" ) [ "+" | "-" ] decimal_digits .375376hex_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>382383<pre>3840.38572.40386072.40 // == 72.403872.718283881.e+03896.67428e-113901E6391.25392.12345E+53931_5. // == 15.03940.15e+0_2 // == 15.03953960x1p-2 // == 0.253970x2.p10 // == 2048.03980x1.Fp+0 // == 1.93753990X.8p-0 // == 0.54000X_1FFFP-16 // == 0.12498474121093754010x15e-2 // == 0x15e - 2 (integer subtraction)4024030x.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>412413414<h3 id="Imaginary_literals">Imaginary literals</h3>415416<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>426427<pre class="ebnf">428imaginary_lit = (decimal_digits | int_lit | float_lit) "i" .429</pre>430431<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>436437<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>451452453<h3 id="Rune_literals">Rune literals</h3>454455<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>466467<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>476477<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>487488<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>496497<p>498After a backslash, certain single-character escapes represent special values:499</p>500501<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>513514<p>515An unrecognized character following a backslash in a rune literal is illegal.516</p>517518<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>529530<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>551552553<h3 id="String_literals">String literals</h3>554555<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>560561<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>572573<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>591592<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>597598<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>611612<p>613These examples all represent the same string:614</p>615616<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>623624<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>631632633<h2 id="Constants">Constants</h2>634635<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>643644<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>666667<p>668In general, complex constants are a form of669<a href="#Constant_expressions">constant expression</a>670and are discussed in that section.671</p>672673<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>678679<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>685686<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>697698<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>708709<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>715716<ul>717 <li>Represent integer constants with at least 256 bits.</li>718719 <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>722723 <li>Give an error if unable to represent an integer constant724 precisely.</li>725726 <li>Give an error if unable to represent a floating-point or727 complex constant due to overflow.</li>728729 <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>733734<p>735These requirements apply both to literal constants and to the result736of evaluating <a href="#Constant_expressions">constant737expressions</a>.738</p>739740741<h2 id="Variables">Variables</h2>742743<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>748749<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.755756Calling 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>762763<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>769770<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>783784<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>790791<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>798799<h2 id="Types">Types</h2>800801<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>808809<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>817818<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>826827<p>828<a href="#Predeclared_identifiers">Predeclared</a> types (excluding <code>any</code>),829<a href="#Type_definitions">defined types</a>, and830<a href="#Type_parameter_declarations">type parameters</a> are called <i>named types</i>.831An <a href="#Alias_declarations">alias</a> denotes a named type if the type given in the alias declaration is a named type.832All named types are <a href="#Type_identity">distinct</a>.833</p>834835<h3 id="Boolean_types">Boolean types</h3>836837<p>838A <i>boolean type</i> represents the set of Boolean truth values839denoted by the predeclared constants <code>true</code>840and <code>false</code>. The predeclared boolean type is <code>bool</code>;841it is a <a href="#Types">named type</a>.842</p>843844<h3 id="Numeric_types">Numeric types</h3>845846<p>847An <i>integer</i>, <i>floating-point</i>, or <i>complex</i> type848represents the set of integer, floating-point, or complex values, respectively.849They are collectively called <i>numeric types</i>.850The predeclared architecture-independent numeric types are:851</p>852853<pre class="grammar">854uint8 the set of all unsigned 8-bit integers (0 to 255)855uint16 the set of all unsigned 16-bit integers (0 to 65535)856uint32 the set of all unsigned 32-bit integers (0 to 4294967295)857uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)858859int8 the set of all signed 8-bit integers (-128 to 127)860int16 the set of all signed 16-bit integers (-32768 to 32767)861int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)862int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)863864float32 the set of all IEEE 754 32-bit floating-point numbers865float64 the set of all IEEE 754 64-bit floating-point numbers866867complex64 the set of all complex numbers with float32 real and imaginary parts868complex128 the set of all complex numbers with float64 real and imaginary parts869870byte alias for uint8871rune alias for int32872</pre>873874<p>875The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using876<a href="https://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>.877</p>878879<p>880There is also a set of predeclared integer types with implementation-specific sizes:881</p>882883<pre class="grammar">884uint either 32 or 64 bits885int same size as uint886uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value887</pre>888889<p>890To avoid portability issues all numeric types are <a href="#Types">named types</a> and thus distinct except891<code>byte</code>, which is an <a href="#Alias_declarations">alias</a> for <code>uint8</code>, and892<code>rune</code>, which is an alias for <code>int32</code>.893Explicit conversions894are required when different numeric types are mixed in an expression895or assignment. For instance, <code>int32</code> and <code>int</code>896are not the same type even though they may have the same size on a897particular architecture.898</p>899900<h3 id="String_types">String types</h3>901902<p>903A <i>string type</i> represents the set of string values.904A string value is a (possibly empty) sequence of bytes.905The number of bytes is called the length of the string and is never negative.906Strings are immutable: once created,907it is impossible to change the contents of a string.908The predeclared string type is <code>string</code>;909it is a <a href="#Types">named type</a>.910</p>911912<p>913The length of a string <code>s</code> can be discovered using914the built-in function <a href="#Length_and_capacity"><code>len</code></a>.915The length is a compile-time constant if the string is a constant.916A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>9170 through <code>len(s)-1</code>.918It is illegal to take the address of such an element; if919<code>s[i]</code> is the <code>i</code>'th byte of a920string, <code>&s[i]</code> is invalid.921</p>922923924<h3 id="Array_types">Array types</h3>925926<p>927An array is a numbered sequence of elements of a single928type, called the element type.929The number of elements is called the length of the array and is never negative.930</p>931932<pre class="ebnf">933ArrayType = "[" ArrayLength "]" ElementType .934ArrayLength = Expression .935ElementType = Type .936</pre>937938<p>939The length is part of the array's type; it must evaluate to a940non-negative <a href="#Constants">constant</a>941<a href="#Representability">representable</a> by a value942of type <code>int</code>.943The length of array <code>a</code> can be discovered944using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.945The elements can be addressed by integer <a href="#Index_expressions">indices</a>9460 through <code>len(a)-1</code>.947Array types are always one-dimensional but may be composed to form948multi-dimensional types.949</p>950951<pre>952[32]byte953[2*N] struct { x, y int32 }954[1000]*float64955[3][5]int956[2][2][2]float64 // same as [2]([2]([2]float64))957</pre>958959<p>960An array type <code>T</code> may not have an element of type <code>T</code>,961or of a type containing <code>T</code> as a component, directly or indirectly,962if those containing types are only array or struct types.963</p>964965<pre>966// invalid array types967type (968 T1 [10]T1 // element type of T1 is T1969 T2 [10]struct{ f T2 } // T2 contains T2 as component of a struct970 T3 [10]T4 // T3 contains T3 as component of a struct in T4971 T4 struct{ f T3 } // T4 contains T4 as component of array T3 in a struct972)973974// valid array types975type (976 T5 [10]*T5 // T5 contains T5 as component of a pointer977 T6 [10]func() T6 // T6 contains T6 as component of a function type978 T7 [10]struct{ f []T7 } // T7 contains T7 as component of a slice in a struct979)980</pre>981982<h3 id="Slice_types">Slice types</h3>983984<p>985A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and986provides access to a numbered sequence of elements from that array.987A slice type denotes the set of all slices of arrays of its element type.988The number of elements is called the length of the slice and is never negative.989The value of an uninitialized slice is <code>nil</code>.990</p>991992<pre class="ebnf">993SliceType = "[" "]" ElementType .994</pre>995996<p>997The length of a slice <code>s</code> can be discovered by the built-in function998<a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during999execution. The elements can be addressed by integer <a href="#Index_expressions">indices</a>10000 through <code>len(s)-1</code>. The slice index of a1001given element may be less than the index of the same element in the1002underlying array.1003</p>1004<p>1005A slice, once initialized, is always associated with an underlying1006array that holds its elements. A slice therefore shares storage1007with its array and with other slices of the same array; by contrast,1008distinct arrays always represent distinct storage.1009</p>1010<p>1011The array underlying a slice may extend past the end of the slice.1012The <i>capacity</i> is a measure of that extent: it is the sum of1013the length of the slice and the length of the array beyond the slice;1014a slice of length up to that capacity can be created by1015<a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice.1016The capacity of a slice <code>a</code> can be discovered using the1017built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.1018</p>10191020<p>1021A new, initialized slice value for a given element type <code>T</code> may be1022made using the built-in function1023<a href="#Making_slices_maps_and_channels"><code>make</code></a>,1024which takes a slice type1025and parameters specifying the length and optionally the capacity.1026A slice created with <code>make</code> always allocates a new, hidden array1027to which the returned slice value refers. That is, executing1028</p>10291030<pre>1031make([]T, length, capacity)1032</pre>10331034<p>1035produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a>1036it, so these two expressions are equivalent:1037</p>10381039<pre>1040make([]int, 50, 100)1041new([100]int)[0:50]1042</pre>10431044<p>1045Like arrays, slices are always one-dimensional but may be composed to construct1046higher-dimensional objects.1047With arrays of arrays, the inner arrays are, by construction, always the same length;1048however with slices of slices (or arrays of slices), the inner lengths may vary dynamically.1049Moreover, the inner slices must be initialized individually.1050</p>10511052<h3 id="Struct_types">Struct types</h3>10531054<p>1055A struct is a sequence of named elements, called fields, each of which has a1056name and a type. Field names may be specified explicitly (IdentifierList) or1057implicitly (EmbeddedField).1058Within a struct, non-<a href="#Blank_identifier">blank</a> field names must1059be <a href="#Uniqueness_of_identifiers">unique</a>.1060</p>10611062<pre class="ebnf">1063StructType = "struct" "{" { FieldDecl ";" } "}" .1064FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] .1065EmbeddedField = [ "*" ] TypeName [ TypeArgs ] .1066Tag = string_lit .1067</pre>10681069<pre>1070// An empty struct.1071struct {}10721073// A struct with 6 fields.1074struct {1075 x, y int1076 u float321077 _ float32 // padding1078 A *[]int1079 F func()1080}1081</pre>10821083<p>1084A field declared with a type but no explicit field name is called an <i>embedded field</i>.1085An embedded field must be specified as1086a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>,1087and <code>T</code> itself may not be1088a pointer type or type parameter. The unqualified type name acts as the field name.1089</p>10901091<pre>1092// A struct with four embedded fields of types T1, *T2, P.T3 and *P.T41093struct {1094 T1 // field name is T11095 *T2 // field name is T21096 P.T3 // field name is T31097 *P.T4 // field name is T41098 x, y int // field names are x and y1099}1100</pre>11011102<p>1103The following declaration is illegal because field names must be unique1104in a struct type:1105</p>11061107<pre>1108struct {1109 T // conflicts with embedded field *T and *P.T1110 *T // conflicts with embedded field T and *P.T1111 *P.T // conflicts with embedded field T and *T1112}1113</pre>11141115<p>1116A field or <a href="#Method_declarations">method</a> <code>f</code> of an1117embedded field in a struct <code>x</code> is called <i>promoted</i> if1118<code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes1119that field or method <code>f</code>.1120</p>11211122<p>1123Promoted fields act like ordinary fields of a struct.1124</p>11251126<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>11381139 <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>11461147<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>11551156<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}11621163// 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>11711172<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>11771178<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)11861187// 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>11941195<h3 id="Pointer_types">Pointer types</h3>11961197<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>.1201</p>12021203<pre class="ebnf">1204PointerType = "*" BaseType .1205BaseType = Type .1206</pre>12071208<pre>1209*Point1210*[4]int1211</pre>12121213<h3 id="Function_types">Function types</h3>12141215<p>1216A function type denotes the set of all functions with the same parameter and result types.1217The <a href="#Representation_of_values">value</a> of an uninitialized variable of function1218type is <code>nil</code>.1219</p>12201221<pre class="ebnf">1222FunctionType = "func" Signature .1223Signature = Parameters [ Result ] .1224Result = Parameters | Type .1225Parameters = "(" [ ParameterList [ "," ] ] ")" .1226ParameterList = ParameterDecl { "," ParameterDecl } .1227ParameterDecl = [ IdentifierList ] [ "..." ] Type .1228</pre>12291230<p>1231Within a list of parameters or results, the names (IdentifierList)1232must either all be present or all be absent. If present, each name1233stands for one item (parameter or result) of the specified type and1234all non-<a href="#Blank_identifier">blank</a> names in the signature1235must be <a href="#Uniqueness_of_identifiers">unique</a>.1236If absent, each type stands for one item of that type.1237Parameter and result1238lists are always parenthesized except that if there is exactly1239one unnamed result it may be written as an unparenthesized type.1240</p>12411242<p>1243The final incoming parameter in a function signature may have1244a type prefixed with <code>...</code>.1245A function with such a parameter is called <i>variadic</i> and1246may be invoked with zero or more arguments for that parameter.1247</p>12481249<pre>1250func()1251func(x int) int1252func(a, _ int, z float32) bool1253func(a, b int, z float32) (bool)1254func(prefix string, values ...int)1255func(a, b int, z float64, opt ...interface{}) (success bool)1256func(int, int, float64) (float64, *[]int)1257func(n int) func(p *T)1258</pre>12591260<h3 id="Interface_types">Interface types</h3>12611262<p>1263An interface type defines a <i>type set</i>.1264A variable of interface type can store a value of any type that is in the type1265set of the interface. Such a type is said to1266<a href="#Implementing_an_interface">implement the interface</a>.1267The <a href="#Representation_of_values">value</a> of an uninitialized variable of1268interface type is <code>nil</code>.1269</p>12701271<pre class="ebnf">1272InterfaceType = "interface" "{" { InterfaceElem ";" } "}" .1273InterfaceElem = MethodElem | TypeElem .1274MethodElem = MethodName Signature .1275MethodName = identifier .1276TypeElem = TypeTerm { "|" TypeTerm } .1277TypeTerm = Type | UnderlyingType .1278UnderlyingType = "~" Type .1279</pre>12801281<p>1282An interface type is specified by a list of <i>interface elements</i>.1283An interface element is either a <i>method</i> or a <i>type element</i>,1284where a type element is a union of one or more <i>type terms</i>.1285A type term is either a single type or a single underlying type.1286</p>12871288<h4 id="Basic_interfaces">Basic interfaces</h4>12891290<p>1291In its most basic form an interface specifies a (possibly empty) list of methods.1292The type set defined by such an interface is the set of types which implement all of1293those methods, and the corresponding <a href="#Method_sets">method set</a> consists1294exactly of the methods specified by the interface.1295Interfaces whose type sets can be defined entirely by a list of methods are called1296<i>basic interfaces.</i>1297Interface methods cannot declare <a href="#Type_parameter_declarations">type parameters</a>,1298but they may use type parameters from the interface declaration.1299</p>13001301<pre>1302// A simple File interface.1303interface {1304 Read([]byte) (int, error)1305 Write([]byte) (int, error)1306 Close() error1307}1308</pre>13091310<p>1311The name of each explicitly specified method must be <a href="#Uniqueness_of_identifiers">unique</a>1312and not <a href="#Blank_identifier">blank</a>.1313</p>13141315<pre>1316interface {1317 String() string1318 String() string // illegal: String not unique1319 _(x int) // illegal: method must have non-blank name1320}1321</pre>13221323<p>1324More than one type may implement an interface.1325For instance, if two types <code>S1</code> and <code>S2</code>1326have the method set1327</p>13281329<pre>1330func (p T) Read(p []byte) (n int, err error)1331func (p T) Write(p []byte) (n int, err error)1332func (p T) Close() error1333</pre>13341335<p>1336(where <code>T</code> stands for either <code>S1</code> or <code>S2</code>)1337then the <code>File</code> interface is implemented by both <code>S1</code> and1338<code>S2</code>, regardless of what other methods1339<code>S1</code> and <code>S2</code> may have or share.1340</p>13411342<p>1343Every type that is a member of the type set of an interface implements that interface.1344Any given type may implement several distinct interfaces.1345For instance, all types implement the <i>empty interface</i> which stands for the set1346of all (non-interface) types:1347</p>13481349<pre>1350interface{}1351</pre>13521353<p>1354For convenience, the predeclared type <code>any</code> is an alias for the empty interface;1355it is not a <a href="#Types">named type</a>.1356[<a href="#Go_1.18">Go 1.18</a>]1357</p>13581359<p>1360Similarly, consider this interface specification,1361which appears within a <a href="#Type_declarations">type declaration</a>1362to define an interface called <code>Locker</code>:1363</p>13641365<pre>1366type Locker interface {1367 Lock()1368 Unlock()1369}1370</pre>13711372<p>1373If <code>S1</code> and <code>S2</code> also implement1374</p>13751376<pre>1377func (p T) Lock() { … }1378func (p T) Unlock() { … }1379</pre>13801381<p>1382they implement the <code>Locker</code> interface as well1383as the <code>File</code> interface.1384</p>13851386<h4 id="Embedded_interfaces">Embedded interfaces</h4>13871388<p>1389In a slightly more general form1390an interface <code>T</code> may use a (possibly qualified) interface type1391name <code>E</code> as an interface element. This is called1392<i>embedding</i> interface <code>E</code> in <code>T</code>1393[<a href="#Go_1.14">Go 1.14</a>].1394The type set of <code>T</code> is the <i>intersection</i> of the type sets1395defined by <code>T</code>'s explicitly declared methods and the type sets1396of <code>T</code>’s embedded interfaces.1397In other words, the type set of <code>T</code> is the set of all types that implement all the1398explicitly declared methods of <code>T</code> and also all the methods of1399<code>E</code>1400[<a href="#Go_1.18">Go 1.18</a>].1401</p>14021403<pre>1404type Reader interface {1405 Read(p []byte) (n int, err error)1406 Close() error1407}14081409type Writer interface {1410 Write(p []byte) (n int, err error)1411 Close() error1412}14131414// ReadWriter's methods are Read, Write, and Close.1415type ReadWriter interface {1416 Reader // includes methods of Reader in ReadWriter's method set1417 Writer // includes methods of Writer in ReadWriter's method set1418}1419</pre>14201421<p>1422When embedding interfaces, methods with the1423<a href="#Uniqueness_of_identifiers">same</a> names must1424have <a href="#Type_identity">identical</a> signatures.1425</p>14261427<pre>1428type ReadCloser interface {1429 Reader // includes methods of Reader in ReadCloser's method set1430 Close() // illegal: signatures of Reader.Close and Close are different1431}1432</pre>14331434<h4 id="General_interfaces">General interfaces</h4>14351436<p>1437In their most general form, an interface element may also be an arbitrary type term1438<code>T</code>, or a term of the form <code>~T</code> specifying the underlying type <code>T</code>,1439or a union of terms <code>t<sub>1</sub>|t<sub>2</sub>|…|t<sub>n</sub></code>1440[<a href="#Go_1.18">Go 1.18</a>].1441Together with method specifications, these elements enable the precise1442definition of an interface's type set as follows:1443</p>14441445<ul>1446 <li>The type set of the empty interface is the set of all non-interface types.1447 </li>14481449 <li>The type set of a non-empty interface is the intersection of the type sets1450 of its interface elements.1451 </li>14521453 <li>The type set of a method specification is the set of all non-interface types1454 whose method sets include that method.1455 </li>14561457 <li>The type set of a non-interface type term is the set consisting1458 of just that type.1459 </li>14601461 <li>The type set of a term of the form <code>~T</code>1462 is the set of all types whose underlying type is <code>T</code>.1463 </li>14641465 <li>The type set of a <i>union</i> of terms1466 <code>t<sub>1</sub>|t<sub>2</sub>|…|t<sub>n</sub></code>1467 is the union of the type sets of the terms.1468 </li>1469</ul>14701471<p>1472The quantification "the set of all non-interface types" refers not just to all (non-interface)1473types declared in the program at hand, but all possible types in all possible programs, and1474hence is infinite.1475Similarly, given the set of all non-interface types that implement a particular method, the1476intersection of the method sets of those types will contain exactly that method, even if all1477types in the program at hand always pair that method with another method.1478</p>14791480<p>1481By construction, an interface's type set never contains an interface type.1482</p>14831484<pre>1485// An interface representing only the type int.1486interface {1487 int1488}14891490// An interface representing all types with underlying type int.1491interface {1492 ~int1493}14941495// An interface representing all types with underlying type int that implement the String method.1496interface {1497 ~int1498 String() string1499}15001501// An interface representing an empty type set: there is no type that is both an int and a string.1502interface {1503 int1504 string1505}1506</pre>15071508<p>1509In a term of the form <code>~T</code>, the underlying type of <code>T</code>1510must be itself, and <code>T</code> cannot be an interface.1511</p>15121513<pre>1514type MyInt int15151516interface {1517 ~[]byte // the underlying type of []byte is itself1518 ~MyInt // illegal: the underlying type of MyInt is not MyInt1519 ~error // illegal: error is an interface1520}1521</pre>15221523<p>1524Union elements denote unions of type sets:1525</p>15261527<pre>1528// The Float interface represents all floating-point types1529// (including any named types whose underlying types are1530// either float32 or float64).1531type Float interface {1532 ~float32 | ~float641533}1534</pre>15351536<p>1537The type <code>T</code> in a term of the form <code>T</code> or <code>~T</code> cannot1538be a <a href="#Type_parameter_declarations">type parameter</a>, and the type sets of all1539non-interface terms must be pairwise disjoint (the pairwise intersection of the type sets must be empty).1540Given a type parameter <code>P</code>:1541</p>15421543<pre>1544interface {1545 P // illegal: P is a type parameter1546 int | ~P // illegal: P is a type parameter1547 ~int | MyInt // illegal: the type sets for ~int and MyInt are not disjoint (~int includes MyInt)1548 float32 | Float // overlapping type sets but Float is an interface1549}1550</pre>15511552<p>1553Implementation restriction:1554A union (with more than one term) cannot contain the1555<a href="#Predeclared_identifiers">predeclared identifier</a> <code>comparable</code>1556or interfaces that specify methods, or embed <code>comparable</code> or interfaces1557that specify methods.1558</p>15591560<p>1561Interfaces that are not <a href="#Basic_interfaces">basic</a> may only be used as type1562constraints, or as elements of other interfaces used as constraints.1563They cannot be the types of values or variables, or components of other,1564non-interface types.1565</p>15661567<pre>1568var x Float // illegal: Float is not a basic interface15691570var x interface{} = Float(nil) // illegal15711572type Floatish struct {1573 f Float // illegal1574}1575</pre>15761577<p>1578An interface type <code>T</code> may not embed a type element1579that is, contains, or embeds <code>T</code>, directly or indirectly.1580</p>15811582<pre>1583// illegal: Bad may not embed itself1584type Bad interface {1585 Bad1586}15871588// illegal: Bad1 may not embed itself using Bad21589type Bad1 interface {1590 Bad21591}1592type Bad2 interface {1593 Bad11594}15951596// illegal: Bad3 may not embed a union containing Bad31597type Bad3 interface {1598 ~int | ~string | Bad31599}16001601// illegal: Bad4 may not embed an array containing Bad4 as element type1602type Bad4 interface {1603 [10]Bad41604}1605</pre>16061607<h4 id="Implementing_an_interface">Implementing an interface</h4>16081609<p>1610A type <code>T</code> implements an interface <code>I</code> if1611</p>16121613<ul>1614<li>1615 <code>T</code> is not an interface and is an element of the type set of <code>I</code>; or1616</li>1617<li>1618 <code>T</code> is an interface and the type set of <code>T</code> is a subset of the1619 type set of <code>I</code>.1620</li>1621</ul>16221623<p>1624A value of type <code>T</code> implements an interface if <code>T</code>1625implements the interface.1626</p>16271628<h3 id="Map_types">Map types</h3>16291630<p>1631A map is an unordered group of elements of one type, called the1632element type, indexed by a set of unique <i>keys</i> of another type,1633called the key type.1634The <a href="#Representation_of_values">value</a> of an uninitialized map is <code>nil</code>.1635</p>16361637<pre class="ebnf">1638MapType = "map" "[" KeyType "]" ElementType .1639KeyType = Type .1640</pre>16411642<p>1643The <a href="#Comparison_operators">comparison operators</a>1644<code>==</code> and <code>!=</code> must be fully defined1645for operands of the key type; thus the key type must not be a function, map, or1646slice.1647If the key type is an interface type, these1648comparison operators must be defined for the dynamic key values;1649failure will cause a <a href="#Run_time_panics">run-time panic</a>.1650</p>16511652<pre>1653map[string]int1654map[*T]struct{ x, y float64 }1655map[string]interface{}1656</pre>16571658<p>1659The number of map elements is called its length.1660For a map <code>m</code>, it can be discovered using the1661built-in function <a href="#Length_and_capacity"><code>len</code></a>1662and may change during execution. Elements may be added during execution1663using <a href="#Assignment_statements">assignments</a> and retrieved with1664<a href="#Index_expressions">index expressions</a>; they may be removed with the1665<a href="#Deletion_of_map_elements"><code>delete</code></a> and1666<a href="#Clear"><code>clear</code></a> built-in function.1667</p>16681669<p>1670A new, empty map value is made using the built-in1671function <a href="#Making_slices_maps_and_channels"><code>make</code></a>,1672which takes the map type and an optional capacity hint as arguments:1673</p>16741675<pre>1676make(map[string]int)1677make(map[string]int, 100)1678</pre>16791680<p>1681The initial capacity does not bound its size:1682maps grow to accommodate the number of items1683stored in them, with the exception of <code>nil</code> maps.1684A <code>nil</code> map is equivalent to an empty map except that no elements1685may be added.1686</p>16871688<h3 id="Channel_types">Channel types</h3>16891690<p>1691A channel provides a mechanism for1692<a href="#Go_statements">concurrently executing functions</a>1693to communicate by1694<a href="#Send_statements">sending</a> and1695<a href="#Receive_operator">receiving</a>1696values of a specified element type.1697The <a href="#Representation_of_values">value</a> of an uninitialized channel is <code>nil</code>.1698</p>16991700<pre class="ebnf">1701ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType .1702</pre>17031704<p>1705The optional <code><-</code> operator specifies the channel <i>direction</i>,1706<i>send</i> or <i>receive</i>. If a direction is given, the channel is <i>directional</i>,1707otherwise it is <i>bidirectional</i>.1708A channel may be constrained only to send or only to receive by1709<a href="#Assignment_statements">assignment</a> or1710explicit <a href="#Conversions">conversion</a>.1711</p>17121713<pre>1714chan T // can be used to send and receive values of type T1715chan<- float64 // can only be used to send float64s1716<-chan int // can only be used to receive ints1717</pre>17181719<p>1720The <code><-</code> operator associates with the leftmost <code>chan</code>1721possible:1722</p>17231724<pre>1725chan<- chan int // same as chan<- (chan int)1726chan<- <-chan int // same as chan<- (<-chan int)1727<-chan <-chan int // same as <-chan (<-chan int)1728chan (<-chan int)1729</pre>17301731<p>1732A new, initialized channel1733value can be made using the built-in function1734<a href="#Making_slices_maps_and_channels"><code>make</code></a>,1735which takes the channel type and an optional <i>capacity</i> as arguments:1736</p>17371738<pre>1739make(chan int, 100)1740</pre>17411742<p>1743The capacity, in number of elements, sets the size of the buffer in the channel.1744If the capacity is zero or absent, the channel is unbuffered and communication1745succeeds only when both a sender and receiver are ready. Otherwise, the channel1746is buffered and communication succeeds without blocking if the buffer1747is not full (sends) or not empty (receives).1748A <code>nil</code> channel is never ready for communication.1749</p>17501751<p>1752A channel may be closed with the built-in function1753<a href="#Close"><code>close</code></a>.1754The multi-valued assignment form of the1755<a href="#Receive_operator">receive operator</a>1756reports whether a received value was sent before1757the channel was closed.1758</p>17591760<p>1761A single channel may be used in1762<a href="#Send_statements">send statements</a>,1763<a href="#Receive_operator">receive operations</a>,1764and calls to the built-in functions1765<a href="#Length_and_capacity"><code>cap</code></a> and1766<a href="#Length_and_capacity"><code>len</code></a>1767by any number of goroutines without further synchronization.1768Channels act as first-in-first-out queues.1769For example, if one goroutine sends values on a channel1770and a second goroutine receives them, the values are1771received in the order sent.1772</p>17731774<h2 id="Properties_of_types_and_values">Properties of types and values</h2>17751776<h3 id="Representation_of_values">Representation of values</h3>17771778<p>1779Values of predeclared types (see below for the interfaces <code>any</code>1780and <code>error</code>), arrays, and structs are self-contained:1781Each such value contains a complete copy of all its data,1782and <a href="#Variables">variables</a> of such types store the entire value.1783For instance, an array variable provides the storage (the variables)1784for all elements of the array.1785The respective <a href="#The_zero_value">zero values</a> are specific to the1786value's types; they are never <code>nil</code>.1787</p>17881789<p>1790Non-nil pointer, function, slice, map, and channel values contain references1791to underlying data which may be shared by multiple values:1792</p>17931794<ul>1795<li>1796 A pointer value is a reference to the variable holding1797 the pointer base type value.1798</li>1799<li>1800 A function value contains references to the (possibly1801 <a href="#Function_literals">anonymous</a>) function1802 and enclosed variables.1803</li>1804<li>1805 A slice value contains the slice length, capacity, and1806 a reference to its <a href="#Slice_types">underlying array</a>.1807</li>1808<li>1809 A map or channel value is a reference to the implementation-specific1810 data structure of the map or channel.1811</li>1812</ul>18131814<p>1815An interface value may be self-contained or contain references to underlying data1816depending on the interface's <a href="#Variables">dynamic type</a>.1817The predeclared identifier <code>nil</code> is the zero value for types whose values1818can contain references.1819</p>18201821<p>1822When multiple values share underlying data, changing one value may change another.1823For instance, changing an element of a <a href="#Slice_types">slice</a> will change1824that element in the underlying array for all slices that share the array.1825</p>18261827<h3 id="Underlying_types">Underlying types</h3>18281829<p>1830Each type <code>T</code> has an <i>underlying type</i>: If <code>T</code>1831is one of the predeclared boolean, numeric, or string types, or a type literal,1832the corresponding underlying type is <code>T</code> itself.1833Otherwise, <code>T</code>'s underlying type is the underlying type of the1834type to which <code>T</code> refers in its declaration.1835For a type parameter that is the underlying type of its1836<a href="#Type_constraints">type constraint</a>, which is always an interface.1837</p>18381839<pre>1840type (1841 A1 = string1842 A2 = A11843)18441845type (1846 B1 string1847 B2 B11848 B3 []B11849 B4 B31850)18511852func f[P any](x P) { … }1853</pre>18541855<p>1856The underlying type of <code>string</code>, <code>A1</code>, <code>A2</code>, <code>B1</code>,1857and <code>B2</code> is <code>string</code>.1858The underlying type of <code>[]B1</code>, <code>B3</code>, and <code>B4</code> is <code>[]B1</code>.1859The underlying type of <code>P</code> is <code>interface{}</code>.1860</p>18611862<h3 id="Type_identity">Type identity</h3>18631864<p>1865Two types are either <i>identical</i> ("the same") or <i>different</i>.1866</p>18671868<p>1869A <a href="#Types">named type</a> is always different from any other type.1870Otherwise, two types are identical if their <a href="#Types">underlying</a> type literals are1871structurally equivalent; that is, they have the same literal structure and corresponding1872components have identical types. In detail:1873</p>18741875<ul>1876 <li>Two array types are identical if they have identical element types and1877 the same array length.</li>18781879 <li>Two slice types are identical if they have identical element types.</li>18801881 <li>Two struct types are identical if they have the same sequence of fields,1882 and if corresponding pairs of fields have the same names, identical types,1883 and identical tags, and are either both embedded or both not embedded.1884 <a href="#Exported_identifiers">Non-exported</a> field names from different1885 packages are always different.</li>18861887 <li>Two pointer types are identical if they have identical base types.</li>18881889 <li>Two function types are identical if they have the same number of parameters1890 and result values, corresponding parameter and result types are1891 identical, and either both functions are variadic or neither is.1892 Parameter and result names are not required to match.</li>18931894 <li>Two interface types are identical if they define the same type set.1895 </li>18961897 <li>Two map types are identical if they have identical key and element types.</li>18981899 <li>Two channel types are identical if they have identical element types and1900 the same direction.</li>19011902 <li>Two <a href="#Instantiations">instantiated</a> types are identical if1903 their defined types and all type arguments are identical.1904 </li>1905</ul>19061907<p>1908Given the declarations1909</p>19101911<pre>1912type (1913 A0 = []string1914 A1 = A01915 A2 = struct{ a, b int }1916 A3 = int1917 A4 = func(A3, float64) *A01918 A5 = func(x int, _ float64) *[]string19191920 B0 A01921 B1 []string1922 B2 struct{ a, b int }1923 B3 struct{ a, c int }1924 B4 func(int, float64) *B01925 B5 func(x int, y float64) *A119261927 C0 = B01928 D0[P1, P2 any] struct{ x P1; y P2 }1929 E0 = D0[int, string]1930)1931</pre>19321933<p>1934these types are identical:1935</p>19361937<pre>1938A0, A1, and []string1939A2 and struct{ a, b int }1940A3 and int1941A4, func(int, float64) *[]string, and A519421943B0 and C01944D0[int, string] and E01945[]int and []int1946struct{ a, b *B5 } and struct{ a, b *B5 }1947func(x int, y float64) *[]string, func(int, float64) (result *[]string), and A51948</pre>19491950<p>1951<code>B0</code> and <code>B1</code> are different because they are new types1952created by distinct <a href="#Type_definitions">type definitions</a>;1953<code>func(int, float64) *B0</code> and <code>func(x int, y float64) *[]string</code>1954are different because <code>B0</code> is different from <code>[]string</code>;1955and <code>P1</code> and <code>P2</code> are different because they are different1956type parameters.1957<code>D0[int, string]</code> and <code>struct{ x int; y string }</code> are1958different because the former is an <a href="#Instantiations">instantiated</a>1959defined type while the latter is a type literal1960(but they are still <a href="#Assignability">assignable</a>).1961</p>19621963<h3 id="Assignability">Assignability</h3>19641965<p>1966A value <code>x</code> of type <code>V</code> is <i>assignable</i> to a <a href="#Variables">variable</a> of type <code>T</code>1967("<code>x</code> is assignable to <code>T</code>") if one of the following conditions applies:1968</p>19691970<ul>1971<li>1972<code>V</code> and <code>T</code> are identical.1973</li>1974<li>1975<code>V</code> and <code>T</code> have identical1976<a href="#Underlying_types">underlying types</a>1977but are not type parameters and at least one of <code>V</code>1978or <code>T</code> is not a <a href="#Types">named type</a>.1979</li>1980<li>1981<code>V</code> and <code>T</code> are channel types with1982identical element types, <code>V</code> is a bidirectional channel,1983and at least one of <code>V</code> or <code>T</code> is not a <a href="#Types">named type</a>.1984</li>1985<li>1986<code>T</code> is an interface type, but not a type parameter, and1987<code>x</code> <a href="#Implementing_an_interface">implements</a> <code>T</code>.1988</li>1989<li>1990<code>x</code> is a (possibly partially instantiated) generic function, <code>T</code>1991is a function type, and any type arguments not provided explicitly for <code>x</code>1992can be <a href="#Type_inference">inferred</a> such that (after full instantiation)1993<code>x</code> and <code>T</code> have identical underlying types1994[<a href="#Go_1.27">Go 1.27</a>].1995</li>1996<li>1997<code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code>1998is a pointer, function, slice, map, channel, or interface type,1999but not a type parameter.2000</li>
Findings
✓ No findings reported for this file.