| 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> |
| 10 |
This is the reference manual for the Go programming language. |
| 11 |
For more information and other documents, see <a href="/">go.dev</a>. |
| 12 |
</p> |
| 13 |
|
| 14 |
<p> |
| 15 |
Go is a general-purpose language designed with systems programming |
| 16 |
in mind. It is strongly typed and garbage-collected and has explicit |
| 17 |
support for concurrent programming. Programs are constructed from |
| 18 |
<i>packages</i>, whose properties allow efficient management of |
| 19 |
dependencies. |
| 20 |
</p> |
| 21 |
|
| 22 |
<p> |
| 23 |
The syntax is compact and simple to parse, allowing for easy analysis |
| 24 |
by automatic tools such as integrated development environments. |
| 25 |
</p> |
| 26 |
|
| 27 |
<h2 id="Notation">Notation</h2> |
| 28 |
<p> |
| 29 |
The syntax is specified using a |
| 30 |
<a href="https://en.wikipedia.org/wiki/Wirth_syntax_notation">variant</a> |
| 31 |
of Extended Backus-Naur Form (EBNF): |
| 32 |
</p> |
| 33 |
|
| 34 |
<pre class="grammar"> |
| 35 |
Syntax = { Production } . |
| 36 |
Production = production_name "=" [ Expression ] "." . |
| 37 |
Expression = Term { "|" Term } . |
| 38 |
Term = Factor { Factor } . |
| 39 |
Factor = production_name | token [ "…" token ] | Group | Option | Repetition . |
| 40 |
Group = "(" Expression ")" . |
| 41 |
Option = "[" Expression "]" . |
| 42 |
Repetition = "{" Expression "}" . |
| 43 |
</pre> |
| 44 |
|
| 45 |
<p> |
| 46 |
Productions are expressions constructed from terms and the following |
| 47 |
operators, in increasing precedence: |
| 48 |
</p> |
| 49 |
<pre class="grammar"> |
| 50 |
| alternation |
| 51 |
() grouping |
| 52 |
[] option (0 or 1 times) |
| 53 |
{} repetition (0 to n times) |
| 54 |
</pre> |
| 55 |
|
| 56 |
<p> |
| 57 |
Lowercase production names are used to identify lexical (terminal) tokens. |
| 58 |
Non-terminals are in CamelCase. Lexical tokens are enclosed in |
| 59 |
double quotes <code>""</code> or back quotes <code>``</code>. |
| 60 |
</p> |
| 61 |
|
| 62 |
<p> |
| 63 |
The form <code>a … b</code> represents the set of characters from |
| 64 |
<code>a</code> through <code>b</code> as alternatives. The horizontal |
| 65 |
ellipsis <code>…</code> is also used elsewhere in the spec to informally denote various |
| 66 |
enumerations 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 Go |
| 68 |
language. |
| 69 |
</p> |
| 70 |
|
| 71 |
<p> |
| 72 |
A link of the form [<a href="#Language_versions">Go 1.xx</a>] indicates that a described |
| 73 |
language feature (or some aspect of it) was changed or added with language version 1.xx and |
| 74 |
thus requires at minimum that language version to build. |
| 75 |
For details, see the <a href="#Language_versions">linked section</a> |
| 76 |
in the <a href="#Appendix">appendix</a>. |
| 77 |
</p> |
| 78 |
|
| 79 |
<h2 id="Source_code_representation">Source code representation</h2> |
| 80 |
|
| 81 |
<p> |
| 82 |
Source code is Unicode text encoded in |
| 83 |
<a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. The text is not |
| 84 |
canonicalized, so a single accented code point is distinct from the |
| 85 |
same character constructed from combining an accent and a letter; |
| 86 |
those are treated as two code points. For simplicity, this document |
| 87 |
will use the unqualified term <i>character</i> to refer to a Unicode code point |
| 88 |
in the source text. |
| 89 |
</p> |
| 90 |
<p> |
| 91 |
Each code point is distinct; for instance, uppercase and lowercase letters |
| 92 |
are different characters. |
| 93 |
</p> |
| 94 |
<p> |
| 95 |
Implementation restriction: For compatibility with other tools, a |
| 96 |
compiler may disallow the NUL character (U+0000) in the source text. |
| 97 |
</p> |
| 98 |
<p> |
| 99 |
Implementation restriction: For compatibility with other tools, a |
| 100 |
compiler may ignore a UTF-8-encoded byte order mark |
| 101 |
(U+FEFF) if it is the first Unicode code point in the source text. |
| 102 |
A byte order mark may be disallowed anywhere else in the source. |
| 103 |
</p> |
| 104 |
|
| 105 |
<h3 id="Characters">Characters</h3> |
| 106 |
|
| 107 |
<p> |
| 108 |
The following terms are used to denote specific Unicode character categories: |
| 109 |
</p> |
| 110 |
<pre class="ebnf"> |
| 111 |
newline = /* the Unicode code point U+000A */ . |
| 112 |
unicode_char = /* an arbitrary Unicode code point except newline */ . |
| 113 |
unicode_letter = /* a Unicode code point categorized as "Letter" */ . |
| 114 |
unicode_digit = /* a Unicode code point categorized as "Number, decimal digit" */ . |
| 115 |
</pre> |
| 116 |
|
| 117 |
<p> |
| 118 |
In <a href="https://www.unicode.org/versions/Unicode8.0.0/">The Unicode Standard 8.0</a>, |
| 119 |
Section 4.5 "General Category" defines a set of character categories. |
| 120 |
Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo |
| 121 |
as 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> |
| 127 |
The underscore character <code>_</code> (U+005F) is considered a lowercase letter. |
| 128 |
</p> |
| 129 |
<pre class="ebnf"> |
| 130 |
letter = unicode_letter | "_" . |
| 131 |
decimal_digit = "0" … "9" . |
| 132 |
binary_digit = "0" | "1" . |
| 133 |
octal_digit = "0" … "7" . |
| 134 |
hex_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> |
| 142 |
Comments 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> |
| 148 |
and stop at the end of the line. |
| 149 |
</li> |
| 150 |
<li> |
| 151 |
<i>General comments</i> start with the character sequence <code>/*</code> |
| 152 |
and stop with the first subsequent character sequence <code>*/</code>. |
| 153 |
</li> |
| 154 |
</ol> |
| 155 |
|
| 156 |
<p> |
| 157 |
A comment cannot start inside a <a href="#Rune_literals">rune</a> or |
| 158 |
<a href="#String_literals">string literal</a>, or inside a comment. |
| 159 |
A general comment containing no newlines acts like a space. |
| 160 |
Any other comment acts like a newline. |
| 161 |
</p> |
| 162 |
|
| 163 |
<h3 id="Tokens">Tokens</h3> |
| 164 |
|
| 165 |
<p> |
| 166 |
Tokens form the vocabulary of the Go language. |
| 167 |
There are four classes: <i>identifiers</i>, <i>keywords</i>, <i>operators |
| 168 |
and punctuation</i>, and <i>literals</i>. <i>White space</i>, formed from |
| 169 |
spaces (U+0020), horizontal tabs (U+0009), |
| 170 |
carriage returns (U+000D), and newlines (U+000A), |
| 171 |
is ignored except as it separates tokens |
| 172 |
that would otherwise combine into a single token. Also, a newline or end of file |
| 173 |
may trigger the insertion of a <a href="#Semicolons">semicolon</a>. |
| 174 |
While breaking the input into tokens, |
| 175 |
the next token is the longest sequence of characters that form a |
| 176 |
valid token. |
| 177 |
</p> |
| 178 |
|
| 179 |
<h3 id="Semicolons">Semicolons</h3> |
| 180 |
|
| 181 |
<p> |
| 182 |
The formal syntax uses semicolons <code>";"</code> as terminators in |
| 183 |
a number of productions. Go programs may omit most of these semicolons |
| 184 |
using the following two rules: |
| 185 |
</p> |
| 186 |
|
| 187 |
<ol> |
| 188 |
<li> |
| 189 |
When the input is broken into tokens, a semicolon is automatically inserted |
| 190 |
into the token stream immediately after a line's final token if that token is |
| 191 |
<ul> |
| 192 |
<li>an |
| 193 |
<a href="#Identifiers">identifier</a> |
| 194 |
</li> |
| 195 |
|
| 196 |
<li>an |
| 197 |
<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>, or |
| 201 |
<a href="#String_literals">string</a> literal |
| 202 |
</li> |
| 203 |
|
| 204 |
<li>one of the <a href="#Keywords">keywords</a> |
| 205 |
<code>break</code>, |
| 206 |
<code>continue</code>, |
| 207 |
<code>fallthrough</code>, or |
| 208 |
<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>, or |
| 216 |
<code>}</code> |
| 217 |
</li> |
| 218 |
</ul> |
| 219 |
</li> |
| 220 |
|
| 221 |
<li> |
| 222 |
To allow complex statements to occupy a single line, a semicolon |
| 223 |
may be omitted before a closing <code>")"</code> or <code>"}"</code>. |
| 224 |
</li> |
| 225 |
</ol> |
| 226 |
|
| 227 |
<p> |
| 228 |
To reflect idiomatic use, code examples in this document elide semicolons |
| 229 |
using these rules. |
| 230 |
</p> |
| 231 |
|
| 232 |
|
| 233 |
<h3 id="Identifiers">Identifiers</h3> |
| 234 |
|
| 235 |
<p> |
| 236 |
Identifiers name program entities such as variables and types. |
| 237 |
An identifier is a sequence of one or more letters and digits. |
| 238 |
The first character in an identifier must be a letter. |
| 239 |
</p> |
| 240 |
<pre class="ebnf"> |
| 241 |
identifier = letter { letter | unicode_digit } . |
| 242 |
</pre> |
| 243 |
<pre> |
| 244 |
a |
| 245 |
_x9 |
| 246 |
ThisVariableIsExported |
| 247 |
αβ |
| 248 |
</pre> |
| 249 |
|
| 250 |
<p> |
| 251 |
Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>. |
| 252 |
</p> |
| 253 |
|
| 254 |
|
| 255 |
<h3 id="Keywords">Keywords</h3> |
| 256 |
|
| 257 |
<p> |
| 258 |
The following keywords are reserved and may not be used as identifiers. |
| 259 |
</p> |
| 260 |
<pre class="grammar"> |
| 261 |
break default func interface select |
| 262 |
case defer go map struct |
| 263 |
chan else goto package switch |
| 264 |
const fallthrough if range type |
| 265 |
continue for import return var |
| 266 |
</pre> |
| 267 |
|
| 268 |
<h3 id="Operators_and_punctuation">Operators and punctuation</h3> |
| 269 |
|
| 270 |
<p> |
| 271 |
The following character sequences represent <a href="#Operators">operators</a> |
| 272 |
(including <a href="#Assignment_statements">assignment operators</a>) and punctuation |
| 273 |
[<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> |
| 287 |
An integer literal is a sequence of digits representing an |
| 288 |
<a href="#Constants">integer constant</a>. |
| 289 |
An optional prefix sets a non-decimal base: <code>0b</code> or <code>0B</code> |
| 290 |
for binary, <code>0</code>, <code>0o</code>, or <code>0O</code> for octal, |
| 291 |
and <code>0x</code> or <code>0X</code> for hexadecimal |
| 292 |
[<a href="#Go_1.13">Go 1.13</a>]. |
| 293 |
A single <code>0</code> is considered a decimal zero. |
| 294 |
In hexadecimal literals, letters <code>a</code> through <code>f</code> |
| 295 |
and <code>A</code> through <code>F</code> represent values 10 through 15. |
| 296 |
</p> |
| 297 |
|
| 298 |
<p> |
| 299 |
For readability, an underscore character <code>_</code> may appear after |
| 300 |
a base prefix or between successive digits; such underscores do not change |
| 301 |
the literal's value. |
| 302 |
</p> |
| 303 |
<pre class="ebnf"> |
| 304 |
int_lit = decimal_lit | binary_lit | octal_lit | hex_lit . |
| 305 |
decimal_lit = "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] . |
| 306 |
binary_lit = "0" ( "b" | "B" ) [ "_" ] binary_digits . |
| 307 |
octal_lit = "0" [ "o" | "O" ] [ "_" ] octal_digits . |
| 308 |
hex_lit = "0" ( "x" | "X" ) [ "_" ] hex_digits . |
| 309 |
|
| 310 |
decimal_digits = decimal_digit { [ "_" ] decimal_digit } . |
| 311 |
binary_digits = binary_digit { [ "_" ] binary_digit } . |
| 312 |
octal_digits = octal_digit { [ "_" ] octal_digit } . |
| 313 |
hex_digits = hex_digit { [ "_" ] hex_digit } . |
| 314 |
</pre> |
| 315 |
|
| 316 |
<pre> |
| 317 |
42 |
| 318 |
4_2 |
| 319 |
0600 |
| 320 |
0_600 |
| 321 |
0o600 |
| 322 |
0O600 // second character is capital letter 'O' |
| 323 |
0xBadFace |
| 324 |
0xBad_Face |
| 325 |
0x_67_7a_2f_cc_40_c6 |
| 326 |
170141183460469231731687303715884105727 |
| 327 |
170_141183_460469_231731_687303_715884_105727 |
| 328 |
|
| 329 |
_42 // an identifier, not an integer literal |
| 330 |
42_ // invalid: _ must separate successive digits |
| 331 |
4__2 // invalid: only one _ at a time |
| 332 |
0_xBadFace // invalid: _ must separate successive digits |
| 333 |
</pre> |
| 334 |
|
| 335 |
|
| 336 |
<h3 id="Floating-point_literals">Floating-point literals</h3> |
| 337 |
|
| 338 |
<p> |
| 339 |
A floating-point literal is a decimal or hexadecimal representation of a |
| 340 |
<a href="#Constants">floating-point constant</a>. |
| 341 |
</p> |
| 342 |
|
| 343 |
<p> |
| 344 |
A decimal floating-point literal consists of an integer part (decimal digits), |
| 345 |
a decimal point, a fractional part (decimal digits), and an exponent part |
| 346 |
(<code>e</code> or <code>E</code> followed by an optional sign and decimal digits). |
| 347 |
One of the integer part or the fractional part may be elided; one of the decimal point |
| 348 |
or the exponent part may be elided. |
| 349 |
An exponent value exp scales the mantissa (integer and fractional part) by 10<sup>exp</sup>. |
| 350 |
</p> |
| 351 |
|
| 352 |
<p> |
| 353 |
A hexadecimal floating-point literal consists of a <code>0x</code> or <code>0X</code> |
| 354 |
prefix, an integer part (hexadecimal digits), a radix point, a fractional part (hexadecimal digits), |
| 355 |
and an exponent part (<code>p</code> or <code>P</code> followed by an optional sign and decimal digits). |
| 356 |
One of the integer part or the fractional part may be elided; the radix point may be elided as well, |
| 357 |
but the exponent part is required. (This syntax matches the one given in IEEE 754-2008 §5.12.3.) |
| 358 |
An 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> |
| 363 |
For readability, an underscore character <code>_</code> may appear after |
| 364 |
a base prefix or between successive digits; such underscores do not change |
| 365 |
the literal value. |
| 366 |
</p> |
| 367 |
|
| 368 |
<pre class="ebnf"> |
| 369 |
float_lit = decimal_float_lit | hex_float_lit . |
| 370 |
|
| 371 |
decimal_float_lit = decimal_digits "." [ decimal_digits ] [ decimal_exponent ] | |
| 372 |
decimal_digits decimal_exponent | |
| 373 |
"." decimal_digits [ decimal_exponent ] . |
| 374 |
decimal_exponent = ( "e" | "E" ) [ "+" | "-" ] decimal_digits . |
| 375 |
|
| 376 |
hex_float_lit = "0" ( "x" | "X" ) hex_mantissa hex_exponent . |
| 377 |
hex_mantissa = [ "_" ] hex_digits "." [ hex_digits ] | |
| 378 |
[ "_" ] hex_digits | |
| 379 |
"." hex_digits . |
| 380 |
hex_exponent = ( "p" | "P" ) [ "+" | "-" ] decimal_digits . |
| 381 |
</pre> |
| 382 |
|
| 383 |
<pre> |
| 384 |
0. |
| 385 |
72.40 |
| 386 |
072.40 // == 72.40 |
| 387 |
2.71828 |
| 388 |
1.e+0 |
| 389 |
6.67428e-11 |
| 390 |
1E6 |
| 391 |
.25 |
| 392 |
.12345E+5 |
| 393 |
1_5. // == 15.0 |
| 394 |
0.15e+0_2 // == 15.0 |
| 395 |
|
| 396 |
0x1p-2 // == 0.25 |
| 397 |
0x2.p10 // == 2048.0 |
| 398 |
0x1.Fp+0 // == 1.9375 |
| 399 |
0X.8p-0 // == 0.5 |
| 400 |
0X_1FFFP-16 // == 0.1249847412109375 |
| 401 |
0x15e-2 // == 0x15e - 2 (integer subtraction) |
| 402 |
|
| 403 |
0x.p1 // invalid: mantissa has no digits |
| 404 |
1p-2 // invalid: p exponent requires hexadecimal mantissa |
| 405 |
0x1.5e-2 // invalid: hexadecimal mantissa requires p exponent |
| 406 |
1_.5 // invalid: _ must separate successive digits |
| 407 |
1._5 // invalid: _ must separate successive digits |
| 408 |
1.5_e1 // invalid: _ must separate successive digits |
| 409 |
1.5e_1 // invalid: _ must separate successive digits |
| 410 |
1.5e1_ // invalid: _ must separate successive digits |
| 411 |
</pre> |
| 412 |
|
| 413 |
|
| 414 |
<h3 id="Imaginary_literals">Imaginary literals</h3> |
| 415 |
|
| 416 |
<p> |
| 417 |
An imaginary literal represents the imaginary part of a |
| 418 |
<a href="#Constants">complex constant</a>. |
| 419 |
It consists of an <a href="#Integer_literals">integer</a> or |
| 420 |
<a href="#Floating-point_literals">floating-point</a> literal |
| 421 |
followed by the lowercase letter <code>i</code>. |
| 422 |
The value of an imaginary literal is the value of the respective |
| 423 |
integer 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"> |
| 428 |
imaginary_lit = (decimal_digits | int_lit | float_lit) "i" . |
| 429 |
</pre> |
| 430 |
|
| 431 |
<p> |
| 432 |
For backward compatibility, an imaginary literal's integer part consisting |
| 433 |
entirely of decimal digits (and possibly underscores) is considered a decimal |
| 434 |
integer, even if it starts with a leading <code>0</code>. |
| 435 |
</p> |
| 436 |
|
| 437 |
<pre> |
| 438 |
0i |
| 439 |
0123i // == 123i for backward-compatibility |
| 440 |
0o123i // == 0o123 * 1i == 83i |
| 441 |
0xabci // == 0xabc * 1i == 2748i |
| 442 |
0.i |
| 443 |
2.71828i |
| 444 |
1.e+0i |
| 445 |
6.67428e-11i |
| 446 |
1E6i |
| 447 |
.25i |
| 448 |
.12345E+5i |
| 449 |
0x1p-2i // == 0x1p-2 * 1i == 0.25i |
| 450 |
</pre> |
| 451 |
|
| 452 |
|
| 453 |
<h3 id="Rune_literals">Rune literals</h3> |
| 454 |
|
| 455 |
<p> |
| 456 |
A rune literal represents a <a href="#Constants">rune constant</a>, |
| 457 |
an integer value identifying a Unicode code point. |
| 458 |
A rune literal is expressed as one or more characters enclosed in single quotes, |
| 459 |
as in <code>'x'</code> or <code>'\n'</code>. |
| 460 |
Within the quotes, any character may appear except newline and unescaped single |
| 461 |
quote. A single quoted character represents the Unicode value |
| 462 |
of the character itself, |
| 463 |
while multi-character sequences beginning with a backslash encode |
| 464 |
values in various formats. |
| 465 |
</p> |
| 466 |
|
| 467 |
<p> |
| 468 |
The simplest form represents the single character within the quotes; |
| 469 |
since Go source text is Unicode characters encoded in UTF-8, multiple |
| 470 |
UTF-8-encoded bytes may represent a single integer value. For |
| 471 |
instance, the literal <code>'a'</code> holds a single byte representing |
| 472 |
a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while |
| 473 |
<code>'ä'</code> holds two bytes (<code>0xc3</code> <code>0xa4</code>) representing |
| 474 |
a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>. |
| 475 |
</p> |
| 476 |
|
| 477 |
<p> |
| 478 |
Several backslash escapes allow arbitrary values to be encoded as |
| 479 |
ASCII text. There are four ways to represent the integer value |
| 480 |
as a numeric constant: <code>\x</code> followed by exactly two hexadecimal |
| 481 |
digits; <code>\u</code> followed by exactly four hexadecimal digits; |
| 482 |
<code>\U</code> followed by exactly eight hexadecimal digits, and a |
| 483 |
plain backslash <code>\</code> followed by exactly three octal digits. |
| 484 |
In each case the value of the literal is the value represented by |
| 485 |
the digits in the corresponding base. |
| 486 |
</p> |
| 487 |
|
| 488 |
<p> |
| 489 |
Although these representations all result in an integer, they have |
| 490 |
different valid ranges. Octal escapes must represent a value between |
| 491 |
0 and 255 inclusive. Hexadecimal escapes satisfy this condition |
| 492 |
by construction. The escapes <code>\u</code> and <code>\U</code> |
| 493 |
represent Unicode code points so within them some values are illegal, |
| 494 |
in particular those above <code>0x10FFFF</code> and surrogate halves. |
| 495 |
</p> |
| 496 |
|
| 497 |
<p> |
| 498 |
After a backslash, certain single-character escapes represent special values: |
| 499 |
</p> |
| 500 |
|
| 501 |
<pre class="grammar"> |
| 502 |
\a U+0007 alert or bell |
| 503 |
\b U+0008 backspace |
| 504 |
\f U+000C form feed |
| 505 |
\n U+000A line feed or newline |
| 506 |
\r U+000D carriage return |
| 507 |
\t U+0009 horizontal tab |
| 508 |
\v U+000B vertical tab |
| 509 |
\\ U+005C backslash |
| 510 |
\' 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> |
| 515 |
An unrecognized character following a backslash in a rune literal is illegal. |
| 516 |
</p> |
| 517 |
|
| 518 |
<pre class="ebnf"> |
| 519 |
rune_lit = "'" ( unicode_value | byte_value ) "'" . |
| 520 |
unicode_value = unicode_char | little_u_value | big_u_value | escaped_char . |
| 521 |
byte_value = octal_byte_value | hex_byte_value . |
| 522 |
octal_byte_value = `\` octal_digit octal_digit octal_digit . |
| 523 |
hex_byte_value = `\` "x" hex_digit hex_digit . |
| 524 |
little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit . |
| 525 |
big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit |
| 526 |
hex_digit hex_digit hex_digit hex_digit . |
| 527 |
escaped_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 character |
| 543 |
'aa' // illegal: too many characters |
| 544 |
'\k' // illegal: k is not recognized after a backslash |
| 545 |
'\xa' // illegal: too few hexadecimal digits |
| 546 |
'\0' // illegal: too few octal digits |
| 547 |
'\400' // illegal: octal value over 255 |
| 548 |
'\uDFFF' // illegal: surrogate half |
| 549 |
'\U00110000' // illegal: invalid Unicode code point |
| 550 |
</pre> |
| 551 |
|
| 552 |
|
| 553 |
<h3 id="String_literals">String literals</h3> |
| 554 |
|
| 555 |
<p> |
| 556 |
A string literal represents a <a href="#Constants">string constant</a> |
| 557 |
obtained from concatenating a sequence of characters. There are two forms: |
| 558 |
raw string literals and interpreted string literals. |
| 559 |
</p> |
| 560 |
|
| 561 |
<p> |
| 562 |
Raw string literals are character sequences between back quotes, as in |
| 563 |
<code>`foo`</code>. Within the quotes, any character may appear except |
| 564 |
back quote. The value of a raw string literal is the |
| 565 |
string composed of the uninterpreted (implicitly UTF-8-encoded) characters |
| 566 |
between the quotes; |
| 567 |
in particular, backslashes have no special meaning and the string may |
| 568 |
contain newlines. |
| 569 |
Carriage return characters ('\r') inside raw string literals |
| 570 |
are discarded from the raw string value. |
| 571 |
</p> |
| 572 |
|
| 573 |
<p> |
| 574 |
Interpreted string literals are character sequences between double |
| 575 |
quotes, as in <code>"bar"</code>. |
| 576 |
Within the quotes, any character may appear except newline and unescaped double quote. |
| 577 |
The text between the quotes forms the |
| 578 |
value of the literal, with backslash escapes interpreted as they |
| 579 |
are in <a href="#Rune_literals">rune literals</a> (except that <code>\'</code> is illegal and |
| 580 |
<code>\"</code> is legal), with the same restrictions. |
| 581 |
The three-digit octal (<code>\</code><i>nnn</i>) |
| 582 |
and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual |
| 583 |
<i>bytes</i> of the resulting string; all other escapes represent |
| 584 |
the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>. |
| 585 |
Thus inside a string literal <code>\377</code> and <code>\xFF</code> represent |
| 586 |
a single byte of value <code>0xFF</code>=255, while <code>ÿ</code>, |
| 587 |
<code>\u00FF</code>, <code>\U000000FF</code> and <code>\xc3\xbf</code> represent |
| 588 |
the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character |
| 589 |
U+00FF. |
| 590 |
</p> |
| 591 |
|
| 592 |
<pre class="ebnf"> |
| 593 |
string_lit = raw_string_lit | interpreted_string_lit . |
| 594 |
raw_string_lit = "`" { unicode_char | newline } "`" . |
| 595 |
interpreted_string_lit = `"` { unicode_value | byte_value } `"` . |
| 596 |
</pre> |
| 597 |
|
| 598 |
<pre> |
| 599 |
`abc` // same as "abc" |
| 600 |
`\n |
| 601 |
\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 half |
| 609 |
"\U00110000" // illegal: invalid Unicode code point |
| 610 |
</pre> |
| 611 |
|
| 612 |
<p> |
| 613 |
These examples all represent the same string: |
| 614 |
</p> |
| 615 |
|
| 616 |
<pre> |
| 617 |
"日本語" // UTF-8 input text |
| 618 |
`日本語` // UTF-8 input text as a raw literal |
| 619 |
"\u65e5\u672c\u8a9e" // the explicit Unicode code points |
| 620 |
"\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points |
| 621 |
"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes |
| 622 |
</pre> |
| 623 |
|
| 624 |
<p> |
| 625 |
If the source code represents a character as two code points, such as |
| 626 |
a combining form involving an accent and a letter, the result will be |
| 627 |
an error if placed in a rune literal (it is not a single code |
| 628 |
point), and will appear as two code points if placed in a string |
| 629 |
literal. |
| 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>, |
| 639 |
and <i>string constants</i>. Rune, integer, floating-point, |
| 640 |
and complex constants are |
| 641 |
collectively called <i>numeric constants</i>. |
| 642 |
</p> |
| 643 |
|
| 644 |
<p> |
| 645 |
A constant value is represented by a |
| 646 |
<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>, |
| 650 |
or |
| 651 |
<a href="#String_literals">string</a> literal, |
| 652 |
an identifier denoting a constant, |
| 653 |
a <a href="#Constant_expressions">constant expression</a>, |
| 654 |
a <a href="#Conversions">conversion</a> with a result that is a constant, or |
| 655 |
the result value of some built-in functions such as |
| 656 |
<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 to |
| 659 |
<a href="#Length_and_capacity">some expressions</a>, |
| 660 |
<code>real</code> and <code>imag</code> applied to a complex constant |
| 661 |
and <code>complex</code> applied to numeric constants. |
| 662 |
The boolean truth values are represented by the predeclared constants |
| 663 |
<code>true</code> and <code>false</code>. The predeclared identifier |
| 664 |
<a href="#Iota">iota</a> denotes an integer constant. |
| 665 |
</p> |
| 666 |
|
| 667 |
<p> |
| 668 |
In general, complex constants are a form of |
| 669 |
<a href="#Constant_expressions">constant expression</a> |
| 670 |
and are discussed in that section. |
| 671 |
</p> |
| 672 |
|
| 673 |
<p> |
| 674 |
Numeric constants represent exact values of arbitrary precision and do not overflow. |
| 675 |
Consequently, there are no constants denoting the IEEE 754 negative zero, infinity, |
| 676 |
and not-a-number values. |
| 677 |
</p> |
| 678 |
|
| 679 |
<p> |
| 680 |
Constants may be <a href="#Types">typed</a> or <i>untyped</i>. |
| 681 |
Literal constants, <code>true</code>, <code>false</code>, <code>iota</code>, |
| 682 |
and certain <a href="#Constant_expressions">constant expressions</a> |
| 683 |
containing only untyped constant operands are untyped. |
| 684 |
</p> |
| 685 |
|
| 686 |
<p> |
| 687 |
A constant may be given a type explicitly by a <a href="#Constant_declarations">constant declaration</a> |
| 688 |
or <a href="#Conversions">conversion</a>, or implicitly when used in a |
| 689 |
<a href="#Variable_declarations">variable declaration</a> or an |
| 690 |
<a href="#Assignment_statements">assignment statement</a> or as an |
| 691 |
operand in an <a href="#Expressions">expression</a>. |
| 692 |
It is an error if the constant value |
| 693 |
cannot be <a href="#Representability">represented</a> as a value of the respective type. |
| 694 |
If the type is a type parameter, the constant is converted into a non-constant |
| 695 |
value of the type parameter. |
| 696 |
</p> |
| 697 |
|
| 698 |
<p> |
| 699 |
An untyped constant has a <i>default type</i> which is the type to which the |
| 700 |
constant is implicitly converted in contexts where a typed value is required, |
| 701 |
for instance, in a <a href="#Short_variable_declarations">short variable declaration</a> |
| 702 |
such as <code>i := 0</code> where there is no explicit type. |
| 703 |
The 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> |
| 705 |
respectively, depending on whether it is a boolean, rune, integer, floating-point, |
| 706 |
complex, or string constant. |
| 707 |
</p> |
| 708 |
|
| 709 |
<p> |
| 710 |
Implementation restriction: Although numeric constants have arbitrary |
| 711 |
precision in the language, a compiler may implement them using an |
| 712 |
internal representation with limited precision. That said, every |
| 713 |
implementation 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 of |
| 720 |
a complex constant, with a mantissa of at least 256 bits |
| 721 |
and a signed binary exponent of at least 16 bits.</li> |
| 722 |
|
| 723 |
<li>Give an error if unable to represent an integer constant |
| 724 |
precisely.</li> |
| 725 |
|
| 726 |
<li>Give an error if unable to represent a floating-point or |
| 727 |
complex constant due to overflow.</li> |
| 728 |
|
| 729 |
<li>Round to the nearest representable constant if unable to |
| 730 |
represent a floating-point or complex constant due to limits |
| 731 |
on precision.</li> |
| 732 |
</ul> |
| 733 |
|
| 734 |
<p> |
| 735 |
These requirements apply both to literal constants and to the result |
| 736 |
of evaluating <a href="#Constant_expressions">constant |
| 737 |
expressions</a>. |
| 738 |
</p> |
| 739 |
|
| 740 |
|
| 741 |
<h2 id="Variables">Variables</h2> |
| 742 |
|
| 743 |
<p> |
| 744 |
A variable is a storage location for holding a <i>value</i>. |
| 745 |
The set of permissible values is determined by the |
| 746 |
variable's <i><a href="#Types">type</a></i>. |
| 747 |
</p> |
| 748 |
|
| 749 |
<p> |
| 750 |
A <a href="#Variable_declarations">variable declaration</a> |
| 751 |
or, for function parameters and results, the signature |
| 752 |
of a <a href="#Function_declarations">function declaration</a> |
| 753 |
or <a href="#Function_literals">function literal</a> reserves |
| 754 |
storage for a named variable. |
| 755 |
|
| 756 |
Calling the built-in function <a href="#Allocation"><code>new</code></a> |
| 757 |
or taking the address of a <a href="#Composite_literals">composite literal</a> |
| 758 |
allocates storage for a variable at run time. |
| 759 |
Such 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>, |
| 765 |
and <a href="#Struct_types">struct</a> types have elements and fields that may |
| 766 |
be <a href="#Address_operators">addressed</a> individually. Each such element |
| 767 |
acts like a variable. |
| 768 |
</p> |
| 769 |
|
| 770 |
<p> |
| 771 |
The <i>static type</i> (or just <i>type</i>) of a variable is the |
| 772 |
type given in its declaration, the type provided in the |
| 773 |
<code>new</code> call or composite literal, or the type of |
| 774 |
an element of a structured variable. |
| 775 |
Variables of interface type also have a distinct <i>dynamic type</i>, |
| 776 |
which is the (non-interface) type of the value assigned to the variable at run time |
| 777 |
(unless the value is the predeclared identifier <code>nil</code>, |
| 778 |
which has no type). |
| 779 |
The dynamic type may vary during execution but values stored in interface |
| 780 |
variables are always <a href="#Assignability">assignable</a> |
| 781 |
to the static type of the variable. |
| 782 |
</p> |
| 783 |
|
| 784 |
<pre> |
| 785 |
var x interface{} // x is nil and has static type interface{} |
| 786 |
var v *T // v has value nil, static type *T |
| 787 |
x = 42 // x has value 42 and dynamic type int |
| 788 |
x = v // x has value (*T)(nil) and dynamic type *T |
| 789 |
</pre> |
| 790 |
|
| 791 |
<p> |
| 792 |
A variable's value is retrieved by referring to the variable in an |
| 793 |
<a href="#Expressions">expression</a>; it is the most recent value |
| 794 |
<a href="#Assignment_statements">assigned</a> to the variable. |
| 795 |
If a variable has not yet been assigned a value, its value is the |
| 796 |
<a href="#The_zero_value">zero value</a> for its type. |
| 797 |
</p> |
| 798 |
|
| 799 |
<h2 id="Types">Types</h2> |
| 800 |
|
| 801 |
<p> |
| 802 |
A type determines a set of values together with operations and methods specific |
| 803 |
to those values. A type may be denoted by a <i>type name</i>, if it has one, which must be |
| 804 |
followed by <a href="#Instantiations">type arguments</a> if the type is generic. |
| 805 |
A type may also be specified using a <i>type literal</i>, which composes a type |
| 806 |
from existing types. |
| 807 |
</p> |
| 808 |
|
| 809 |
<pre class="ebnf"> |
| 810 |
Type = TypeName [ TypeArgs ] | TypeLit | "(" Type ")" . |
| 811 |
TypeName = identifier | QualifiedIdent . |
| 812 |
TypeArgs = "[" TypeList [ "," ] "]" . |
| 813 |
TypeList = Type { "," Type } . |
| 814 |
TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType | |
| 815 |
SliceType | MapType | ChannelType . |
| 816 |
</pre> |
| 817 |
|
| 818 |
<p> |
| 819 |
The language <a href="#Predeclared_identifiers">predeclares</a> certain type names. |
| 820 |
Others are introduced with <a href="#Type_declarations">type declarations</a> |
| 821 |
or <a href="#Type_parameter_declarations">type parameter lists</a>. |
| 822 |
<i>Composite types</i>—array, struct, pointer, function, |
| 823 |
interface, slice, map, and channel types—may be constructed using |
| 824 |
type literals. |
| 825 |
</p> |
| 826 |
|
| 827 |
<p> |
| 828 |
Predeclared types, defined types, and type parameters are called <i>named types</i>. |
| 829 |
An 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> |
| 835 |
A <i>boolean type</i> represents the set of Boolean truth values |
| 836 |
denoted by the predeclared constants <code>true</code> |
| 837 |
and <code>false</code>. The predeclared boolean type is <code>bool</code>; |
| 838 |
it is a <a href="#Type_definitions">defined type</a>. |
| 839 |
</p> |
| 840 |
|
| 841 |
<h3 id="Numeric_types">Numeric types</h3> |
| 842 |
|
| 843 |
<p> |
| 844 |
An <i>integer</i>, <i>floating-point</i>, or <i>complex</i> type |
| 845 |
represents the set of integer, floating-point, or complex values, respectively. |
| 846 |
They are collectively called <i>numeric types</i>. |
| 847 |
The predeclared architecture-independent numeric types are: |
| 848 |
</p> |
| 849 |
|
| 850 |
<pre class="grammar"> |
| 851 |
uint8 the set of all unsigned 8-bit integers (0 to 255) |
| 852 |
uint16 the set of all unsigned 16-bit integers (0 to 65535) |
| 853 |
uint32 the set of all unsigned 32-bit integers (0 to 4294967295) |
| 854 |
uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615) |
| 855 |
|
| 856 |
int8 the set of all signed 8-bit integers (-128 to 127) |
| 857 |
int16 the set of all signed 16-bit integers (-32768 to 32767) |
| 858 |
int32 the set of all signed 32-bit integers (-2147483648 to 2147483647) |
| 859 |
int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807) |
| 860 |
|
| 861 |
float32 the set of all IEEE 754 32-bit floating-point numbers |
| 862 |
float64 the set of all IEEE 754 64-bit floating-point numbers |
| 863 |
|
| 864 |
complex64 the set of all complex numbers with float32 real and imaginary parts |
| 865 |
complex128 the set of all complex numbers with float64 real and imaginary parts |
| 866 |
|
| 867 |
byte alias for uint8 |
| 868 |
rune alias for int32 |
| 869 |
</pre> |
| 870 |
|
| 871 |
<p> |
| 872 |
The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using |
| 873 |
<a href="https://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>. |
| 874 |
</p> |
| 875 |
|
| 876 |
<p> |
| 877 |
There is also a set of predeclared integer types with implementation-specific sizes: |
| 878 |
</p> |
| 879 |
|
| 880 |
<pre class="grammar"> |
| 881 |
uint either 32 or 64 bits |
| 882 |
int same size as uint |
| 883 |
uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value |
| 884 |
</pre> |
| 885 |
|
| 886 |
<p> |
| 887 |
To avoid portability issues all numeric types are <a href="#Type_definitions">defined |
| 888 |
types</a> and thus distinct except |
| 889 |
<code>byte</code>, which is an <a href="#Alias_declarations">alias</a> for <code>uint8</code>, and |
| 890 |
<code>rune</code>, which is an alias for <code>int32</code>. |
| 891 |
Explicit conversions |
| 892 |
are required when different numeric types are mixed in an expression |
| 893 |
or assignment. For instance, <code>int32</code> and <code>int</code> |
| 894 |
are not the same type even though they may have the same size on a |
| 895 |
particular architecture. |
| 896 |
</p> |
| 897 |
|
| 898 |
<h3 id="String_types">String types</h3> |
| 899 |
|
| 900 |
<p> |
| 901 |
A <i>string type</i> represents the set of string values. |
| 902 |
A string value is a (possibly empty) sequence of bytes. |
| 903 |
The number of bytes is called the length of the string and is never negative. |
| 904 |
Strings are immutable: once created, |
| 905 |
it is impossible to change the contents of a string. |
| 906 |
The predeclared string type is <code>string</code>; |
| 907 |
it is a <a href="#Type_definitions">defined type</a>. |
| 908 |
</p> |
| 909 |
|
| 910 |
<p> |
| 911 |
The length of a string <code>s</code> can be discovered using |
| 912 |
the built-in function <a href="#Length_and_capacity"><code>len</code></a>. |
| 913 |
The length is a compile-time constant if the string is a constant. |
| 914 |
A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a> |
| 915 |
0 through <code>len(s)-1</code>. |
| 916 |
It is illegal to take the address of such an element; if |
| 917 |
<code>s[i]</code> is the <code>i</code>'th byte of a |
| 918 |
string, <code>&s[i]</code> is invalid. |
| 919 |
</p> |
| 920 |
|
| 921 |
|
| 922 |
<h3 id="Array_types">Array types</h3> |
| 923 |
|
| 924 |
<p> |
| 925 |
An array is a numbered sequence of elements of a single |
| 926 |
type, called the element type. |
| 927 |
The number of elements is called the length of the array and is never negative. |
| 928 |
</p> |
| 929 |
|
| 930 |
<pre class="ebnf"> |
| 931 |
ArrayType = "[" ArrayLength "]" ElementType . |
| 932 |
ArrayLength = Expression . |
| 933 |
ElementType = Type . |
| 934 |
</pre> |
| 935 |
|
| 936 |
<p> |
| 937 |
The length is part of the array's type; it must evaluate to a |
| 938 |
non-negative <a href="#Constants">constant</a> |
| 939 |
<a href="#Representability">representable</a> by a value |
| 940 |
of type <code>int</code>. |
| 941 |
The length of array <code>a</code> can be discovered |
| 942 |
using the built-in function <a href="#Length_and_capacity"><code>len</code></a>. |
| 943 |
The elements can be addressed by integer <a href="#Index_expressions">indices</a> |
| 944 |
0 through <code>len(a)-1</code>. |
| 945 |
Array types are always one-dimensional but may be composed to form |
| 946 |
multi-dimensional types. |
| 947 |
</p> |
| 948 |
|
| 949 |
<pre> |
| 950 |
[32]byte |
| 951 |
[2*N] struct { x, y int32 } |
| 952 |
[1000]*float64 |
| 953 |
[3][5]int |
| 954 |
[2][2][2]float64 // same as [2]([2]([2]float64)) |
| 955 |
</pre> |
| 956 |
|
| 957 |
<p> |
| 958 |
An array type <code>T</code> may not have an element of type <code>T</code>, |
| 959 |
or of a type containing <code>T</code> as a component, directly or indirectly, |
| 960 |
if those containing types are only array or struct types. |
| 961 |
</p> |
| 962 |
|
| 963 |
<pre> |
| 964 |
// invalid array types |
| 965 |
type ( |
| 966 |
T1 [10]T1 // element type of T1 is T1 |
| 967 |
T2 [10]struct{ f T2 } // T2 contains T2 as component of a struct |
| 968 |
T3 [10]T4 // T3 contains T3 as component of a struct in T4 |
| 969 |
T4 struct{ f T3 } // T4 contains T4 as component of array T3 in a struct |
| 970 |
) |
| 971 |
|
| 972 |
// valid array types |
| 973 |
type ( |
| 974 |
T5 [10]*T5 // T5 contains T5 as component of a pointer |
| 975 |
T6 [10]func() T6 // T6 contains T6 as component of a function type |
| 976 |
T7 [10]struct{ f []T7 } // T7 contains T7 as component of a slice in a struct |
| 977 |
) |
| 978 |
</pre> |
| 979 |
|
| 980 |
<h3 id="Slice_types">Slice types</h3> |
| 981 |
|
| 982 |
<p> |
| 983 |
A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and |
| 984 |
provides access to a numbered sequence of elements from that array. |
| 985 |
A slice type denotes the set of all slices of arrays of its element type. |
| 986 |
The number of elements is called the length of the slice and is never negative. |
| 987 |
The value of an uninitialized slice is <code>nil</code>. |
| 988 |
</p> |
| 989 |
|
| 990 |
<pre class="ebnf"> |
| 991 |
SliceType = "[" "]" ElementType . |
| 992 |
</pre> |
| 993 |
|
| 994 |
<p> |
| 995 |
The length of a slice <code>s</code> can be discovered by the built-in function |
| 996 |
<a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during |
| 997 |
execution. The elements can be addressed by integer <a href="#Index_expressions">indices</a> |
| 998 |
0 through <code>len(s)-1</code>. The slice index of a |
| 999 |
given element may be less than the index of the same element in the |
| 1000 |
underlying array. |
| 1001 |
</p> |
| 1002 |
<p> |
| 1003 |
A slice, once initialized, is always associated with an underlying |
| 1004 |
array that holds its elements. A slice therefore shares storage |
| 1005 |
with its array and with other slices of the same array; by contrast, |
| 1006 |
distinct arrays always represent distinct storage. |
| 1007 |
</p> |
| 1008 |
<p> |
| 1009 |
The array underlying a slice may extend past the end of the slice. |
| 1010 |
The <i>capacity</i> is a measure of that extent: it is the sum of |
| 1011 |
the length of the slice and the length of the array beyond the slice; |
| 1012 |
a slice of length up to that capacity can be created by |
| 1013 |
<a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice. |
| 1014 |
The capacity of a slice <code>a</code> can be discovered using the |
| 1015 |
built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>. |
| 1016 |
</p> |
| 1017 |
|
| 1018 |
<p> |
| 1019 |
A new, initialized slice value for a given element type <code>T</code> may be |
| 1020 |
made using the built-in function |
| 1021 |
<a href="#Making_slices_maps_and_channels"><code>make</code></a>, |
| 1022 |
which takes a slice type |
| 1023 |
and parameters specifying the length and optionally the capacity. |
| 1024 |
A slice created with <code>make</code> always allocates a new, hidden array |
| 1025 |
to which the returned slice value refers. That is, executing |
| 1026 |
</p> |
| 1027 |
|
| 1028 |
<pre> |
| 1029 |
make([]T, length, capacity) |
| 1030 |
</pre> |
| 1031 |
|
| 1032 |
<p> |
| 1033 |
produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a> |
| 1034 |
it, so these two expressions are equivalent: |
| 1035 |
</p> |
| 1036 |
|
| 1037 |
<pre> |
| 1038 |
make([]int, 50, 100) |
| 1039 |
new([100]int)[0:50] |
| 1040 |
</pre> |
| 1041 |
|
| 1042 |
<p> |
| 1043 |
Like arrays, slices are always one-dimensional but may be composed to construct |
| 1044 |
higher-dimensional objects. |
| 1045 |
With arrays of arrays, the inner arrays are, by construction, always the same length; |
| 1046 |
however with slices of slices (or arrays of slices), the inner lengths may vary dynamically. |
| 1047 |
Moreover, the inner slices must be initialized individually. |
| 1048 |
</p> |
| 1049 |
|
| 1050 |
<h3 id="Struct_types">Struct types</h3> |
| 1051 |
|
| 1052 |
<p> |
| 1053 |
A struct is a sequence of named elements, called fields, each of which has a |
| 1054 |
name and a type. Field names may be specified explicitly (IdentifierList) or |
| 1055 |
implicitly (EmbeddedField). |
| 1056 |
Within a struct, non-<a href="#Blank_identifier">blank</a> field names must |
| 1057 |
be <a href="#Uniqueness_of_identifiers">unique</a>. |
| 1058 |
</p> |
| 1059 |
|
| 1060 |
<pre class="ebnf"> |
| 1061 |
StructType = "struct" "{" { FieldDecl ";" } "}" . |
| 1062 |
FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] . |
| 1063 |
EmbeddedField = [ "*" ] TypeName [ TypeArgs ] . |
| 1064 |
Tag = string_lit . |
| 1065 |
</pre> |
| 1066 |
|
| 1067 |
<pre> |
| 1068 |
// An empty struct. |
| 1069 |
struct {} |
| 1070 |
|
| 1071 |
// A struct with 6 fields. |
| 1072 |
struct { |
| 1073 |
x, y int |
| 1074 |
u float32 |
| 1075 |
_ float32 // padding |
| 1076 |
A *[]int |
| 1077 |
F func() |
| 1078 |
} |
| 1079 |
</pre> |
| 1080 |
|
| 1081 |
<p> |
| 1082 |
A field declared with a type but no explicit field name is called an <i>embedded field</i>. |
| 1083 |
An embedded field must be specified as |
| 1084 |
a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>, |
| 1085 |
and <code>T</code> itself may not be |
| 1086 |
a 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.T4 |
| 1091 |
struct { |
| 1092 |
T1 // field name is T1 |
| 1093 |
*T2 // field name is T2 |
| 1094 |
P.T3 // field name is T3 |
| 1095 |
*P.T4 // field name is T4 |
| 1096 |
x, y int // field names are x and y |
| 1097 |
} |
| 1098 |
</pre> |
| 1099 |
|
| 1100 |
<p> |
| 1101 |
The following declaration is illegal because field names must be unique |
| 1102 |
in a struct type: |
| 1103 |
</p> |
| 1104 |
|
| 1105 |
<pre> |
| 1106 |
struct { |
| 1107 |
T // conflicts with embedded field *T and *P.T |
| 1108 |
*T // conflicts with embedded field T and *P.T |
| 1109 |
*P.T // conflicts with embedded field T and *T |
| 1110 |
} |
| 1111 |
</pre> |
| 1112 |
|
| 1113 |
<p> |
| 1114 |
A field or <a href="#Method_declarations">method</a> <code>f</code> of an |
| 1115 |
embedded field in a struct <code>x</code> is called <i>promoted</i> if |
| 1116 |
<code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes |
| 1117 |
that field or method <code>f</code>. |
| 1118 |
</p> |
| 1119 |
|
| 1120 |
<p> |
| 1121 |
Promoted fields act like ordinary fields |
| 1122 |
of a struct except that they cannot be used as field names in |
| 1123 |
<a href="#Composite_literals">composite literals</a> of the struct. |
| 1124 |
</p> |
| 1125 |
|
| 1126 |
<p> |
| 1127 |
Given a struct type <code>S</code> and a type name |
| 1128 |
<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 receiver |
| 1135 |
<code>T</code>. The method set of <code>*S</code> also |
| 1136 |
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> both |
| 1142 |
include promoted methods with receiver <code>T</code> or |
| 1143 |
<code>*T</code>. |
| 1144 |
</li> |
| 1145 |
</ul> |
| 1146 |
|
| 1147 |
<p> |
| 1148 |
A field declaration may be followed by an optional string literal <i>tag</i>, |
| 1149 |
which becomes an attribute for all the fields in the corresponding |
| 1150 |
field declaration. An empty tag string is equivalent to an absent tag. |
| 1151 |
The tags are made visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a> |
| 1152 |
and take part in <a href="#Type_identity">type identity</a> for structs |
| 1153 |
but are otherwise ignored. |
| 1154 |
</p> |
| 1155 |
|
| 1156 |
<pre> |
| 1157 |
struct { |
| 1158 |
x, y float64 "" // an empty tag string is like an absent tag |
| 1159 |
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. |
| 1166 |
struct { |
| 1167 |
microsec uint64 `protobuf:"1"` |
| 1168 |
serverIP6 uint64 `protobuf:"2"` |
| 1169 |
} |
| 1170 |
</pre> |
| 1171 |
|
| 1172 |
<p> |
| 1173 |
A struct type <code>T</code> may not contain a field of type <code>T</code>, |
| 1174 |
or of a type containing <code>T</code> as a component, directly or indirectly, |
| 1175 |
if those containing types are only array or struct types. |
| 1176 |
</p> |
| 1177 |
|
| 1178 |
<pre> |
| 1179 |
// invalid struct types |
| 1180 |
type ( |
| 1181 |
T1 struct{ T1 } // T1 contains a field of T1 |
| 1182 |
T2 struct{ f [10]T2 } // T2 contains T2 as component of an array |
| 1183 |
T3 struct{ T4 } // T3 contains T3 as component of an array in struct T4 |
| 1184 |
T4 struct{ f [10]T3 } // T4 contains T4 as component of struct T3 in an array |
| 1185 |
) |
| 1186 |
|
| 1187 |
// valid struct types |
| 1188 |
type ( |
| 1189 |
T5 struct{ f *T5 } // T5 contains T5 as component of a pointer |
| 1190 |
T6 struct{ f func() T6 } // T6 contains T6 as component of a function type |
| 1191 |
T7 struct{ f [10][]T7 } // T7 contains T7 as component of a slice in an array |
| 1192 |
) |
| 1193 |
</pre> |
| 1194 |
|
| 1195 |
<h3 id="Pointer_types">Pointer types</h3> |
| 1196 |
|
| 1197 |
<p> |
| 1198 |
A pointer type denotes the set of all pointers to <a href="#Variables">variables</a> of a given |
| 1199 |
type, called the <i>base type</i> of the pointer. |
| 1200 |
The <a href="#Representation_of_values">value</a> of an uninitialized pointer is <code>nil</code>. |
| 1201 |
</p> |
| 1202 |
|
| 1203 |
<pre class="ebnf"> |
| 1204 |
PointerType = "*" BaseType . |
| 1205 |
BaseType = Type . |
| 1206 |
</pre> |
| 1207 |
|
| 1208 |
<pre> |
| 1209 |
*Point |
| 1210 |
*[4]int |
| 1211 |
</pre> |
| 1212 |
|
| 1213 |
<h3 id="Function_types">Function types</h3> |
| 1214 |
|
| 1215 |
<p> |
| 1216 |
A function type denotes the set of all functions with the same parameter and result types. |
| 1217 |
The <a href="#Representation_of_values">value</a> of an uninitialized variable of function |
| 1218 |
type is <code>nil</code>. |
| 1219 |
</p> |
| 1220 |
|
| 1221 |
<pre class="ebnf"> |
| 1222 |
FunctionType = "func" Signature . |
| 1223 |
Signature = Parameters [ Result ] . |
| 1224 |
Result = Parameters | Type . |
| 1225 |
Parameters = "(" [ ParameterList [ "," ] ] ")" . |
| 1226 |
ParameterList = ParameterDecl { "," ParameterDecl } . |
| 1227 |
ParameterDecl = [ IdentifierList ] [ "..." ] Type . |
| 1228 |
</pre> |
| 1229 |
|
| 1230 |
<p> |
| 1231 |
Within a list of parameters or results, the names (IdentifierList) |
| 1232 |
must either all be present or all be absent. If present, each name |
| 1233 |
stands for one item (parameter or result) of the specified type and |
| 1234 |
all non-<a href="#Blank_identifier">blank</a> names in the signature |
| 1235 |
must be <a href="#Uniqueness_of_identifiers">unique</a>. |
| 1236 |
If absent, each type stands for one item of that type. |
| 1237 |
Parameter and result |
| 1238 |
lists are always parenthesized except that if there is exactly |
| 1239 |
one unnamed result it may be written as an unparenthesized type. |
| 1240 |
</p> |
| 1241 |
|
| 1242 |
<p> |
| 1243 |
The final incoming parameter in a function signature may have |
| 1244 |
a type prefixed with <code>...</code>. |
| 1245 |
A function with such a parameter is called <i>variadic</i> and |
| 1246 |
may be invoked with zero or more arguments for that parameter. |
| 1247 |
</p> |
| 1248 |
|
| 1249 |
<pre> |
| 1250 |
func() |
| 1251 |
func(x int) int |
| 1252 |
func(a, _ int, z float32) bool |
| 1253 |
func(a, b int, z float32) (bool) |
| 1254 |
func(prefix string, values ...int) |
| 1255 |
func(a, b int, z float64, opt ...interface{}) (success bool) |
| 1256 |
func(int, int, float64) (float64, *[]int) |
| 1257 |
func(n int) func(p *T) |
| 1258 |
</pre> |
| 1259 |
|
| 1260 |
<h3 id="Interface_types">Interface types</h3> |
| 1261 |
|
| 1262 |
<p> |
| 1263 |
An interface type defines a <i>type set</i>. |
| 1264 |
A variable of interface type can store a value of any type that is in the type |
| 1265 |
set of the interface. Such a type is said to |
| 1266 |
<a href="#Implementing_an_interface">implement the interface</a>. |
| 1267 |
The <a href="#Representation_of_values">value</a> of an uninitialized variable of |
| 1268 |
interface type is <code>nil</code>. |
| 1269 |
</p> |
| 1270 |
|
| 1271 |
<pre class="ebnf"> |
| 1272 |
InterfaceType = "interface" "{" { InterfaceElem ";" } "}" . |
| 1273 |
InterfaceElem = MethodElem | TypeElem . |
| 1274 |
MethodElem = MethodName Signature . |
| 1275 |
MethodName = identifier . |
| 1276 |
TypeElem = TypeTerm { "|" TypeTerm } . |
| 1277 |
TypeTerm = Type | UnderlyingType . |
| 1278 |
UnderlyingType = "~" Type . |
| 1279 |
</pre> |
| 1280 |
|
| 1281 |
<p> |
| 1282 |
An interface type is specified by a list of <i>interface elements</i>. |
| 1283 |
An interface element is either a <i>method</i> or a <i>type element</i>, |
| 1284 |
where a type element is a union of one or more <i>type terms</i>. |
| 1285 |
A type term is either a single type or a single underlying type. |
| 1286 |
</p> |
| 1287 |
|
| 1288 |
<h4 id="Basic_interfaces">Basic interfaces</h4> |
| 1289 |
|
| 1290 |
<p> |
| 1291 |
In its most basic form an interface specifies a (possibly empty) list of methods. |
| 1292 |
The type set defined by such an interface is the set of types which implement all of |
| 1293 |
those methods, and the corresponding <a href="#Method_sets">method set</a> consists |
| 1294 |
exactly of the methods specified by the interface. |
| 1295 |
Interfaces whose type sets can be defined entirely by a list of methods are called |
| 1296 |
<i>basic interfaces.</i> |
| 1297 |
</p> |
| 1298 |
|
| 1299 |
<pre> |
| 1300 |
// A simple File interface. |
| 1301 |
interface { |
| 1302 |
Read([]byte) (int, error) |
| 1303 |
Write([]byte) (int, error) |
| 1304 |
Close() error |
| 1305 |
} |
| 1306 |
</pre> |
| 1307 |
|
| 1308 |
<p> |
| 1309 |
The name of each explicitly specified method must be <a href="#Uniqueness_of_identifiers">unique</a> |
| 1310 |
and not <a href="#Blank_identifier">blank</a>. |
| 1311 |
</p> |
| 1312 |
|
| 1313 |
<pre> |
| 1314 |
interface { |
| 1315 |
String() string |
| 1316 |
String() string // illegal: String not unique |
| 1317 |
_(x int) // illegal: method must have non-blank name |
| 1318 |
} |
| 1319 |
</pre> |
| 1320 |
|
| 1321 |
<p> |
| 1322 |
More than one type may implement an interface. |
| 1323 |
For instance, if two types <code>S1</code> and <code>S2</code> |
| 1324 |
have the method set |
| 1325 |
</p> |
| 1326 |
|
| 1327 |
<pre> |
| 1328 |
func (p T) Read(p []byte) (n int, err error) |
| 1329 |
func (p T) Write(p []byte) (n int, err error) |
| 1330 |
func (p T) Close() error |
| 1331 |
</pre> |
| 1332 |
|
| 1333 |
<p> |
| 1334 |
(where <code>T</code> stands for either <code>S1</code> or <code>S2</code>) |
| 1335 |
then the <code>File</code> interface is implemented by both <code>S1</code> and |
| 1336 |
<code>S2</code>, regardless of what other methods |
| 1337 |
<code>S1</code> and <code>S2</code> may have or share. |
| 1338 |
</p> |
| 1339 |
|
| 1340 |
<p> |
| 1341 |
Every type that is a member of the type set of an interface implements that interface. |
| 1342 |
Any given type may implement several distinct interfaces. |
| 1343 |
For instance, all types implement the <i>empty interface</i> which stands for the set |
| 1344 |
of all (non-interface) types: |
| 1345 |
</p> |
| 1346 |
|
| 1347 |
<pre> |
| 1348 |
interface{} |
| 1349 |
</pre> |
| 1350 |
|
| 1351 |
<p> |
| 1352 |
For convenience, the predeclared type <code>any</code> is an alias for the empty interface. |
| 1353 |
[<a href="#Go_1.18">Go 1.18</a>] |
| 1354 |
</p> |
| 1355 |
|
| 1356 |
<p> |
| 1357 |
Similarly, consider this interface specification, |
| 1358 |
which appears within a <a href="#Type_declarations">type declaration</a> |
| 1359 |
to define an interface called <code>Locker</code>: |
| 1360 |
</p> |
| 1361 |
|
| 1362 |
<pre> |
| 1363 |
type Locker interface { |
| 1364 |
Lock() |
| 1365 |
Unlock() |
| 1366 |
} |
| 1367 |
</pre> |
| 1368 |
|
| 1369 |
<p> |
| 1370 |
If <code>S1</code> and <code>S2</code> also implement |
| 1371 |
</p> |
| 1372 |
|
| 1373 |
<pre> |
| 1374 |
func (p T) Lock() { … } |
| 1375 |
func (p T) Unlock() { … } |
| 1376 |
</pre> |
| 1377 |
|
| 1378 |
<p> |
| 1379 |
they implement the <code>Locker</code> interface as well |
| 1380 |
as the <code>File</code> interface. |
| 1381 |
</p> |
| 1382 |
|
| 1383 |
<h4 id="Embedded_interfaces">Embedded interfaces</h4> |
| 1384 |
|
| 1385 |
<p> |
| 1386 |
In a slightly more general form |
| 1387 |
an interface <code>T</code> may use a (possibly qualified) interface type |
| 1388 |
name <code>E</code> as an interface element. This is called |
| 1389 |
<i>embedding</i> interface <code>E</code> in <code>T</code> |
| 1390 |
[<a href="#Go_1.14">Go 1.14</a>]. |
| 1391 |
The type set of <code>T</code> is the <i>intersection</i> of the type sets |
| 1392 |
defined by <code>T</code>'s explicitly declared methods and the type sets |
| 1393 |
of <code>T</code>’s embedded interfaces. |
| 1394 |
In other words, the type set of <code>T</code> is the set of all types that implement all the |
| 1395 |
explicitly declared methods of <code>T</code> and also all the methods of |
| 1396 |
<code>E</code> |
| 1397 |
[<a href="#Go_1.18">Go 1.18</a>]. |
| 1398 |
</p> |
| 1399 |
|
| 1400 |
<pre> |
| 1401 |
type Reader interface { |
| 1402 |
Read(p []byte) (n int, err error) |
| 1403 |
Close() error |
| 1404 |
} |
| 1405 |
|
| 1406 |
type Writer interface { |
| 1407 |
Write(p []byte) (n int, err error) |
| 1408 |
Close() error |
| 1409 |
} |
| 1410 |
|
| 1411 |
// ReadWriter's methods are Read, Write, and Close. |
| 1412 |
type ReadWriter interface { |
| 1413 |
Reader // includes methods of Reader in ReadWriter's method set |
| 1414 |
Writer // includes methods of Writer in ReadWriter's method set |
| 1415 |
} |
| 1416 |
</pre> |
| 1417 |
|
| 1418 |
<p> |
| 1419 |
When embedding interfaces, methods with the |
| 1420 |
<a href="#Uniqueness_of_identifiers">same</a> names must |
| 1421 |
have <a href="#Type_identity">identical</a> signatures. |
| 1422 |
</p> |
| 1423 |
|
| 1424 |
<pre> |
| 1425 |
type ReadCloser interface { |
| 1426 |
Reader // includes methods of Reader in ReadCloser's method set |
| 1427 |
Close() // illegal: signatures of Reader.Close and Close are different |
| 1428 |
} |
| 1429 |
</pre> |
| 1430 |
|
| 1431 |
<h4 id="General_interfaces">General interfaces</h4> |
| 1432 |
|
| 1433 |
<p> |
| 1434 |
In their most general form, an interface element may also be an arbitrary type term |
| 1435 |
<code>T</code>, or a term of the form <code>~T</code> specifying the underlying type <code>T</code>, |
| 1436 |
or a union of terms <code>t<sub>1</sub>|t<sub>2</sub>|…|t<sub>n</sub></code> |
| 1437 |
[<a href="#Go_1.18">Go 1.18</a>]. |
| 1438 |
Together with method specifications, these elements enable the precise |
| 1439 |
definition of an interface's type set as follows: |
| 1440 |
</p> |
| 1441 |
|
| 1442 |
<ul> |
| 1443 |
<li>The type set of the empty interface is the set of all non-interface types. |
| 1444 |
</li> |
| 1445 |
|
| 1446 |
<li>The type set of a non-empty interface is the intersection of the type sets |
| 1447 |
of its interface elements. |
| 1448 |
</li> |
| 1449 |
|
| 1450 |
<li>The type set of a method specification is the set of all non-interface types |
| 1451 |
whose method sets include that method. |
| 1452 |
</li> |
| 1453 |
|
| 1454 |
<li>The type set of a non-interface type term is the set consisting |
| 1455 |
of just that type. |
| 1456 |
</li> |
| 1457 |
|
| 1458 |
<li>The type set of a term of the form <code>~T</code> |
| 1459 |
is the set of all types whose underlying type is <code>T</code>. |
| 1460 |
</li> |
| 1461 |
|
| 1462 |
<li>The type set of a <i>union</i> of terms |
| 1463 |
<code>t<sub>1</sub>|t<sub>2</sub>|…|t<sub>n</sub></code> |
| 1464 |
is the union of the type sets of the terms. |
| 1465 |
</li> |
| 1466 |
</ul> |
| 1467 |
|
| 1468 |
<p> |
| 1469 |
The quantification "the set of all non-interface types" refers not just to all (non-interface) |
| 1470 |
types declared in the program at hand, but all possible types in all possible programs, and |
| 1471 |
hence is infinite. |
| 1472 |
Similarly, given the set of all non-interface types that implement a particular method, the |
| 1473 |
intersection of the method sets of those types will contain exactly that method, even if all |
| 1474 |
types in the program at hand always pair that method with another method. |
| 1475 |
</p> |
| 1476 |
|
| 1477 |
<p> |
| 1478 |
By construction, an interface's type set never contains an interface type. |
| 1479 |
</p> |
| 1480 |
|
| 1481 |
<pre> |
| 1482 |
// An interface representing only the type int. |
| 1483 |
interface { |
| 1484 |
int |
| 1485 |
} |
| 1486 |
|
| 1487 |
// An interface representing all types with underlying type int. |
| 1488 |
interface { |
| 1489 |
~int |
| 1490 |
} |
| 1491 |
|
| 1492 |
// An interface representing all types with underlying type int that implement the String method. |
| 1493 |
interface { |
| 1494 |
~int |
| 1495 |
String() string |
| 1496 |
} |
| 1497 |
|
| 1498 |
// An interface representing an empty type set: there is no type that is both an int and a string. |
| 1499 |
interface { |
| 1500 |
int |
| 1501 |
string |
| 1502 |
} |
| 1503 |
</pre> |
| 1504 |
|
| 1505 |
<p> |
| 1506 |
In a term of the form <code>~T</code>, the underlying type of <code>T</code> |
| 1507 |
must be itself, and <code>T</code> cannot be an interface. |
| 1508 |
</p> |
| 1509 |
|
| 1510 |
<pre> |
| 1511 |
type MyInt int |
| 1512 |
|
| 1513 |
interface { |
| 1514 |
~[]byte // the underlying type of []byte is itself |
| 1515 |
~MyInt // illegal: the underlying type of MyInt is not MyInt |
| 1516 |
~error // illegal: error is an interface |
| 1517 |
} |
| 1518 |
</pre> |
| 1519 |
|
| 1520 |
<p> |
| 1521 |
Union elements denote unions of type sets: |
| 1522 |
</p> |
| 1523 |
|
| 1524 |
<pre> |
| 1525 |
// The Float interface represents all floating-point types |
| 1526 |
// (including any named types whose underlying types are |
| 1527 |
// either float32 or float64). |
| 1528 |
type Float interface { |
| 1529 |
~float32 | ~float64 |
| 1530 |
} |
| 1531 |
</pre> |
| 1532 |
|
| 1533 |
<p> |
| 1534 |
The type <code>T</code> in a term of the form <code>T</code> or <code>~T</code> cannot |
| 1535 |
be a <a href="#Type_parameter_declarations">type parameter</a>, and the type sets of all |
| 1536 |
non-interface terms must be pairwise disjoint (the pairwise intersection of the type sets must be empty). |
| 1537 |
Given a type parameter <code>P</code>: |
| 1538 |
</p> |
| 1539 |
|
| 1540 |
<pre> |
| 1541 |
interface { |
| 1542 |
P // illegal: P is a type parameter |
| 1543 |
int | ~P // illegal: P is a type parameter |
| 1544 |
~int | MyInt // illegal: the type sets for ~int and MyInt are not disjoint (~int includes MyInt) |
| 1545 |
float32 | Float // overlapping type sets but Float is an interface |
| 1546 |
} |
| 1547 |
</pre> |
| 1548 |
|
| 1549 |
<p> |
| 1550 |
Implementation restriction: |
| 1551 |
A union (with more than one term) cannot contain the |
| 1552 |
<a href="#Predeclared_identifiers">predeclared identifier</a> <code>comparable</code> |
| 1553 |
or interfaces that specify methods, or embed <code>comparable</code> or interfaces |
| 1554 |
that specify methods. |
| 1555 |
</p> |
| 1556 |
|
| 1557 |
<p> |
| 1558 |
Interfaces that are not <a href="#Basic_interfaces">basic</a> may only be used as type |
| 1559 |
constraints, or as elements of other interfaces used as constraints. |
| 1560 |
They cannot be the types of values or variables, or components of other, |
| 1561 |
non-interface types. |
| 1562 |
</p> |
| 1563 |
|
| 1564 |
<pre> |
| 1565 |
var x Float // illegal: Float is not a basic interface |
| 1566 |
|
| 1567 |
var x interface{} = Float(nil) // illegal |
| 1568 |
|
| 1569 |
type Floatish struct { |
| 1570 |
f Float // illegal |
| 1571 |
} |
| 1572 |
</pre> |
| 1573 |
|
| 1574 |
<p> |
| 1575 |
An interface type <code>T</code> may not embed a type element |
| 1576 |
that is, contains, or embeds <code>T</code>, directly or indirectly. |
| 1577 |
</p> |
| 1578 |
|
| 1579 |
<pre> |
| 1580 |
// illegal: Bad may not embed itself |
| 1581 |
type Bad interface { |
| 1582 |
Bad |
| 1583 |
} |
| 1584 |
|
| 1585 |
// illegal: Bad1 may not embed itself using Bad2 |
| 1586 |
type Bad1 interface { |
| 1587 |
Bad2 |
| 1588 |
} |
| 1589 |
type Bad2 interface { |
| 1590 |
Bad1 |
| 1591 |
} |
| 1592 |
|
| 1593 |
// illegal: Bad3 may not embed a union containing Bad3 |
| 1594 |
type Bad3 interface { |
| 1595 |
~int | ~string | Bad3 |
| 1596 |
} |
| 1597 |
|
| 1598 |
// illegal: Bad4 may not embed an array containing Bad4 as element type |
| 1599 |
type Bad4 interface { |
| 1600 |
[10]Bad4 |
| 1601 |
} |
| 1602 |
</pre> |
| 1603 |
|
| 1604 |
<h4 id="Implementing_an_interface">Implementing an interface</h4> |
| 1605 |
|
| 1606 |
<p> |
| 1607 |
A type <code>T</code> implements an interface <code>I</code> if |
| 1608 |
</p> |
| 1609 |
|
| 1610 |
<ul> |
| 1611 |
<li> |
| 1612 |
<code>T</code> is not an interface and is an element of the type set of <code>I</code>; or |
| 1613 |
</li> |
| 1614 |
<li> |
| 1615 |
<code>T</code> is an interface and the type set of <code>T</code> is a subset of the |
| 1616 |
type set of <code>I</code>. |
| 1617 |
</li> |
| 1618 |
</ul> |
| 1619 |
|
| 1620 |
<p> |
| 1621 |
A value of type <code>T</code> implements an interface if <code>T</code> |
| 1622 |
implements the interface. |
| 1623 |
</p> |
| 1624 |
|
| 1625 |
<h3 id="Map_types">Map types</h3> |
| 1626 |
|
| 1627 |
<p> |
| 1628 |
A map is an unordered group of elements of one type, called the |
| 1629 |
element type, indexed by a set of unique <i>keys</i> of another type, |
| 1630 |
called the key type. |
| 1631 |
The <a href="#Representation_of_values">value</a> of an uninitialized map is <code>nil</code>. |
| 1632 |
</p> |
| 1633 |
|
| 1634 |
<pre class="ebnf"> |
| 1635 |
MapType = "map" "[" KeyType "]" ElementType . |
| 1636 |
KeyType = Type . |
| 1637 |
</pre> |
| 1638 |
|
| 1639 |
<p> |
| 1640 |
The <a href="#Comparison_operators">comparison operators</a> |
| 1641 |
<code>==</code> and <code>!=</code> must be fully defined |
| 1642 |
for operands of the key type; thus the key type must not be a function, map, or |
| 1643 |
slice. |
| 1644 |
If the key type is an interface type, these |
| 1645 |
comparison operators must be defined for the dynamic key values; |
| 1646 |
failure will cause a <a href="#Run_time_panics">run-time panic</a>. |
| 1647 |
</p> |
| 1648 |
|
| 1649 |
<pre> |
| 1650 |
map[string]int |
| 1651 |
map[*T]struct{ x, y float64 } |
| 1652 |
map[string]interface{} |
| 1653 |
</pre> |
| 1654 |
|
| 1655 |
<p> |
| 1656 |
The number of map elements is called its length. |
| 1657 |
For a map <code>m</code>, it can be discovered using the |
| 1658 |
built-in function <a href="#Length_and_capacity"><code>len</code></a> |
| 1659 |
and may change during execution. Elements may be added during execution |
| 1660 |
using <a href="#Assignment_statements">assignments</a> and retrieved with |
| 1661 |
<a href="#Index_expressions">index expressions</a>; they may be removed with the |
| 1662 |
<a href="#Deletion_of_map_elements"><code>delete</code></a> and |
| 1663 |
<a href="#Clear"><code>clear</code></a> built-in function. |
| 1664 |
</p> |
| 1665 |
|
| 1666 |
<p> |
| 1667 |
A new, empty map value is made using the built-in |
| 1668 |
function <a href="#Making_slices_maps_and_channels"><code>make</code></a>, |
| 1669 |
which takes the map type and an optional capacity hint as arguments: |
| 1670 |
</p> |
| 1671 |
|
| 1672 |
<pre> |
| 1673 |
make(map[string]int) |
| 1674 |
make(map[string]int, 100) |
| 1675 |
</pre> |
| 1676 |
|
| 1677 |
<p> |
| 1678 |
The initial capacity does not bound its size: |
| 1679 |
maps grow to accommodate the number of items |
| 1680 |
stored in them, with the exception of <code>nil</code> maps. |
| 1681 |
A <code>nil</code> map is equivalent to an empty map except that no elements |
| 1682 |
may be added. |
| 1683 |
</p> |
| 1684 |
|
| 1685 |
<h3 id="Channel_types">Channel types</h3> |
| 1686 |
|
| 1687 |
<p> |
| 1688 |
A channel provides a mechanism for |
| 1689 |
<a href="#Go_statements">concurrently executing functions</a> |
| 1690 |
to communicate by |
| 1691 |
<a href="#Send_statements">sending</a> and |
| 1692 |
<a href="#Receive_operator">receiving</a> |
| 1693 |
values of a specified element type. |
| 1694 |
The <a href="#Representation_of_values">value</a> of an uninitialized channel is <code>nil</code>. |
| 1695 |
</p> |
| 1696 |
|
| 1697 |
<pre class="ebnf"> |
| 1698 |
ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType . |
| 1699 |
</pre> |
| 1700 |
|
| 1701 |
<p> |
| 1702 |
The optional <code><-</code> operator specifies the channel <i>direction</i>, |
| 1703 |
<i>send</i> or <i>receive</i>. If a direction is given, the channel is <i>directional</i>, |
| 1704 |
otherwise it is <i>bidirectional</i>. |
| 1705 |
A channel may be constrained only to send or only to receive by |
| 1706 |
<a href="#Assignment_statements">assignment</a> or |
| 1707 |
explicit <a href="#Conversions">conversion</a>. |
| 1708 |
</p> |
| 1709 |
|
| 1710 |
<pre> |
| 1711 |
chan T // can be used to send and receive values of type T |
| 1712 |
chan<- float64 // can only be used to send float64s |
| 1713 |
<-chan int // can only be used to receive ints |
| 1714 |
</pre> |
| 1715 |
|
| 1716 |
<p> |
| 1717 |
The <code><-</code> operator associates with the leftmost <code>chan</code> |
| 1718 |
possible: |
| 1719 |
</p> |
| 1720 |
|
| 1721 |
<pre> |
| 1722 |
chan<- chan int // same as chan<- (chan int) |
| 1723 |
chan<- <-chan int // same as chan<- (<-chan int) |
| 1724 |
<-chan <-chan int // same as <-chan (<-chan int) |
| 1725 |
chan (<-chan int) |
| 1726 |
</pre> |
| 1727 |
|
| 1728 |
<p> |
| 1729 |
A new, initialized channel |
| 1730 |
value can be made using the built-in function |
| 1731 |
<a href="#Making_slices_maps_and_channels"><code>make</code></a>, |
| 1732 |
which takes the channel type and an optional <i>capacity</i> as arguments: |
| 1733 |
</p> |
| 1734 |
|
| 1735 |
<pre> |
| 1736 |
make(chan int, 100) |
| 1737 |
</pre> |
| 1738 |
|
| 1739 |
<p> |
| 1740 |
The capacity, in number of elements, sets the size of the buffer in the channel. |
| 1741 |
If the capacity is zero or absent, the channel is unbuffered and communication |
| 1742 |
succeeds only when both a sender and receiver are ready. Otherwise, the channel |
| 1743 |
is buffered and communication succeeds without blocking if the buffer |
| 1744 |
is not full (sends) or not empty (receives). |
| 1745 |
A <code>nil</code> channel is never ready for communication. |
| 1746 |
</p> |
| 1747 |
|
| 1748 |
<p> |
| 1749 |
A channel may be closed with the built-in function |
| 1750 |
<a href="#Close"><code>close</code></a>. |
| 1751 |
The multi-valued assignment form of the |
| 1752 |
<a href="#Receive_operator">receive operator</a> |
| 1753 |
reports whether a received value was sent before |
| 1754 |
the channel was closed. |
| 1755 |
</p> |
| 1756 |
|
| 1757 |
<p> |
| 1758 |
A single channel may be used in |
| 1759 |
<a href="#Send_statements">send statements</a>, |
| 1760 |
<a href="#Receive_operator">receive operations</a>, |
| 1761 |
and calls to the built-in functions |
| 1762 |
<a href="#Length_and_capacity"><code>cap</code></a> and |
| 1763 |
<a href="#Length_and_capacity"><code>len</code></a> |
| 1764 |
by any number of goroutines without further synchronization. |
| 1765 |
Channels act as first-in-first-out queues. |
| 1766 |
For example, if one goroutine sends values on a channel |
| 1767 |
and a second goroutine receives them, the values are |
| 1768 |
received in the order sent. |
| 1769 |
</p> |
| 1770 |
|
| 1771 |
<h2 id="Properties_of_types_and_values">Properties of types and values</h2> |
| 1772 |
|
| 1773 |
<h3 id="Representation_of_values">Representation of values</h3> |
| 1774 |
|
| 1775 |
<p> |
| 1776 |
Values of predeclared types (see below for the interfaces <code>any</code> |
| 1777 |
and <code>error</code>), arrays, and structs are self-contained: |
| 1778 |
Each such value contains a complete copy of all its data, |
| 1779 |
and <a href="#Variables">variables</a> of such types store the entire value. |
| 1780 |
For instance, an array variable provides the storage (the variables) |
| 1781 |
for all elements of the array. |
| 1782 |
The respective <a href="#The_zero_value">zero values</a> are specific to the |
| 1783 |
value's types; they are never <code>nil</code>. |
| 1784 |
</p> |
| 1785 |
|
| 1786 |
<p> |
| 1787 |
Non-nil pointer, function, slice, map, and channel values contain references |
| 1788 |
to underlying data which may be shared by multiple values: |
| 1789 |
</p> |
| 1790 |
|
| 1791 |
<ul> |
| 1792 |
<li> |
| 1793 |
A pointer value is a reference to the variable holding |
| 1794 |
the pointer base type value. |
| 1795 |
</li> |
| 1796 |
<li> |
| 1797 |
A function value contains references to the (possibly |
| 1798 |
<a href="#Function_literals">anonymous</a>) function |
| 1799 |
and enclosed variables. |
| 1800 |
</li> |
| 1801 |
<li> |
| 1802 |
A slice value contains the slice length, capacity, and |
| 1803 |
a reference to its <a href="#Slice_types">underlying array</a>. |
| 1804 |
</li> |
| 1805 |
<li> |
| 1806 |
A map or channel value is a reference to the implementation-specific |
| 1807 |
data structure of the map or channel. |
| 1808 |
</li> |
| 1809 |
</ul> |
| 1810 |
|
| 1811 |
<p> |
| 1812 |
An interface value may be self-contained or contain references to underlying data |
| 1813 |
depending on the interface's <a href="#Variables">dynamic type</a>. |
| 1814 |
The predeclared identifier <code>nil</code> is the zero value for types whose values |
| 1815 |
can contain references. |
| 1816 |
</p> |
| 1817 |
|
| 1818 |
<p> |
| 1819 |
When multiple values share underlying data, changing one value may change another. |
| 1820 |
For instance, changing an element of a <a href="#Slice_types">slice</a> will change |
| 1821 |
that element in the underlying array for all slices that share the array. |
| 1822 |
</p> |
| 1823 |
|
| 1824 |
<h3 id="Underlying_types">Underlying types</h3> |
| 1825 |
|
| 1826 |
<p> |
| 1827 |
Each type <code>T</code> has an <i>underlying type</i>: If <code>T</code> |
| 1828 |
is one of the predeclared boolean, numeric, or string types, or a type literal, |
| 1829 |
the corresponding underlying type is <code>T</code> itself. |
| 1830 |
Otherwise, <code>T</code>'s underlying type is the underlying type of the |
| 1831 |
type to which <code>T</code> refers in its declaration. |
| 1832 |
For a type parameter that is the underlying type of its |
| 1833 |
<a href="#Type_constraints">type constraint</a>, which is always an interface. |
| 1834 |
</p> |
| 1835 |
|
| 1836 |
<pre> |
| 1837 |
type ( |
| 1838 |
A1 = string |
| 1839 |
A2 = A1 |
| 1840 |
) |
| 1841 |
|
| 1842 |
type ( |
| 1843 |
B1 string |
| 1844 |
B2 B1 |
| 1845 |
B3 []B1 |
| 1846 |
B4 B3 |
| 1847 |
) |
| 1848 |
|
| 1849 |
func f[P any](x P) { … } |
| 1850 |
</pre> |
| 1851 |
|
| 1852 |
<p> |
| 1853 |
The underlying type of <code>string</code>, <code>A1</code>, <code>A2</code>, <code>B1</code>, |
| 1854 |
and <code>B2</code> is <code>string</code>. |
| 1855 |
The underlying type of <code>[]B1</code>, <code>B3</code>, and <code>B4</code> is <code>[]B1</code>. |
| 1856 |
The underlying type of <code>P</code> is <code>interface{}</code>. |
| 1857 |
</p> |
| 1858 |
|
| 1859 |
<h3 id="Type_identity">Type identity</h3> |
| 1860 |
|
| 1861 |
<p> |
| 1862 |
Two types are either <i>identical</i> ("the same") or <i>different</i>. |
| 1863 |
</p> |
| 1864 |
|
| 1865 |
<p> |
| 1866 |
A <a href="#Types">named type</a> is always different from any other type. |
| 1867 |
Otherwise, two types are identical if their <a href="#Types">underlying</a> type literals are |
| 1868 |
structurally equivalent; that is, they have the same literal structure and corresponding |
| 1869 |
components have identical types. In detail: |
| 1870 |
</p> |
| 1871 |
|
| 1872 |
<ul> |
| 1873 |
<li>Two array types are identical if they have identical element types and |
| 1874 |
the same array length.</li> |
| 1875 |
|
| 1876 |
<li>Two slice types are identical if they have identical element types.</li> |
| 1877 |
|
| 1878 |
<li>Two struct types are identical if they have the same sequence of fields, |
| 1879 |
and if corresponding pairs of fields have the same names, identical types, |
| 1880 |
and identical tags, and are either both embedded or both not embedded. |
| 1881 |
<a href="#Exported_identifiers">Non-exported</a> field names from different |
| 1882 |
packages are always different.</li> |
| 1883 |
|
| 1884 |
<li>Two pointer types are identical if they have identical base types.</li> |
| 1885 |
|
| 1886 |
<li>Two function types are identical if they have the same number of parameters |
| 1887 |
and result values, corresponding parameter and result types are |
| 1888 |
identical, and either both functions are variadic or neither is. |
| 1889 |
Parameter and result names are not required to match.</li> |
| 1890 |
|
| 1891 |
<li>Two interface types are identical if they define the same type set. |
| 1892 |
</li> |
| 1893 |
|
| 1894 |
<li>Two map types are identical if they have identical key and element types.</li> |
| 1895 |
|
| 1896 |
<li>Two channel types are identical if they have identical element types and |
| 1897 |
the same direction.</li> |
| 1898 |
|
| 1899 |
<li>Two <a href="#Instantiations">instantiated</a> types are identical if |
| 1900 |
their defined types and all type arguments are identical. |
| 1901 |
</li> |
| 1902 |
</ul> |
| 1903 |
|
| 1904 |
<p> |
| 1905 |
Given the declarations |
| 1906 |
</p> |
| 1907 |
|
| 1908 |
<pre> |
| 1909 |
type ( |
| 1910 |
A0 = []string |
| 1911 |
A1 = A0 |
| 1912 |
A2 = struct{ a, b int } |
| 1913 |
A3 = int |
| 1914 |
A4 = func(A3, float64) *A0 |
| 1915 |
A5 = func(x int, _ float64) *[]string |
| 1916 |
|
| 1917 |
B0 A0 |
| 1918 |
B1 []string |
| 1919 |
B2 struct{ a, b int } |
| 1920 |
B3 struct{ a, c int } |
| 1921 |
B4 func(int, float64) *B0 |
| 1922 |
B5 func(x int, y float64) *A1 |
| 1923 |
|
| 1924 |
C0 = B0 |
| 1925 |
D0[P1, P2 any] struct{ x P1; y P2 } |
| 1926 |
E0 = D0[int, string] |
| 1927 |
) |
| 1928 |
</pre> |
| 1929 |
|
| 1930 |
<p> |
| 1931 |
these types are identical: |
| 1932 |
</p> |
| 1933 |
|
| 1934 |
<pre> |
| 1935 |
A0, A1, and []string |
| 1936 |
A2 and struct{ a, b int } |
| 1937 |
A3 and int |
| 1938 |
A4, func(int, float64) *[]string, and A5 |
| 1939 |
|
| 1940 |
B0 and C0 |
| 1941 |
D0[int, string] and E0 |
| 1942 |
[]int and []int |
| 1943 |
struct{ a, b *B5 } and struct{ a, b *B5 } |
| 1944 |
func(x int, y float64) *[]string, func(int, float64) (result *[]string), and A5 |
| 1945 |
</pre> |
| 1946 |
|
| 1947 |
<p> |
| 1948 |
<code>B0</code> and <code>B1</code> are different because they are new types |
| 1949 |
created by distinct <a href="#Type_definitions">type definitions</a>; |
| 1950 |
<code>func(int, float64) *B0</code> and <code>func(x int, y float64) *[]string</code> |
| 1951 |
are different because <code>B0</code> is different from <code>[]string</code>; |
| 1952 |
and <code>P1</code> and <code>P2</code> are different because they are different |
| 1953 |
type parameters. |
| 1954 |
<code>D0[int, string]</code> and <code>struct{ x int; y string }</code> are |
| 1955 |
different because the former is an <a href="#Instantiations">instantiated</a> |
| 1956 |
defined type while the latter is a type literal |
| 1957 |
(but they are still <a href="#Assignability">assignable</a>). |
| 1958 |
</p> |
| 1959 |
|
| 1960 |
<h3 id="Assignability">Assignability</h3> |
| 1961 |
|
| 1962 |
<p> |
| 1963 |
A value <code>x</code> of type <code>V</code> is <i>assignable</i> to a <a href="#Variables">variable</a> of type <code>T</code> |
| 1964 |
("<code>x</code> is assignable to <code>T</code>") if one of the following conditions applies: |
| 1965 |
</p> |
| 1966 |
|
| 1967 |
<ul> |
| 1968 |
<li> |
| 1969 |
<code>V</code> and <code>T</code> are identical. |
| 1970 |
</li> |
| 1971 |
<li> |
| 1972 |
<code>V</code> and <code>T</code> have identical |
| 1973 |
<a href="#Underlying_types">underlying types</a> |
| 1974 |
but are not type parameters and at least one of <code>V</code> |
| 1975 |
or <code>T</code> is not a <a href="#Types">named type</a>. |
| 1976 |
</li> |
| 1977 |
<li> |
| 1978 |
<code>V</code> and <code>T</code> are channel types with |
| 1979 |
identical element types, <code>V</code> is a bidirectional channel, |
| 1980 |
and at least one of <code>V</code> or <code>T</code> is not a <a href="#Types">named type</a>. |
| 1981 |
</li> |
| 1982 |
<li> |
| 1983 |
<code>T</code> is an interface type, but not a type parameter, and |
| 1984 |
<code>x</code> <a href="#Implementing_an_interface">implements</a> <code>T</code>. |
| 1985 |
</li> |
| 1986 |
<li> |
| 1987 |
<code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code> |
| 1988 |
is a pointer, function, slice, map, channel, or interface type, |
| 1989 |
but not a type parameter. |
| 1990 |
</li> |
| 1991 |
<li> |
| 1992 |
<code>x</code> is an untyped <a href="#Constants">constant</a> |
| 1993 |
<a href="#Representability">representable</a> |
| 1994 |
by a value of type <code>T</code>. |
| 1995 |
</li> |
| 1996 |
</ul> |
| 1997 |
|
| 1998 |
<p> |
| 1999 |
Additionally, if <code>x</code>'s type <code>V</code> or <code>T</code> are type parameters, <code>x</code> |
| 2000 |
is assignable to a variable of type <code>T</code> if one of the following conditions applies: |
| 2001 |
</p> |
| 2002 |
|
| 2003 |
<ul> |
| 2004 |
<li> |
| 2005 |
<code>x</code> is the predeclared identifier <code>nil</code>, <code>T</code> is |
| 2006 |
a type parameter, and <code>x</code> is assignable to each type in |
| 2007 |
<code>T</code>'s type set. |
| 2008 |
</li> |
| 2009 |
<li> |
| 2010 |
<code>V</code> is not a <a href="#Types">named type</a>, <code>T</code> is |
| 2011 |
a type parameter, and <code>x</code> is assignable to each type in |
| 2012 |
<code>T</code>'s type set. |
| 2013 |
</li> |
| 2014 |
<li> |
| 2015 |
<code>V</code> is a type parameter and <code>T</code> is not a named type, |
| 2016 |
and values of each type in <code>V</code>'s type set are assignable |
| 2017 |
to <code>T</code>. |
| 2018 |
</li> |
| 2019 |
</ul> |
| 2020 |
|
| 2021 |
<h3 id="Representability">Representability</h3> |
| 2022 |
|
| 2023 |
<p> |
| 2024 |
A <a href="#Constants">constant</a> <code>x</code> is <i>representable</i> |
| 2025 |
by a value of type <code>T</code>, |
| 2026 |
where <code>T</code> is not a <a href="#Type_parameter_declarations">type parameter</a>, |
| 2027 |
if one of the following conditions applies: |
| 2028 |
</p> |
| 2029 |
|
| 2030 |
<ul> |
| 2031 |
<li> |
| 2032 |
<code>x</code> is in the set of values <a href="#Types">determined</a> by <code>T</code>. |
| 2033 |
</li> |
| 2034 |
|
| 2035 |
<li> |
| 2036 |
<code>T</code> is a <a href="#Numeric_types">floating-point type</a> and <code>x</code> can be rounded to <code>T</code>'s |
| 2037 |
precision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEE |
| 2038 |
negative zero further simplified to an unsigned zero. Note that constant values never result |
| 2039 |
in an IEEE negative zero, NaN, or infinity. |
| 2040 |
</li> |
| 2041 |
|
| 2042 |
<li> |
| 2043 |
<code>T</code> is a complex type, and <code>x</code>'s |
| 2044 |
<a href="#Complex_numbers">components</a> <code>real(x)</code> and <code>imag(x)</code> |
| 2045 |
are representable by values of <code>T</code>'s component type (<code>float32</code> or |
| 2046 |
<code>float64</code>). |
| 2047 |
</li> |
| 2048 |
</ul> |
| 2049 |
|
| 2050 |
<p> |
| 2051 |
If <code>T</code> is a type parameter, |
| 2052 |
<code>x</code> is representable by a value of type <code>T</code> if <code>x</code> is representable |
| 2053 |
by a value of each type in <code>T</code>'s type set. |
| 2054 |
</p> |
| 2055 |
|
| 2056 |
<pre> |
| 2057 |
x T x is representable by a value of T because |
| 2058 |
|
| 2059 |
'a' byte 97 is in the set of byte values |
| 2060 |
97 rune rune is an alias for int32, and 97 is in the set of 32-bit integers |
| 2061 |
"foo" string "foo" is in the set of string values |
| 2062 |
1024 int16 1024 is in the set of 16-bit integers |
| 2063 |
42.0 byte 42 is in the set of unsigned 8-bit integers |
| 2064 |
1e10 uint64 10000000000 is in the set of unsigned 64-bit integers |
| 2065 |
2.718281828459045 float32 2.718281828459045 rounds to 2.7182817 which is in the set of float32 values |
| 2066 |
-1e-1000 float64 -1e-1000 rounds to IEEE -0.0 which is further simplified to 0.0 |
| 2067 |
0i int 0 is an integer value |
| 2068 |
(42 + 0i) float32 42.0 (with zero imaginary part) is in the set of float32 values |
| 2069 |
</pre> |
| 2070 |
|
| 2071 |
<pre> |
| 2072 |
x T x is not representable by a value of T because |
| 2073 |
|
| 2074 |
0 bool 0 is not in the set of boolean values |
| 2075 |
'a' string 'a' is a rune, it is not in the set of string values |
| 2076 |
1024 byte 1024 is not in the set of unsigned 8-bit integers |
| 2077 |
-1 uint16 -1 is not in the set of unsigned 16-bit integers |
| 2078 |
1.1 int 1.1 is not an integer value |
| 2079 |
42i float32 (0 + 42i) is not in the set of float32 values |
| 2080 |
1e1000 float64 1e1000 overflows to IEEE +Inf after rounding |
| 2081 |
</pre> |
| 2082 |
|
| 2083 |
<h3 id="Method_sets">Method sets</h3> |
| 2084 |
|
| 2085 |
<p> |
| 2086 |
The <i>method set</i> of a type determines the methods that can be |
| 2087 |
<a href="#Calls">called</a> on an <a href="#Operands">operand</a> of that type. |
| 2088 |
Every type has a (possibly empty) method set associated with it: |
| 2089 |
</p> |
| 2090 |
|
| 2091 |
<ul> |
| 2092 |
<li>The method set of a <a href="#Type_definitions">defined type</a> <code>T</code> consists of all |
| 2093 |
<a href="#Method_declarations">methods</a> declared with receiver type <code>T</code>. |
| 2094 |
</li> |
| 2095 |
|
| 2096 |
<li> |
| 2097 |
The method set of a pointer to a defined type <code>T</code> |
| 2098 |
(where <code>T</code> is neither a pointer nor an interface) |
| 2099 |
is the set of all methods declared with receiver <code>*T</code> or <code>T</code>. |
| 2100 |
</li> |
| 2101 |
|
| 2102 |
<li>The method set of an <a href="#Interface_types">interface type</a> is the intersection |
| 2103 |
of the method sets of each type in the interface's <a href="#Interface_types">type set</a> |
| 2104 |
(the resulting method set is usually just the set of declared methods in the interface). |
| 2105 |
</li> |
| 2106 |
</ul> |
| 2107 |
|
| 2108 |
<p> |
| 2109 |
Further rules apply to structs (and pointer to structs) containing embedded fields, |
| 2110 |
as described in the section on <a href="#Struct_types">struct types</a>. |
| 2111 |
Any other type has an empty method set. |
| 2112 |
</p> |
| 2113 |
|
| 2114 |
<p> |
| 2115 |
In a method set, each method must have a |
| 2116 |
<a href="#Uniqueness_of_identifiers">unique</a> |
| 2117 |
non-<a href="#Blank_identifier">blank</a> <a href="#MethodName">method name</a>. |
| 2118 |
</p> |
| 2119 |
|
| 2120 |
<h2 id="Blocks">Blocks</h2> |
| 2121 |
|
| 2122 |
<p> |
| 2123 |
A <i>block</i> is a possibly empty sequence of declarations and statements |
| 2124 |
within matching brace brackets. |
| 2125 |
</p> |
| 2126 |
|
| 2127 |
<pre class="ebnf"> |
| 2128 |
Block = "{" StatementList "}" . |
| 2129 |
StatementList = { Statement ";" } . |
| 2130 |
</pre> |
| 2131 |
|
| 2132 |
<p> |
| 2133 |
In addition to explicit blocks in the source code, there are implicit blocks: |
| 2134 |
</p> |
| 2135 |
|
| 2136 |
<ol> |
| 2137 |
<li>The <i>universe block</i> encompasses all Go source text.</li> |
| 2138 |
|
| 2139 |
<li>Each <a href="#Packages">package</a> has a <i>package block</i> containing all |
| 2140 |
Go source text for that package.</li> |
| 2141 |
|
| 2142 |
<li>Each file has a <i>file block</i> containing all Go source text |
| 2143 |
in that file.</li> |
| 2144 |
|
| 2145 |
<li>Each <a href="#If_statements">"if"</a>, |
| 2146 |
<a href="#For_statements">"for"</a>, and |
| 2147 |
<a href="#Switch_statements">"switch"</a> |
| 2148 |
statement is considered to be in its own implicit block.</li> |
| 2149 |
|
| 2150 |
<li>Each clause in a <a href="#Switch_statements">"switch"</a> |
| 2151 |
or <a href="#Select_statements">"select"</a> statement |
| 2152 |
acts as an implicit block.</li> |
| 2153 |
</ol> |
| 2154 |
|
| 2155 |
<p> |
| 2156 |
Blocks nest and influence <a href="#Declarations_and_scope">scoping</a>. |
| 2157 |
</p> |
| 2158 |
|
| 2159 |
|
| 2160 |
<h2 id="Declarations_and_scope">Declarations and scope</h2> |
| 2161 |
|
| 2162 |
<p> |
| 2163 |
A <i>declaration</i> binds a non-<a href="#Blank_identifier">blank</a> identifier to a |
| 2164 |
<a href="#Constant_declarations">constant</a>, |
| 2165 |
<a href="#Type_declarations">type</a>, |
| 2166 |
<a href="#Type_parameter_declarations">type parameter</a>, |
| 2167 |
<a href="#Variable_declarations">variable</a>, |
| 2168 |
<a href="#Function_declarations">function</a>, |
| 2169 |
<a href="#Labeled_statements">label</a>, or |
| 2170 |
<a href="#Import_declarations">package</a>. |
| 2171 |
Every identifier in a program must be declared. |
| 2172 |
No identifier may be declared twice in the same block, and |
| 2173 |
no identifier may be declared in both the file and package block. |
| 2174 |
</p> |
| 2175 |
|
| 2176 |
<p> |
| 2177 |
The <a href="#Blank_identifier">blank identifier</a> may be used like any other identifier |
| 2178 |
in a declaration, but it does not introduce a binding and thus is not declared. |
| 2179 |
In the package block, the identifier <code>init</code> may only be used for |
| 2180 |
<a href="#Package_initialization"><code>init</code> function</a> declarations, |
| 2181 |
and like the blank identifier it does not introduce a new binding. |
| 2182 |
</p> |
| 2183 |
|
| 2184 |
<pre class="ebnf"> |
| 2185 |
Declaration = ConstDecl | TypeDecl | VarDecl . |
| 2186 |
TopLevelDecl = Declaration | FunctionDecl | MethodDecl . |
| 2187 |
</pre> |
| 2188 |
|
| 2189 |
<p> |
| 2190 |
The <i>scope</i> of a declared identifier is the extent of source text in which |
| 2191 |
the identifier denotes the specified constant, type, variable, function, label, or package. |
| 2192 |
</p> |
| 2193 |
|
| 2194 |
<p> |
| 2195 |
Go is lexically scoped using <a href="#Blocks">blocks</a>: |
| 2196 |
</p> |
| 2197 |
|
| 2198 |
<ol> |
| 2199 |
<li>The scope of a <a href="#Predeclared_identifiers">predeclared identifier</a> is the universe block.</li> |
| 2200 |
|
| 2201 |
<li>The scope of an identifier denoting a constant, type, variable, |
| 2202 |
or function (but not method) declared at top level (outside any |
| 2203 |
function) is the package block.</li> |
| 2204 |
|
| 2205 |
<li>The scope of the package name of an imported package is the file block |
| 2206 |
of the file containing the import declaration.</li> |
| 2207 |
|
| 2208 |
<li>The scope of an identifier denoting a method receiver, function parameter, |
| 2209 |
or result variable is the function body.</li> |
| 2210 |
|
| 2211 |
<li>The scope of an identifier denoting a type parameter of a function |
| 2212 |
or declared by a method receiver begins after the name of the function |
| 2213 |
and ends at the end of the function body.</li> |
| 2214 |
|
| 2215 |
<li>The scope of an identifier denoting a type parameter of a type |
| 2216 |
begins after the name of the type and ends at the end |
| 2217 |
of the TypeSpec.</li> |
| 2218 |
|
| 2219 |
<li>The scope of a constant or variable identifier declared |
| 2220 |
inside a function begins at the end of the ConstSpec or VarSpec |
| 2221 |
(ShortVarDecl for short variable declarations) |
| 2222 |
and ends at the end of the innermost containing block.</li> |
| 2223 |
|
| 2224 |
<li>The scope of a type identifier declared inside a function |
| 2225 |
begins at the identifier in the TypeSpec |
| 2226 |
and ends at the end of the innermost containing block.</li> |
| 2227 |
</ol> |
| 2228 |
|
| 2229 |
<p> |
| 2230 |
An identifier declared in a block may be redeclared in an inner block. |
| 2231 |
While the identifier of the inner declaration is in scope, it denotes |
| 2232 |
the entity declared by the inner declaration. |
| 2233 |
</p> |
| 2234 |
|
| 2235 |
<p> |
| 2236 |
The <a href="#Package_clause">package clause</a> is not a declaration; the package name |
| 2237 |
does not appear in any scope. Its purpose is to identify the files belonging |
| 2238 |
to the same <a href="#Packages">package</a> and to specify the default package name for import |
| 2239 |
declarations. |
| 2240 |
</p> |
| 2241 |
|
| 2242 |
|
| 2243 |
<h3 id="Label_scopes">Label scopes</h3> |
| 2244 |
|
| 2245 |
<p> |
| 2246 |
Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are |
| 2247 |
used in the <a href="#Break_statements">"break"</a>, |
| 2248 |
<a href="#Continue_statements">"continue"</a>, and |
| 2249 |
<a href="#Goto_statements">"goto"</a> statements. |
| 2250 |
It is illegal to define a label that is never used. |
| 2251 |
In contrast to other identifiers, labels are not block scoped and do |
| 2252 |
not conflict with identifiers that are not labels. The scope of a label |
| 2253 |
is the body of the function in which it is declared and excludes |
| 2254 |
the body of any nested function. |
| 2255 |
</p> |
| 2256 |
|
| 2257 |
|
| 2258 |
<h3 id="Blank_identifier">Blank identifier</h3> |
| 2259 |
|
| 2260 |
<p> |
| 2261 |
The <i>blank identifier</i> is represented by the underscore character <code>_</code>. |
| 2262 |
It serves as an anonymous placeholder instead of a regular (non-blank) |
| 2263 |
identifier and has special meaning in <a href="#Declarations_and_scope">declarations</a>, |
| 2264 |
as an <a href="#Operands">operand</a>, and in <a href="#Assignment_statements">assignment statements</a>. |
| 2265 |
</p> |
| 2266 |
|
| 2267 |
|
| 2268 |
<h3 id="Predeclared_identifiers">Predeclared identifiers</h3> |
| 2269 |
|
| 2270 |
<p> |
| 2271 |
The following identifiers are implicitly declared in the |
| 2272 |
<a href="#Blocks">universe block</a> |
| 2273 |
[<a href="#Go_1.18">Go 1.18</a>] |
| 2274 |
[<a href="#Go_1.21">Go 1.21</a>]: |
| 2275 |
</p> |
| 2276 |
<pre class="grammar"> |
| 2277 |
Types: |
| 2278 |
any bool byte comparable |
| 2279 |
complex64 complex128 error float32 float64 |
| 2280 |
int int8 int16 int32 int64 rune string |
| 2281 |
uint uint8 uint16 uint32 uint64 uintptr |
| 2282 |
|
| 2283 |
Constants: |
| 2284 |
true false iota |
| 2285 |
|
| 2286 |
Zero value: |
| 2287 |
nil |
| 2288 |
|
| 2289 |
Functions: |
| 2290 |
append cap clear close complex copy delete imag len |
| 2291 |
make max min new panic print println real recover |
| 2292 |
</pre> |
| 2293 |
|
| 2294 |
<h3 id="Exported_identifiers">Exported identifiers</h3> |
| 2295 |
|
| 2296 |
<p> |
| 2297 |
An identifier may be <i>exported</i> to permit access to it from another package. |
| 2298 |
An identifier is exported if both: |
| 2299 |
</p> |
| 2300 |
<ol> |
| 2301 |
<li>the first character of the identifier's name is a Unicode uppercase |
| 2302 |
letter (Unicode character category Lu); and</li> |
| 2303 |
<li>the identifier is declared in the <a href="#Blocks">package block</a> |
| 2304 |
or it is a <a href="#Struct_types">field name</a> or |
| 2305 |
<a href="#MethodName">method name</a>.</li> |
| 2306 |
</ol> |
| 2307 |
<p> |
| 2308 |
All other identifiers are not exported. |
| 2309 |
</p> |
| 2310 |
|
| 2311 |
<h3 id="Uniqueness_of_identifiers">Uniqueness of identifiers</h3> |
| 2312 |
|
| 2313 |
<p> |
| 2314 |
Given a set of identifiers, an identifier is called <i>unique</i> if it is |
| 2315 |
<i>different</i> from every other in the set. |
| 2316 |
Two identifiers are different if they are spelled differently, or if they |
| 2317 |
appear in different <a href="#Packages">packages</a> and are not |
| 2318 |
<a href="#Exported_identifiers">exported</a>. Otherwise, they are the same. |
| 2319 |
</p> |
| 2320 |
|
| 2321 |
<h3 id="Constant_declarations">Constant declarations</h3> |
| 2322 |
|
| 2323 |
<p> |
| 2324 |
A constant declaration binds a list of identifiers (the names of |
| 2325 |
the constants) to the values of a list of <a href="#Constant_expressions">constant expressions</a>. |
| 2326 |
The number of identifiers must be equal |
| 2327 |
to the number of expressions, and the <i>n</i>th identifier on |
| 2328 |
the left is bound to the value of the <i>n</i>th expression on the |
| 2329 |
right. |
| 2330 |
</p> |
| 2331 |
|
| 2332 |
<pre class="ebnf"> |
| 2333 |
ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) . |
| 2334 |
ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] . |
| 2335 |
|
| 2336 |
IdentifierList = identifier { "," identifier } . |
| 2337 |
ExpressionList = Expression { "," Expression } . |
| 2338 |
</pre> |
| 2339 |
|
| 2340 |
<p> |
| 2341 |
If the type is present, all constants take the type specified, and |
| 2342 |
the expressions must be <a href="#Assignability">assignable</a> to that type, |
| 2343 |
which must not be a type parameter. |
| 2344 |
If the type is omitted, the constants take the |
| 2345 |
individual types of the corresponding expressions. |
| 2346 |
If the expression values are untyped <a href="#Constants">constants</a>, |
| 2347 |
the declared constants remain untyped and the constant identifiers |
| 2348 |
denote the constant values. For instance, if the expression is a |
| 2349 |
floating-point literal, the constant identifier denotes a floating-point |
| 2350 |
constant, even if the literal's fractional part is zero. |
| 2351 |
</p> |
| 2352 |
|
| 2353 |
<pre> |
| 2354 |
const Pi float64 = 3.14159265358979323846 |
| 2355 |
const zero = 0.0 // untyped floating-point constant |
| 2356 |
const ( |
| 2357 |
size int64 = 1024 |
| 2358 |
eof = -1 // untyped integer constant |
| 2359 |
) |
| 2360 |
const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants |
| 2361 |
const u, v float32 = 0, 3 // u = 0.0, v = 3.0 |
| 2362 |
</pre> |
| 2363 |
|
| 2364 |
<p> |
| 2365 |
Within a parenthesized <code>const</code> declaration list the |
| 2366 |
expression list may be omitted from any but the first ConstSpec. |
| 2367 |
Such an empty list is equivalent to the textual substitution of the |
| 2368 |
first preceding non-empty expression list and its type if any. |
| 2369 |
Omitting the list of expressions is therefore equivalent to |
| 2370 |
repeating the previous list. The number of identifiers must be equal |
| 2371 |
to the number of expressions in the previous list. |
| 2372 |
Together with the <a href="#Iota"><code>iota</code> constant generator</a> |
| 2373 |
this mechanism permits light-weight declaration of sequential values: |
| 2374 |
</p> |
| 2375 |
|
| 2376 |
<pre> |
| 2377 |
const ( |
| 2378 |
Sunday = iota |
| 2379 |
Monday |
| 2380 |
Tuesday |
| 2381 |
Wednesday |
| 2382 |
Thursday |
| 2383 |
Friday |
| 2384 |
Partyday |
| 2385 |
numberOfDays // this constant is not exported |
| 2386 |
) |
| 2387 |
</pre> |
| 2388 |
|
| 2389 |
|
| 2390 |
<h3 id="Iota">Iota</h3> |
| 2391 |
|
| 2392 |
<p> |
| 2393 |
Within a <a href="#Constant_declarations">constant declaration</a>, the predeclared identifier |
| 2394 |
<code>iota</code> represents successive untyped integer <a href="#Constants"> |
| 2395 |
constants</a>. Its value is the index of the respective <a href="#ConstSpec">ConstSpec</a> |
| 2396 |
in that constant declaration, starting at zero. |
| 2397 |
It can be used to construct a set of related constants: |
| 2398 |
</p> |
| 2399 |
|
| 2400 |
<pre> |
| 2401 |
const ( |
| 2402 |
c0 = iota // c0 == 0 |
| 2403 |
c1 = iota // c1 == 1 |
| 2404 |
c2 = iota // c2 == 2 |
| 2405 |
) |
| 2406 |
|
| 2407 |
const ( |
| 2408 |
a = 1 << iota // a == 1 (iota == 0) |
| 2409 |
b = 1 << iota // b == 2 (iota == 1) |
| 2410 |
c = 3 // c == 3 (iota == 2, unused) |
| 2411 |
d = 1 << iota // d == 8 (iota == 3) |
| 2412 |
) |
| 2413 |
|
| 2414 |
const ( |
| 2415 |
u = iota * 42 // u == 0 (untyped integer constant) |
| 2416 |
v float64 = iota * 42 // v == 42.0 (float64 constant) |
| 2417 |
w = iota * 42 // w == 84 (untyped integer constant) |
| 2418 |
) |
| 2419 |
|
| 2420 |
const x = iota // x == 0 |
| 2421 |
const y = iota // y == 0 |
| 2422 |
</pre> |
| 2423 |
|
| 2424 |
<p> |
| 2425 |
By definition, multiple uses of <code>iota</code> in the same ConstSpec all have the same value: |
| 2426 |
</p> |
| 2427 |
|
| 2428 |
<pre> |
| 2429 |
const ( |
| 2430 |
bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 (iota == 0) |
| 2431 |
bit1, mask1 // bit1 == 2, mask1 == 1 (iota == 1) |
| 2432 |
_, _ // (iota == 2, unused) |
| 2433 |
bit3, mask3 // bit3 == 8, mask3 == 7 (iota == 3) |
| 2434 |
) |
| 2435 |
</pre> |
| 2436 |
|
| 2437 |
<p> |
| 2438 |
This last example exploits the <a href="#Constant_declarations">implicit repetition</a> |
| 2439 |
of the last non-empty expression list. |
| 2440 |
</p> |
| 2441 |
|
| 2442 |
|
| 2443 |
<h3 id="Type_declarations">Type declarations</h3> |
| 2444 |
|
| 2445 |
<p> |
| 2446 |
A type declaration binds an identifier, the <i>type name</i>, to a <a href="#Types">type</a>. |
| 2447 |
Type declarations come in two forms: alias declarations and type definitions. |
| 2448 |
</p> |
| 2449 |
|
| 2450 |
<pre class="ebnf"> |
| 2451 |
TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) . |
| 2452 |
TypeSpec = AliasDecl | TypeDef . |
| 2453 |
</pre> |
| 2454 |
|
| 2455 |
<h4 id="Alias_declarations">Alias declarations</h4> |
| 2456 |
|
| 2457 |
<p> |
| 2458 |
An alias declaration binds an identifier to the given type |
| 2459 |
[<a href="#Go_1.9">Go 1.9</a>]. |
| 2460 |
</p> |
| 2461 |
|
| 2462 |
<pre class="ebnf"> |
| 2463 |
AliasDecl = identifier [ TypeParameters ] "=" Type . |
| 2464 |
</pre> |
| 2465 |
|
| 2466 |
<p> |
| 2467 |
Within the <a href="#Declarations_and_scope">scope</a> of |
| 2468 |
the identifier, it serves as an <i>alias</i> for the given type. |
| 2469 |
</p> |
| 2470 |
|
| 2471 |
<pre> |
| 2472 |
type ( |
| 2473 |
nodeList = []*Node // nodeList and []*Node are identical types |
| 2474 |
Polar = polar // Polar and polar denote identical types |
| 2475 |
) |
| 2476 |
</pre> |
| 2477 |
|
| 2478 |
<p> |
| 2479 |
If the alias declaration specifies <a href="#Type_parameter_declarations">type parameters</a> |
| 2480 |
[<a href="#Go_1.24">Go 1.24</a>], the type name denotes a <i>generic alias</i>. |
| 2481 |
Generic aliases must be <a href="#Instantiations">instantiated</a> when they |
| 2482 |
are used. |
| 2483 |
</p> |
| 2484 |
|
| 2485 |
<pre> |
| 2486 |
type set[P comparable] = map[P]bool |
| 2487 |
</pre> |
| 2488 |
|
| 2489 |
<p> |
| 2490 |
In an alias declaration the given type cannot be a type parameter declared in the same declaration. |
| 2491 |
</p> |
| 2492 |
|
| 2493 |
<pre> |
| 2494 |
type A[P any] = P // illegal: P is a type parameter declared in the declaration of A |
| 2495 |
|
| 2496 |
func f[P any]() { |
| 2497 |
type A = P // ok: T is a type parameter declared by the enclosing function |
| 2498 |
} |
| 2499 |
</pre> |
| 2500 |
|
| 2501 |
<h4 id="Type_definitions">Type definitions</h4> |
| 2502 |
|
| 2503 |
<p> |
| 2504 |
A type definition creates a new, distinct type with the same |
| 2505 |
<a href="#Underlying_types">underlying type</a> and operations as the given type |
| 2506 |
and binds an identifier, the <i>type name</i>, to it. |
| 2507 |
</p> |
| 2508 |
|
| 2509 |
<pre class="ebnf"> |
| 2510 |
TypeDef = identifier [ TypeParameters ] Type . |
| 2511 |
</pre> |
| 2512 |
|
| 2513 |
<p> |
| 2514 |
The new type is called a <i>defined type</i>. |
| 2515 |
It is <a href="#Type_identity">different</a> from any other type, |
| 2516 |
including the type it is created from. |
| 2517 |
</p> |
| 2518 |
|
| 2519 |
<pre> |
| 2520 |
type ( |
| 2521 |
Point struct{ x, y float64 } // Point and struct{ x, y float64 } are different types |
| 2522 |
polar Point // polar and Point denote different types |
| 2523 |
) |
| 2524 |
|
| 2525 |
type TreeNode struct { |
| 2526 |
left, right *TreeNode |
| 2527 |
value any |
| 2528 |
} |
| 2529 |
|
| 2530 |
type Block interface { |
| 2531 |
BlockSize() int |
| 2532 |
Encrypt(src, dst []byte) |
| 2533 |
Decrypt(src, dst []byte) |
| 2534 |
} |
| 2535 |
</pre> |
| 2536 |
|
| 2537 |
<p> |
| 2538 |
A defined type may have <a href="#Method_declarations">methods</a> associated with it. |
| 2539 |
It does not inherit any methods bound to the given type, |
| 2540 |
but the <a href="#Method_sets">method set</a> |
| 2541 |
of an interface type or of elements of a composite type remains unchanged: |
| 2542 |
</p> |
| 2543 |
|
| 2544 |
<pre> |
| 2545 |
// A Mutex is a data type with two methods, Lock and Unlock. |
| 2546 |
type Mutex struct { /* Mutex fields */ } |
| 2547 |
func (m *Mutex) Lock() { /* Lock implementation */ } |
| 2548 |
func (m *Mutex) Unlock() { /* Unlock implementation */ } |
| 2549 |
|
| 2550 |
// NewMutex has the same composition as Mutex but its method set is empty. |
| 2551 |
type NewMutex Mutex |
| 2552 |
|
| 2553 |
// The method set of PtrMutex's underlying type *Mutex remains unchanged, |
| 2554 |
// but the method set of PtrMutex is empty. |
| 2555 |
type PtrMutex *Mutex |
| 2556 |
|
| 2557 |
// The method set of *PrintableMutex contains the methods |
| 2558 |
// Lock and Unlock bound to its embedded field Mutex. |
| 2559 |
type PrintableMutex struct { |
| 2560 |
Mutex |
| 2561 |
} |
| 2562 |
|
| 2563 |
// MyBlock is an interface type that has the same method set as Block. |
| 2564 |
type MyBlock Block |
| 2565 |
</pre> |
| 2566 |
|
| 2567 |
<p> |
| 2568 |
Type definitions may be used to define different boolean, numeric, |
| 2569 |
or string types and associate methods with them: |
| 2570 |
</p> |
| 2571 |
|
| 2572 |
<pre> |
| 2573 |
type TimeZone int |
| 2574 |
|
| 2575 |
const ( |
| 2576 |
EST TimeZone = -(5 + iota) |
| 2577 |
CST |
| 2578 |
MST |
| 2579 |
PST |
| 2580 |
) |
| 2581 |
|
| 2582 |
func (tz TimeZone) String() string { |
| 2583 |
return fmt.Sprintf("GMT%+dh", tz) |
| 2584 |
} |
| 2585 |
</pre> |
| 2586 |
|
| 2587 |
<p> |
| 2588 |
If the type definition specifies <a href="#Type_parameter_declarations">type parameters</a>, |
| 2589 |
the type name denotes a <i>generic type</i>. |
| 2590 |
Generic types must be <a href="#Instantiations">instantiated</a> when they |
| 2591 |
are used. |
| 2592 |
</p> |
| 2593 |
|
| 2594 |
<pre> |
| 2595 |
type List[T any] struct { |
| 2596 |
next *List[T] |
| 2597 |
value T |
| 2598 |
} |
| 2599 |
</pre> |
| 2600 |
|
| 2601 |
<p> |
| 2602 |
In a type definition the given type cannot be a type parameter. |
| 2603 |
</p> |
| 2604 |
|
| 2605 |
<pre> |
| 2606 |
type T[P any] P // illegal: P is a type parameter |
| 2607 |
|
| 2608 |
func f[P any]() { |
| 2609 |
type L P // illegal: P is a type parameter declared by the enclosing function |
| 2610 |
} |
| 2611 |
</pre> |
| 2612 |
|
| 2613 |
<p> |
| 2614 |
A generic type may also have <a href="#Method_declarations">methods</a> associated with it. |
| 2615 |
In this case, the method receivers must declare the same number of type parameters as |
| 2616 |
present in the generic type definition. |
| 2617 |
</p> |
| 2618 |
|
| 2619 |
<pre> |
| 2620 |
// The method Len returns the number of elements in the linked list l. |
| 2621 |
func (l *List[T]) Len() int { … } |
| 2622 |
</pre> |
| 2623 |
|
| 2624 |
<h3 id="Type_parameter_declarations">Type parameter declarations</h3> |
| 2625 |
|
| 2626 |
<p> |
| 2627 |
A type parameter list declares the <i>type parameters</i> of a generic function or type declaration. |
| 2628 |
The type parameter list looks like an ordinary <a href="#Function_types">function parameter list</a> |
| 2629 |
except that the type parameter names must all be present and the list is enclosed |
| 2630 |
in square brackets rather than parentheses |
| 2631 |
[<a href="#Go_1.18">Go 1.18</a>]. |
| 2632 |
</p> |
| 2633 |
|
| 2634 |
<pre class="ebnf"> |
| 2635 |
TypeParameters = "[" TypeParamList [ "," ] "]" . |
| 2636 |
TypeParamList = TypeParamDecl { "," TypeParamDecl } . |
| 2637 |
TypeParamDecl = IdentifierList TypeConstraint . |
| 2638 |
</pre> |
| 2639 |
|
| 2640 |
<p> |
| 2641 |
All non-blank names in the list must be unique. |
| 2642 |
Each name declares a type parameter, which is a new and different <a href="#Types">named type</a> |
| 2643 |
that acts as a placeholder for an (as of yet) unknown type in the declaration. |
| 2644 |
The type parameter is replaced with a <i>type argument</i> upon |
| 2645 |
<a href="#Instantiations">instantiation</a> of the generic function or type. |
| 2646 |
</p> |
| 2647 |
|
| 2648 |
<pre> |
| 2649 |
[P any] |
| 2650 |
[S interface{ ~[]byte|string }] |
| 2651 |
[S ~[]E, E any] |
| 2652 |
[P Constraint[int]] |
| 2653 |
[_ any] |
| 2654 |
</pre> |
| 2655 |
|
| 2656 |
<p> |
| 2657 |
Just as each ordinary function parameter has a parameter type, each type parameter |
| 2658 |
has a corresponding (meta-)type which is called its |
| 2659 |
<a href="#Type_constraints"><i>type constraint</i></a>. |
| 2660 |
</p> |
| 2661 |
|
| 2662 |
<p> |
| 2663 |
A parsing ambiguity arises when the type parameter list for a generic type |
| 2664 |
declares a single type parameter <code>P</code> with a constraint <code>C</code> |
| 2665 |
such that the text <code>P C</code> forms a valid expression: |
| 2666 |
</p> |
| 2667 |
|
| 2668 |
<pre> |
| 2669 |
type T[P *C] … |
| 2670 |
type T[P (C)] … |
| 2671 |
type T[P *C|Q] … |
| 2672 |
… |
| 2673 |
</pre> |
| 2674 |
|
| 2675 |
<p> |
| 2676 |
In these rare cases, the type parameter list is indistinguishable from an |
| 2677 |
expression and the type declaration is parsed as an array type declaration. |
| 2678 |
To resolve the ambiguity, embed the constraint in an |
| 2679 |
<a href="#Interface_types">interface</a> or use a trailing comma: |
| 2680 |
</p> |
| 2681 |
|
| 2682 |
<pre> |
| 2683 |
type T[P interface{*C}] … |
| 2684 |
type T[P *C,] … |
| 2685 |
</pre> |
| 2686 |
|
| 2687 |
<p> |
| 2688 |
Type parameters may also be declared by the receiver specification |
| 2689 |
of a <a href="#Method_declarations">method declaration</a> associated |
| 2690 |
with a generic type. |
| 2691 |
</p> |
| 2692 |
|
| 2693 |
<h4 id="Type_constraints">Type constraints</h4> |
| 2694 |
|
| 2695 |
<p> |
| 2696 |
A <i>type constraint</i> is an <a href="#Interface_types">interface</a> that defines the |
| 2697 |
set of permissible type arguments for the respective type parameter and controls the |
| 2698 |
operations supported by values of that type parameter |
| 2699 |
[<a href="#Go_1.18">Go 1.18</a>]. |
| 2700 |
</p> |
| 2701 |
|
| 2702 |
<pre class="ebnf"> |
| 2703 |
TypeConstraint = TypeElem . |
| 2704 |
</pre> |
| 2705 |
|
| 2706 |
<p> |
| 2707 |
If the constraint is an interface literal of the form <code>interface{E}</code> where |
| 2708 |
<code>E</code> is an embedded <a href="#Interface_types">type element</a> (not a method), in a type parameter list |
| 2709 |
the enclosing <code>interface{ … }</code> may be omitted for convenience: |
| 2710 |
</p> |
| 2711 |
|
| 2712 |
<pre> |
| 2713 |
[T []P] // = [T interface{[]P}] |
| 2714 |
[T ~int] // = [T interface{~int}] |
| 2715 |
[T int|string] // = [T interface{int|string}] |
| 2716 |
type Constraint ~int // illegal: ~int is not in a type parameter list |
| 2717 |
</pre> |
| 2718 |
|
| 2719 |
<!-- |
| 2720 |
We should be able to simplify the rules for comparable or delegate some of them |
| 2721 |
elsewhere since we have a section that clearly defines how interfaces implement |
| 2722 |
other interfaces based on their type sets. But this should get us going for now. |
| 2723 |
--> |
| 2724 |
|
| 2725 |
<p> |
| 2726 |
The <a href="#Predeclared_identifiers">predeclared</a> |
| 2727 |
<a href="#Interface_types">interface type</a> <code>comparable</code> |
| 2728 |
denotes the set of all non-interface types that are |
| 2729 |
<a href="#Comparison_operators">strictly comparable</a> |
| 2730 |
[<a href="#Go_1.18">Go 1.18</a>]. |
| 2731 |
</p> |
| 2732 |
|
| 2733 |
<p> |
| 2734 |
Even though interfaces that are not type parameters are <a href="#Comparison_operators">comparable</a>, |
| 2735 |
they are not strictly comparable and therefore they do not implement <code>comparable</code>. |
| 2736 |
However, they <a href="#Satisfying_a_type_constraint">satisfy</a> <code>comparable</code>. |
| 2737 |
</p> |
| 2738 |
|
| 2739 |
<pre> |
| 2740 |
int // implements comparable (int is strictly comparable) |
| 2741 |
[]byte // does not implement comparable (slices cannot be compared) |
| 2742 |
interface{} // does not implement comparable (see above) |
| 2743 |
interface{ ~int | ~string } // type parameter only: implements comparable (int, string types are strictly comparable) |
| 2744 |
interface{ comparable } // type parameter only: implements comparable (comparable implements itself) |
| 2745 |
interface{ ~int | ~[]byte } // type parameter only: does not implement comparable (slices are not comparable) |
| 2746 |
interface{ ~struct{ any } } // type parameter only: does not implement comparable (field any is not strictly comparable) |
| 2747 |
</pre> |
| 2748 |
|
| 2749 |
<p> |
| 2750 |
The <code>comparable</code> interface and interfaces that (directly or indirectly) embed |
| 2751 |
<code>comparable</code> may only be used as type constraints. They cannot be the types of |
| 2752 |
values or variables, or components of other, non-interface types. |
| 2753 |
</p> |
| 2754 |
|
| 2755 |
<h4 id="Satisfying_a_type_constraint">Satisfying a type constraint</h4> |
| 2756 |
|
| 2757 |
<p> |
| 2758 |
A type argument <code>T</code><i> satisfies</i> a type constraint <code>C</code> |
| 2759 |
if <code>T</code> is an element of the type set defined by <code>C</code>; in other words, |
| 2760 |
if <code>T</code> <a href="#Implementing_an_interface">implements</a> <code>C</code>. |
| 2761 |
As an exception, a <a href="#Comparison_operators">strictly comparable</a> |
| 2762 |
type constraint may also be satisfied by a <a href="#Comparison_operators">comparable</a> |
| 2763 |
(not necessarily strictly comparable) type argument |
| 2764 |
[<a href="#Go_1.20">Go 1.20</a>]. |
| 2765 |
More precisely: |
| 2766 |
</p> |
| 2767 |
|
| 2768 |
<p> |
| 2769 |
A type T <i>satisfies</i> a constraint <code>C</code> if |
| 2770 |
</p> |
| 2771 |
|
| 2772 |
<ul> |
| 2773 |
<li> |
| 2774 |
<code>T</code> <a href="#Implementing_an_interface">implements</a> <code>C</code>; or |
| 2775 |
</li> |
| 2776 |
<li> |
| 2777 |
<code>C</code> can be written in the form <code>interface{ comparable; E }</code>, |
| 2778 |
where <code>E</code> is a <a href="#Basic_interfaces">basic interface</a> and |
| 2779 |
<code>T</code> is <a href="#Comparison_operators">comparable</a> and implements <code>E</code>. |
| 2780 |
</li> |
| 2781 |
</ul> |
| 2782 |
|
| 2783 |
<pre> |
| 2784 |
type argument type constraint // constraint satisfaction |
| 2785 |
|
| 2786 |
int interface{ ~int } // satisfied: int implements interface{ ~int } |
| 2787 |
string comparable // satisfied: string implements comparable (string is strictly comparable) |
| 2788 |
[]byte comparable // not satisfied: slices are not comparable |
| 2789 |
any interface{ comparable; int } // not satisfied: any does not implement interface{ int } |
| 2790 |
any comparable // satisfied: any is comparable and implements the basic interface any |
| 2791 |
struct{f any} comparable // satisfied: struct{f any} is comparable and implements the basic interface any |
| 2792 |
any interface{ comparable; m() } // not satisfied: any does not implement the basic interface interface{ m() } |
| 2793 |
interface{ m() } interface{ comparable; m() } // satisfied: interface{ m() } is comparable and implements the basic interface interface{ m() } |
| 2794 |
</pre> |
| 2795 |
|
| 2796 |
<p> |
| 2797 |
Because of the exception in the constraint satisfaction rule, comparing operands of type parameter type |
| 2798 |
may panic at run-time (even though comparable type parameters are always strictly comparable). |
| 2799 |
</p> |
| 2800 |
|
| 2801 |
<h3 id="Variable_declarations">Variable declarations</h3> |
| 2802 |
|
| 2803 |
<p> |
| 2804 |
A variable declaration creates one or more <a href="#Variables">variables</a>, |
| 2805 |
binds corresponding identifiers to them, and gives each a type and an initial value. |
| 2806 |
</p> |
| 2807 |
|
| 2808 |
<pre class="ebnf"> |
| 2809 |
VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) . |
| 2810 |
VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) . |
| 2811 |
</pre> |
| 2812 |
|
| 2813 |
<pre> |
| 2814 |
var i int |
| 2815 |
var U, V, W float64 |
| 2816 |
var k = 0 |
| 2817 |
var x, y float32 = -1, -2 |
| 2818 |
var ( |
| 2819 |
i int |
| 2820 |
u, v, s = 2.0, 3.0, "bar" |
| 2821 |
) |
| 2822 |
var re, im = complexSqrt(-1) |
| 2823 |
var _, found = entries[name] // map lookup; only interested in "found" |
| 2824 |
</pre> |
| 2825 |
|
| 2826 |
<p> |
| 2827 |
If a list of expressions is given, the variables are initialized |
| 2828 |
with the expressions following the rules for <a href="#Assignment_statements">assignment statements</a>. |
| 2829 |
Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>. |
| 2830 |
</p> |
| 2831 |
|
| 2832 |
<p> |
| 2833 |
If a type is present, each variable is given that type. |
| 2834 |
Otherwise, each variable is given the type of the corresponding |
| 2835 |
initialization value in the assignment. |
| 2836 |
If that value is an untyped constant, it is first implicitly |
| 2837 |
<a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>; |
| 2838 |
if it is an untyped boolean value, it is first implicitly converted to type <code>bool</code>. |
| 2839 |
The predeclared identifier <code>nil</code> cannot be used to initialize a variable |
| 2840 |
with no explicit type. |
| 2841 |
</p> |
| 2842 |
|
| 2843 |
<pre> |
| 2844 |
var d = math.Sin(0.5) // d is float64 |
| 2845 |
var i = 42 // i is int |
| 2846 |
var t, ok = x.(T) // t is T, ok is bool |
| 2847 |
var n = nil // illegal |
| 2848 |
</pre> |
| 2849 |
|
| 2850 |
<p> |
| 2851 |
Implementation restriction: A compiler may make it illegal to declare a variable |
| 2852 |
inside a <a href="#Function_declarations">function body</a> if the variable is |
| 2853 |
never used. |
| 2854 |
</p> |
| 2855 |
|
| 2856 |
<h3 id="Short_variable_declarations">Short variable declarations</h3> |
| 2857 |
|
| 2858 |
<p> |
| 2859 |
A <i>short variable declaration</i> uses the syntax: |
| 2860 |
</p> |
| 2861 |
|
| 2862 |
<pre class="ebnf"> |
| 2863 |
ShortVarDecl = IdentifierList ":=" ExpressionList . |
| 2864 |
</pre> |
| 2865 |
|
| 2866 |
<p> |
| 2867 |
It is shorthand for a regular <a href="#Variable_declarations">variable declaration</a> |
| 2868 |
with initializer expressions but no types: |
| 2869 |
</p> |
| 2870 |
|
| 2871 |
<pre class="grammar"> |
| 2872 |
"var" IdentifierList "=" ExpressionList . |
| 2873 |
</pre> |
| 2874 |
|
| 2875 |
<pre> |
| 2876 |
i, j := 0, 10 |
| 2877 |
f := func() int { return 7 } |
| 2878 |
ch := make(chan int) |
| 2879 |
r, w, _ := os.Pipe() // os.Pipe() returns a connected pair of Files and an error, if any |
| 2880 |
_, y, _ := coord(p) // coord() returns three values; only interested in y coordinate |
| 2881 |
</pre> |
| 2882 |
|
| 2883 |
<p> |
| 2884 |
Unlike regular variable declarations, a short variable declaration may <i>redeclare</i> |
| 2885 |
variables provided they were originally declared earlier in the same block |
| 2886 |
(or the parameter lists if the block is the function body) with the same type, |
| 2887 |
and at least one of the non-<a href="#Blank_identifier">blank</a> variables is new. |
| 2888 |
As a consequence, redeclaration can only appear in a multi-variable short declaration. |
| 2889 |
Redeclaration does not introduce a new variable; it just assigns a new value to the original. |
| 2890 |
The non-blank variable names on the left side of <code>:=</code> |
| 2891 |
must be <a href="#Uniqueness_of_identifiers">unique</a>. |
| 2892 |
</p> |
| 2893 |
|
| 2894 |
<pre> |
| 2895 |
field1, offset := nextField(str, 0) |
| 2896 |
field2, offset := nextField(str, offset) // redeclares offset |
| 2897 |
x, y, x := 1, 2, 3 // illegal: x repeated on left side of := |
| 2898 |
</pre> |
| 2899 |
|
| 2900 |
<p> |
| 2901 |
Short variable declarations may appear only inside functions. |
| 2902 |
In some contexts such as the initializers for |
| 2903 |
<a href="#If_statements">"if"</a>, |
| 2904 |
<a href="#For_statements">"for"</a>, or |
| 2905 |
<a href="#Switch_statements">"switch"</a> statements, |
| 2906 |
they can be used to declare local temporary variables. |
| 2907 |
</p> |
| 2908 |
|
| 2909 |
<h3 id="Function_declarations">Function declarations</h3> |
| 2910 |
|
| 2911 |
<!-- |
| 2912 |
Given the importance of functions, this section has always |
| 2913 |
been woefully underdeveloped. Would be nice to expand this |
| 2914 |
a bit. |
| 2915 |
--> |
| 2916 |
|
| 2917 |
<p> |
| 2918 |
A function declaration binds an identifier, the <i>function name</i>, |
| 2919 |
to a function. |
| 2920 |
</p> |
| 2921 |
|
| 2922 |
<pre class="ebnf"> |
| 2923 |
FunctionDecl = "func" FunctionName [ TypeParameters ] Signature [ FunctionBody ] . |
| 2924 |
FunctionName = identifier . |
| 2925 |
FunctionBody = Block . |
| 2926 |
</pre> |
| 2927 |
|
| 2928 |
<p> |
| 2929 |
If the function's <a href="#Function_types">signature</a> declares |
| 2930 |
result parameters, the function body's statement list must end in |
| 2931 |
a <a href="#Terminating_statements">terminating statement</a>. |
| 2932 |
</p> |
| 2933 |
|
| 2934 |
<pre> |
| 2935 |
func IndexRune(s string, r rune) int { |
| 2936 |
for i, c := range s { |
| 2937 |
if c == r { |
| 2938 |
return i |
| 2939 |
} |
| 2940 |
} |
| 2941 |
// invalid: missing return statement |
| 2942 |
} |
| 2943 |
</pre> |
| 2944 |
|
| 2945 |
<p> |
| 2946 |
If the function declaration specifies <a href="#Type_parameter_declarations">type parameters</a>, |
| 2947 |
the function name denotes a <i>generic function</i>. |
| 2948 |
A generic function must be <a href="#Instantiations">instantiated</a> before it can be |
| 2949 |
called or used as a value. |
| 2950 |
</p> |
| 2951 |
|
| 2952 |
<pre> |
| 2953 |
func min[T ~int|~float64](x, y T) T { |
| 2954 |
if x < y { |
| 2955 |
return x |
| 2956 |
} |
| 2957 |
return y |
| 2958 |
} |
| 2959 |
</pre> |
| 2960 |
|
| 2961 |
<p> |
| 2962 |
A function declaration without type parameters may omit the body. |
| 2963 |
Such a declaration provides the signature for a function implemented outside Go, |
| 2964 |
such as an assembly routine. |
| 2965 |
</p> |
| 2966 |
|
| 2967 |
<pre> |
| 2968 |
func flushICache(begin, end uintptr) // implemented externally |
| 2969 |
</pre> |
| 2970 |
|
| 2971 |
<h3 id="Method_declarations">Method declarations</h3> |
| 2972 |
|
| 2973 |
<p> |
| 2974 |
A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>. |
| 2975 |
A method declaration binds an identifier, the <i>method name</i>, to a method, |
| 2976 |
and associates the method with the receiver's <i>base type</i>. |
| 2977 |
</p> |
| 2978 |
|
| 2979 |
<pre class="ebnf"> |
| 2980 |
MethodDecl = "func" Receiver MethodName Signature [ FunctionBody ] . |
| 2981 |
Receiver = Parameters . |
| 2982 |
</pre> |
| 2983 |
|
| 2984 |
<p> |
| 2985 |
The receiver is specified via an extra parameter section preceding the method |
| 2986 |
name. That parameter section must declare a single non-variadic parameter, the receiver. |
| 2987 |
Its type must be a <a href="#Type_definitions">defined</a> type <code>T</code> or a |
| 2988 |
pointer to a defined type <code>T</code>, possibly followed by a list of type parameter |
| 2989 |
names <code>[P1, P2, …]</code> enclosed in square brackets. |
| 2990 |
<code>T</code> is called the receiver <i>base type</i>. A receiver base type cannot be |
| 2991 |
a pointer or interface type and it must be defined in the same package as the method. |
| 2992 |
The method is said to be <i>bound</i> to its receiver base type and the method name |
| 2993 |
is visible only within <a href="#Selectors">selectors</a> for type <code>T</code> |
| 2994 |
or <code>*T</code>. |
| 2995 |
</p> |
| 2996 |
|
| 2997 |
<p> |
| 2998 |
A non-<a href="#Blank_identifier">blank</a> receiver identifier must be |
| 2999 |
<a href="#Uniqueness_of_identifiers">unique</a> in the method signature. |
| 3000 |
If the receiver's value is not referenced inside the body of the method, |
| 3001 |
its identifier may be omitted in the declaration. The same applies in |
| 3002 |
general to parameters of functions and methods. |
| 3003 |
</p> |
| 3004 |
|
| 3005 |
<p> |
| 3006 |
For a base type, the non-blank names of methods bound to it must be unique. |
| 3007 |
If the base type is a <a href="#Struct_types">struct type</a>, |
| 3008 |
the non-blank method and field names must be distinct. |
| 3009 |
</p> |
| 3010 |
|
| 3011 |
<p> |
| 3012 |
Given defined type <code>Point</code> the declarations |
| 3013 |
</p> |
| 3014 |
|
| 3015 |
<pre> |
| 3016 |
func (p *Point) Length() float64 { |
| 3017 |
return math.Sqrt(p.x * p.x + p.y * p.y) |
| 3018 |
} |
| 3019 |
|
| 3020 |
func (p *Point) Scale(factor float64) { |
| 3021 |
p.x *= factor |
| 3022 |
p.y *= factor |
| 3023 |
} |
| 3024 |
</pre> |
| 3025 |
|
| 3026 |
<p> |
| 3027 |
bind the methods <code>Length</code> and <code>Scale</code>, |
| 3028 |
with receiver type <code>*Point</code>, |
| 3029 |
to the base type <code>Point</code>. |
| 3030 |
</p> |
| 3031 |
|
| 3032 |
<p> |
| 3033 |
If the receiver base type is a <a href="#Type_definitions">generic type</a>, the |
| 3034 |
receiver specification must declare corresponding type parameters for the method |
| 3035 |
to use. This makes the receiver type parameters available to the method. |
| 3036 |
Syntactically, this type parameter declaration looks like an |
| 3037 |
<a href="#Instantiations">instantiation</a> of the receiver base type: the type |
| 3038 |
arguments must be identifiers denoting the type parameters being declared, one |
| 3039 |
for each type parameter of the receiver base type. |
| 3040 |
The type parameter names do not need to match their corresponding parameter names in the |
| 3041 |
receiver base type definition, and all non-blank parameter names must be unique in the |
| 3042 |
receiver parameter section and the method signature. |
| 3043 |
The receiver type parameter constraints are implied by the receiver base type definition: |
| 3044 |
corresponding type parameters have corresponding constraints. |
| 3045 |
</p> |
| 3046 |
|
| 3047 |
<pre> |
| 3048 |
type Pair[A, B any] struct { |
| 3049 |
a A |
| 3050 |
b B |
| 3051 |
} |
| 3052 |
|
| 3053 |
func (p Pair[A, B]) Swap() Pair[B, A] { … } // receiver declares A, B |
| 3054 |
func (p Pair[First, _]) First() First { … } // receiver declares First, corresponds to A in Pair |
| 3055 |
</pre> |
| 3056 |
|
| 3057 |
<p> |
| 3058 |
If the receiver type is denoted by (a pointer to) an <a href="#Alias_declarations">alias</a>, |
| 3059 |
the alias must not be generic and it must not denote an instantiated generic type, neither |
| 3060 |
directly nor indirectly via another alias, and irrespective of pointer indirections. |
| 3061 |
</p> |
| 3062 |
|
| 3063 |
<pre> |
| 3064 |
type GPoint[P any] = Point |
| 3065 |
type HPoint = *GPoint[int] |
| 3066 |
type IPair = Pair[int, int] |
| 3067 |
|
| 3068 |
func (*GPoint[P]) Draw(P) { … } // illegal: alias must not be generic |
| 3069 |
func (HPoint) Draw(P) { … } // illegal: alias must not denote instantiated type GPoint[int] |
| 3070 |
func (*IPair) Second() int { … } // illegal: alias must not denote instantiated type Pair[int, int] |
| 3071 |
</pre> |
| 3072 |
|
| 3073 |
<h2 id="Expressions">Expressions</h2> |
| 3074 |
|
| 3075 |
<p> |
| 3076 |
An expression specifies the computation of a value by applying |
| 3077 |
operators and functions to operands. |
| 3078 |
</p> |
| 3079 |
|
| 3080 |
<h3 id="Operands">Operands</h3> |
| 3081 |
|
| 3082 |
<p> |
| 3083 |
Operands denote the elementary values in an expression. An operand may be a |
| 3084 |
literal, a (possibly <a href="#Qualified_identifiers">qualified</a>) |
| 3085 |
non-<a href="#Blank_identifier">blank</a> identifier denoting a |
| 3086 |
<a href="#Constant_declarations">constant</a>, |
| 3087 |
<a href="#Variable_declarations">variable</a>, or |
| 3088 |
<a href="#Function_declarations">function</a>, |
| 3089 |
or a parenthesized expression. |
| 3090 |
</p> |
| 3091 |
|
| 3092 |
<pre class="ebnf"> |
| 3093 |
Operand = Literal | OperandName [ TypeArgs ] | "(" Expression ")" . |
| 3094 |
Literal = BasicLit | CompositeLit | FunctionLit . |
| 3095 |
BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit . |
| 3096 |
OperandName = identifier | QualifiedIdent . |
| 3097 |
</pre> |
| 3098 |
|
| 3099 |
<p> |
| 3100 |
An operand name denoting a <a href="#Function_declarations">generic function</a> |
| 3101 |
may be followed by a list of <a href="#Instantiations">type arguments</a>; the |
| 3102 |
resulting operand is an <a href="#Instantiations">instantiated</a> function. |
| 3103 |
</p> |
| 3104 |
|
| 3105 |
<p> |
| 3106 |
The <a href="#Blank_identifier">blank identifier</a> may appear as an |
| 3107 |
operand only on the left-hand side of an <a href="#Assignment_statements">assignment statement</a>. |
| 3108 |
</p> |
| 3109 |
|
| 3110 |
<p> |
| 3111 |
Implementation restriction: A compiler need not report an error if an operand's |
| 3112 |
type is a <a href="#Type_parameter_declarations">type parameter</a> with an empty |
| 3113 |
<a href="#Interface_types">type set</a>. Functions with such type parameters |
| 3114 |
cannot be <a href="#Instantiations">instantiated</a>; any attempt will lead |
| 3115 |
to an error at the instantiation site. |
| 3116 |
</p> |
| 3117 |
|
| 3118 |
<h3 id="Qualified_identifiers">Qualified identifiers</h3> |
| 3119 |
|
| 3120 |
<p> |
| 3121 |
A <i>qualified identifier</i> is an identifier qualified with a package name prefix. |
| 3122 |
Both the package name and the identifier must not be |
| 3123 |
<a href="#Blank_identifier">blank</a>. |
| 3124 |
</p> |
| 3125 |
|
| 3126 |
<pre class="ebnf"> |
| 3127 |
QualifiedIdent = PackageName "." identifier . |
| 3128 |
</pre> |
| 3129 |
|
| 3130 |
<p> |
| 3131 |
A qualified identifier accesses an identifier in a different package, which |
| 3132 |
must be <a href="#Import_declarations">imported</a>. |
| 3133 |
The identifier must be <a href="#Exported_identifiers">exported</a> and |
| 3134 |
declared in the <a href="#Blocks">package block</a> of that package. |
| 3135 |
</p> |
| 3136 |
|
| 3137 |
<pre> |
| 3138 |
math.Sin // denotes the Sin function in package math |
| 3139 |
</pre> |
| 3140 |
|
| 3141 |
<h3 id="Composite_literals">Composite literals</h3> |
| 3142 |
|
| 3143 |
<p> |
| 3144 |
Composite literals construct new values for structs, arrays, slices, and maps |
| 3145 |
each time they are evaluated. |
| 3146 |
They consist of the type of the literal followed by a (possibly empty) |
| 3147 |
brace-bound list of elements. |
| 3148 |
Each element may optionally be preceded by a corresponding key. |
| 3149 |
</p> |
| 3150 |
|
| 3151 |
<pre class="ebnf"> |
| 3152 |
CompositeLit = LiteralType LiteralValue . |
| 3153 |
LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | |
| 3154 |
SliceType | MapType | TypeName [ TypeArgs ] . |
| 3155 |
LiteralValue = "{" [ ElementList [ "," ] ] "}" . |
| 3156 |
ElementList = KeyedElement { "," KeyedElement } . |
| 3157 |
KeyedElement = [ Key ":" ] Element . |
| 3158 |
Key = FieldName | Expression | LiteralValue . |
| 3159 |
FieldName = identifier . |
| 3160 |
Element = Expression | LiteralValue . |
| 3161 |
</pre> |
| 3162 |
|
| 3163 |
<p> |
| 3164 |
Unless the LiteralType is a type parameter, |
| 3165 |
its <a href="#Underlying_types">underlying type</a> |
| 3166 |
must be a struct, array, slice, or map type |
| 3167 |
(the syntax enforces this constraint except when the type is given |
| 3168 |
as a TypeName). |
| 3169 |
If the LiteralType is a type parameter, all types in its type set |
| 3170 |
must have the same underlying type which must be |
| 3171 |
a valid composite literal type. |
| 3172 |
</p> |
| 3173 |
|
| 3174 |
<p> |
| 3175 |
The types of the elements and keys must be <a href="#Assignability">assignable</a> |
| 3176 |
to the respective field, element, and key types of the LiteralType; |
| 3177 |
there is no additional conversion. |
| 3178 |
The key is interpreted as a field name for struct literals, |
| 3179 |
an index for array and slice literals, and a key for map literals. |
| 3180 |
It is an error to specify multiple elements with the same field name |
| 3181 |
or constant key value. |
| 3182 |
A literal may omit the element list; such a literal evaluates |
| 3183 |
to the zero value for its type. |
| 3184 |
</p> |
| 3185 |
|
| 3186 |
<p> |
| 3187 |
A parsing ambiguity arises when a composite literal using the |
| 3188 |
TypeName form of the LiteralType appears as an operand between the |
| 3189 |
<a href="#Keywords">keyword</a> and the opening brace of the block |
| 3190 |
of an "if", "for", or "switch" statement, and the composite literal |
| 3191 |
is not enclosed in parentheses, square brackets, or curly braces. |
| 3192 |
In this rare case, the opening brace of the literal is erroneously parsed |
| 3193 |
as the one introducing the block of statements. To resolve the ambiguity, |
| 3194 |
the composite literal must appear within parentheses. |
| 3195 |
</p> |
| 3196 |
|
| 3197 |
<pre> |
| 3198 |
if x == (T{a,b,c}[i]) { … } |
| 3199 |
if (x == T{a,b,c}[i]) { … } |
| 3200 |
</pre> |
| 3201 |
|
| 3202 |
<h4>Struct literals</h4> |
| 3203 |
|
| 3204 |
<p> |
| 3205 |
For struct literals without keys, the element list must contain an element |
| 3206 |
for each struct field in the order in which the fields are declared. |
| 3207 |
</p> |
| 3208 |
|
| 3209 |
<p> |
| 3210 |
For struct literals with keys the following rules apply: |
| 3211 |
</p> |
| 3212 |
<ul> |
| 3213 |
<li>Every element must have a key. |
| 3214 |
</li> |
| 3215 |
<li>Each key must be a field name declared in the struct type. |
| 3216 |
</li> |
| 3217 |
<li>The element list does not need to have an element for each struct field. |
| 3218 |
Omitted fields get the zero value for that field. |
| 3219 |
</li> |
| 3220 |
<li>It is an error to specify an element for a non-exported |
| 3221 |
field of a struct belonging to a different package. |
| 3222 |
</li> |
| 3223 |
</ul> |
| 3224 |
|
| 3225 |
<p> |
| 3226 |
Given the declarations |
| 3227 |
</p> |
| 3228 |
<pre> |
| 3229 |
type Point3D struct { x, y, z float64 } |
| 3230 |
type Line struct { p, q Point3D } |
| 3231 |
</pre> |
| 3232 |
|
| 3233 |
<p> |
| 3234 |
one may write |
| 3235 |
</p> |
| 3236 |
|
| 3237 |
<pre> |
| 3238 |
origin := Point3D{} // zero value for Point3D |
| 3239 |
line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x |
| 3240 |
</pre> |
| 3241 |
|
| 3242 |
<h4>Array and slice literals</h4> |
| 3243 |
|
| 3244 |
<p> |
| 3245 |
For array and slice literals the following rules apply: |
| 3246 |
</p> |
| 3247 |
<ul> |
| 3248 |
<li>Each element has an associated integer index marking |
| 3249 |
its position in the array. |
| 3250 |
</li> |
| 3251 |
<li>An element with a key uses the key as its index. The |
| 3252 |
key must be a non-negative constant |
| 3253 |
<a href="#Representability">representable</a> by |
| 3254 |
a value of type <code>int</code>; and if it is typed |
| 3255 |
it must be of <a href="#Numeric_types">integer type</a>. |
| 3256 |
</li> |
| 3257 |
<li>An element without a key uses the previous element's index plus one. |
| 3258 |
If the first element has no key, its index is zero. |
| 3259 |
</li> |
| 3260 |
</ul> |
| 3261 |
|
| 3262 |
<p> |
| 3263 |
<a href="#Address_operators">Taking the address</a> of a composite literal |
| 3264 |
generates a pointer to a unique <a href="#Variables">variable</a> initialized |
| 3265 |
with the literal's value. |
| 3266 |
</p> |
| 3267 |
|
| 3268 |
<pre> |
| 3269 |
var pointer *Point3D = &Point3D{y: 1000} |
| 3270 |
</pre> |
| 3271 |
|
| 3272 |
<p> |
| 3273 |
Note that the <a href="#The_zero_value">zero value</a> for a slice or map |
| 3274 |
type is not the same as an initialized but empty value of the same type. |
| 3275 |
Consequently, taking the address of an empty slice or map composite literal |
| 3276 |
does not have the same effect as allocating a new slice or map value with |
| 3277 |
<a href="#Allocation">new</a>. |
| 3278 |
</p> |
| 3279 |
|
| 3280 |
<pre> |
| 3281 |
p1 := &[]int{} // p1 points to an initialized, empty slice with value []int{} and length 0 |
| 3282 |
p2 := new([]int) // p2 points to an uninitialized slice with value nil and length 0 |
| 3283 |
</pre> |
| 3284 |
|
| 3285 |
<p> |
| 3286 |
The length of an array literal is the length specified in the literal type. |
| 3287 |
If fewer elements than the length are provided in the literal, the missing |
| 3288 |
elements are set to the zero value for the array element type. |
| 3289 |
It is an error to provide elements with index values outside the index range |
| 3290 |
of the array. The notation <code>...</code> specifies an array length equal |
| 3291 |
to the maximum element index plus one. |
| 3292 |
</p> |
| 3293 |
|
| 3294 |
<pre> |
| 3295 |
buffer := [10]string{} // len(buffer) == 10 |
| 3296 |
intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6 |
| 3297 |
days := [...]string{"Sat", "Sun"} // len(days) == 2 |
| 3298 |
</pre> |
| 3299 |
|
| 3300 |
<p> |
| 3301 |
A slice literal describes the entire underlying array literal. |
| 3302 |
Thus the length and capacity of a slice literal are the maximum |
| 3303 |
element index plus one. A slice literal has the form |
| 3304 |
</p> |
| 3305 |
|
| 3306 |
<pre> |
| 3307 |
[]T{x1, x2, … xn} |
| 3308 |
</pre> |
| 3309 |
|
| 3310 |
<p> |
| 3311 |
and is shorthand for a slice operation applied to an array: |
| 3312 |
</p> |
| 3313 |
|
| 3314 |
<pre> |
| 3315 |
tmp := [n]T{x1, x2, … xn} |
| 3316 |
tmp[0 : n] |
| 3317 |
</pre> |
| 3318 |
|
| 3319 |
<h4>Map literals</h4> |
| 3320 |
|
| 3321 |
<p> |
| 3322 |
For map literals, each element must have a key. |
| 3323 |
For non-constant map keys, see the section on |
| 3324 |
<a href="#Order_of_evaluation">evaluation order</a>. |
| 3325 |
</p> |
| 3326 |
|
| 3327 |
<h4>Elision of element types</h4> |
| 3328 |
|
| 3329 |
<p> |
| 3330 |
Within a composite literal of array, slice, or map type <code>T</code>, |
| 3331 |
elements or map keys that are themselves composite literals may elide the respective |
| 3332 |
literal type if it is identical to the element or key type of <code>T</code>. |
| 3333 |
Similarly, elements or keys that are addresses of composite literals may elide |
| 3334 |
the <code>&T</code> when the element or key type is <code>*T</code>. |
| 3335 |
</p> |
| 3336 |
|
| 3337 |
<pre> |
| 3338 |
[...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}} |
| 3339 |
[][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}} |
| 3340 |
[][]Point{{{0, 1}, {1, 2}}} // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}} |
| 3341 |
map[string]Point{"orig": {0, 0}} // same as map[string]Point{"orig": Point{0, 0}} |
| 3342 |
map[Point]string{{0, 0}: "orig"} // same as map[Point]string{Point{0, 0}: "orig"} |
| 3343 |
|
| 3344 |
type PPoint *Point |
| 3345 |
[2]*Point{{1.5, -3.5}, {}} // same as [2]*Point{&Point{1.5, -3.5}, &Point{}} |
| 3346 |
[2]PPoint{{1.5, -3.5}, {}} // same as [2]PPoint{PPoint(&Point{1.5, -3.5}), PPoint(&Point{})} |
| 3347 |
</pre> |
| 3348 |
|
| 3349 |
<p> |
| 3350 |
Examples of valid array, slice, and map literals: |
| 3351 |
</p> |
| 3352 |
|
| 3353 |
<pre> |
| 3354 |
// list of prime numbers |
| 3355 |
primes := []int{2, 3, 5, 7, 9, 2147483647} |
| 3356 |
|
| 3357 |
// vowels[ch] is true if ch is a vowel |
| 3358 |
vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true} |
| 3359 |
|
| 3360 |
// the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1} |
| 3361 |
filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1} |
| 3362 |
|
| 3363 |
// frequencies in Hz for equal-tempered scale (A4 = 440Hz) |
| 3364 |
noteFrequency := map[string]float32{ |
| 3365 |
"C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83, |
| 3366 |
"G0": 24.50, "A0": 27.50, "B0": 30.87, |
| 3367 |
} |
| 3368 |
</pre> |
| 3369 |
|
| 3370 |
<h3 id="Function_literals">Function literals</h3> |
| 3371 |
|
| 3372 |
<p> |
| 3373 |
A function literal represents an anonymous <a href="#Function_declarations">function</a>. |
| 3374 |
Function literals cannot declare type parameters. |
| 3375 |
</p> |
| 3376 |
|
| 3377 |
<pre class="ebnf"> |
| 3378 |
FunctionLit = "func" Signature FunctionBody . |
| 3379 |
</pre> |
| 3380 |
|
| 3381 |
<pre> |
| 3382 |
func(a, b int, z float64) bool { return a*b < int(z) } |
| 3383 |
</pre> |
| 3384 |
|
| 3385 |
<p> |
| 3386 |
A function literal can be assigned to a variable or invoked directly. |
| 3387 |
</p> |
| 3388 |
|
| 3389 |
<pre> |
| 3390 |
f := func(x, y int) int { return x + y } |
| 3391 |
func(ch chan int) { ch <- ACK }(replyChan) |
| 3392 |
</pre> |
| 3393 |
|
| 3394 |
<p> |
| 3395 |
Function literals are <i>closures</i>: they may refer to variables |
| 3396 |
defined in a surrounding function. Those variables are then shared between |
| 3397 |
the surrounding function and the function literal, and they survive as long |
| 3398 |
as they are accessible. |
| 3399 |
</p> |
| 3400 |
|
| 3401 |
|
| 3402 |
<h3 id="Primary_expressions">Primary expressions</h3> |
| 3403 |
|
| 3404 |
<p> |
| 3405 |
Primary expressions are the operands for unary and binary expressions. |
| 3406 |
</p> |
| 3407 |
|
| 3408 |
<pre class="ebnf"> |
| 3409 |
PrimaryExpr = Operand | |
| 3410 |
Conversion | |
| 3411 |
MethodExpr | |
| 3412 |
PrimaryExpr Selector | |
| 3413 |
PrimaryExpr Index | |
| 3414 |
PrimaryExpr Slice | |
| 3415 |
PrimaryExpr TypeAssertion | |
| 3416 |
PrimaryExpr Arguments . |
| 3417 |
|
| 3418 |
Selector = "." identifier . |
| 3419 |
Index = "[" Expression [ "," ] "]" . |
| 3420 |
Slice = "[" [ Expression ] ":" [ Expression ] "]" | |
| 3421 |
"[" [ Expression ] ":" Expression ":" Expression "]" . |
| 3422 |
TypeAssertion = "." "(" Type ")" . |
| 3423 |
Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" . |
| 3424 |
</pre> |
| 3425 |
|
| 3426 |
|
| 3427 |
<pre> |
| 3428 |
x |
| 3429 |
2 |
| 3430 |
(s + ".txt") |
| 3431 |
f(3.1415, true) |
| 3432 |
Point{1, 2} |
| 3433 |
m["foo"] |
| 3434 |
s[i : j + 1] |
| 3435 |
obj.color |
| 3436 |
f.p[i].x() |
| 3437 |
</pre> |
| 3438 |
|
| 3439 |
|
| 3440 |
<h3 id="Selectors">Selectors</h3> |
| 3441 |
|
| 3442 |
<p> |
| 3443 |
For a <a href="#Primary_expressions">primary expression</a> <code>x</code> |
| 3444 |
that is not a <a href="#Package_clause">package name</a>, the |
| 3445 |
<i>selector expression</i> |
| 3446 |
</p> |
| 3447 |
|
| 3448 |
<pre> |
| 3449 |
x.f |
| 3450 |
</pre> |
| 3451 |
|
| 3452 |
<p> |
| 3453 |
denotes the field or method <code>f</code> of the value <code>x</code> |
| 3454 |
(or sometimes <code>*x</code>; see below). |
| 3455 |
The identifier <code>f</code> is called the (field or method) <i>selector</i>; |
| 3456 |
it must not be the <a href="#Blank_identifier">blank identifier</a>. |
| 3457 |
The type of the selector expression is the type of <code>f</code>. |
| 3458 |
If <code>x</code> is a package name, see the section on |
| 3459 |
<a href="#Qualified_identifiers">qualified identifiers</a>. |
| 3460 |
</p> |
| 3461 |
|
| 3462 |
<p> |
| 3463 |
A selector <code>f</code> may denote a field or method <code>f</code> of |
| 3464 |
a type <code>T</code>, or it may refer |
| 3465 |
to a field or method <code>f</code> of a nested |
| 3466 |
<a href="#Struct_types">embedded field</a> of <code>T</code>. |
| 3467 |
The number of embedded fields traversed |
| 3468 |
to reach <code>f</code> is called its <i>depth</i> in <code>T</code>. |
| 3469 |
The depth of a field or method <code>f</code> |
| 3470 |
declared in <code>T</code> is zero. |
| 3471 |
The depth of a field or method <code>f</code> declared in |
| 3472 |
an embedded field <code>A</code> in <code>T</code> is the |
| 3473 |
depth of <code>f</code> in <code>A</code> plus one. |
| 3474 |
</p> |
| 3475 |
|
| 3476 |
<p> |
| 3477 |
The following rules apply to selectors: |
| 3478 |
</p> |
| 3479 |
|
| 3480 |
<ol> |
| 3481 |
<li> |
| 3482 |
For a value <code>x</code> of type <code>T</code> or <code>*T</code> |
| 3483 |
where <code>T</code> is not a pointer or interface type, |
| 3484 |
<code>x.f</code> denotes the field or method at the shallowest depth |
| 3485 |
in <code>T</code> where there is such an <code>f</code>. |
| 3486 |
If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a> |
| 3487 |
with shallowest depth, the selector expression is illegal. |
| 3488 |
</li> |
| 3489 |
|
| 3490 |
<li> |
| 3491 |
For a value <code>x</code> of type <code>I</code> where <code>I</code> |
| 3492 |
is an interface type, <code>x.f</code> denotes the actual method with name |
| 3493 |
<code>f</code> of the dynamic value of <code>x</code>. |
| 3494 |
If there is no method with name <code>f</code> in the |
| 3495 |
<a href="#Method_sets">method set</a> of <code>I</code>, the selector |
| 3496 |
expression is illegal. |
| 3497 |
</li> |
| 3498 |
|
| 3499 |
<li> |
| 3500 |
As an exception, if the type of <code>x</code> is a <a href="#Type_definitions">defined</a> |
| 3501 |
pointer type and <code>(*x).f</code> is a valid selector expression denoting a field |
| 3502 |
(but not a method), <code>x.f</code> is shorthand for <code>(*x).f</code>. |
| 3503 |
</li> |
| 3504 |
|
| 3505 |
<li> |
| 3506 |
In all other cases, <code>x.f</code> is illegal. |
| 3507 |
</li> |
| 3508 |
|
| 3509 |
<li> |
| 3510 |
If <code>x</code> is of pointer type and has the value |
| 3511 |
<code>nil</code> and <code>x.f</code> denotes a struct field, |
| 3512 |
assigning to or evaluating <code>x.f</code> |
| 3513 |
causes a <a href="#Run_time_panics">run-time panic</a>. |
| 3514 |
</li> |
| 3515 |
|
| 3516 |
<li> |
| 3517 |
If <code>x</code> is of interface type and has the value |
| 3518 |
<code>nil</code>, <a href="#Calls">calling</a> or |
| 3519 |
<a href="#Method_values">evaluating</a> the method <code>x.f</code> |
| 3520 |
causes a <a href="#Run_time_panics">run-time panic</a>. |
| 3521 |
</li> |
| 3522 |
</ol> |
| 3523 |
|
| 3524 |
<p> |
| 3525 |
For example, given the declarations: |
| 3526 |
</p> |
| 3527 |
|
| 3528 |
<pre> |
| 3529 |
type T0 struct { |
| 3530 |
x int |
| 3531 |
} |
| 3532 |
|
| 3533 |
func (*T0) M0() |
| 3534 |
|
| 3535 |
type T1 struct { |
| 3536 |
y int |
| 3537 |
} |
| 3538 |
|
| 3539 |
func (T1) M1() |
| 3540 |
|
| 3541 |
type T2 struct { |
| 3542 |
z int |
| 3543 |
T1 |
| 3544 |
*T0 |
| 3545 |
} |
| 3546 |
|
| 3547 |
func (*T2) M2() |
| 3548 |
|
| 3549 |
type Q *T2 |
| 3550 |
|
| 3551 |
var t T2 // with t.T0 != nil |
| 3552 |
var p *T2 // with p != nil and (*p).T0 != nil |
| 3553 |
var q Q = p |
| 3554 |
</pre> |
| 3555 |
|
| 3556 |
<p> |
| 3557 |
one may write: |
| 3558 |
</p> |
| 3559 |
|
| 3560 |
<pre> |
| 3561 |
t.z // t.z |
| 3562 |
t.y // t.T1.y |
| 3563 |
t.x // (*t.T0).x |
| 3564 |
|
| 3565 |
p.z // (*p).z |
| 3566 |
p.y // (*p).T1.y |
| 3567 |
p.x // (*(*p).T0).x |
| 3568 |
|
| 3569 |
q.x // (*(*q).T0).x (*q).x is a valid field selector |
| 3570 |
|
| 3571 |
p.M0() // ((*p).T0).M0() M0 expects *T0 receiver |
| 3572 |
p.M1() // ((*p).T1).M1() M1 expects T1 receiver |
| 3573 |
p.M2() // p.M2() M2 expects *T2 receiver |
| 3574 |
t.M2() // (&t).M2() M2 expects *T2 receiver, see section on Calls |
| 3575 |
</pre> |
| 3576 |
|
| 3577 |
<p> |
| 3578 |
but the following is invalid: |
| 3579 |
</p> |
| 3580 |
|
| 3581 |
<pre> |
| 3582 |
q.M0() // (*q).M0 is valid but not a field selector |
| 3583 |
</pre> |
| 3584 |
|
| 3585 |
|
| 3586 |
<h3 id="Method_expressions">Method expressions</h3> |
| 3587 |
|
| 3588 |
<p> |
| 3589 |
If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>, |
| 3590 |
<code>T.M</code> is a function that is callable as a regular function |
| 3591 |
with the same arguments as <code>M</code> prefixed by an additional |
| 3592 |
argument that is the receiver of the method. |
| 3593 |
</p> |
| 3594 |
|
| 3595 |
<pre class="ebnf"> |
| 3596 |
MethodExpr = ReceiverType "." MethodName . |
| 3597 |
ReceiverType = Type . |
| 3598 |
</pre> |
| 3599 |
|
| 3600 |
<p> |
| 3601 |
Consider a struct type <code>T</code> with two methods, |
| 3602 |
<code>Mv</code>, whose receiver is of type <code>T</code>, and |
| 3603 |
<code>Mp</code>, whose receiver is of type <code>*T</code>. |
| 3604 |
</p> |
| 3605 |
|
| 3606 |
<pre> |
| 3607 |
type T struct { |
| 3608 |
a int |
| 3609 |
} |
| 3610 |
func (tv T) Mv(a int) int { return 0 } // value receiver |
| 3611 |
func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver |
| 3612 |
|
| 3613 |
var t T |
| 3614 |
</pre> |
| 3615 |
|
| 3616 |
<p> |
| 3617 |
The expression |
| 3618 |
</p> |
| 3619 |
|
| 3620 |
<pre> |
| 3621 |
T.Mv |
| 3622 |
</pre> |
| 3623 |
|
| 3624 |
<p> |
| 3625 |
yields a function equivalent to <code>Mv</code> but |
| 3626 |
with an explicit receiver as its first argument; it has signature |
| 3627 |
</p> |
| 3628 |
|
| 3629 |
<pre> |
| 3630 |
func(tv T, a int) int |
| 3631 |
</pre> |
| 3632 |
|
| 3633 |
<p> |
| 3634 |
That function may be called normally with an explicit receiver, so |
| 3635 |
these five invocations are equivalent: |
| 3636 |
</p> |
| 3637 |
|
| 3638 |
<pre> |
| 3639 |
t.Mv(7) |
| 3640 |
T.Mv(t, 7) |
| 3641 |
(T).Mv(t, 7) |
| 3642 |
f1 := T.Mv; f1(t, 7) |
| 3643 |
f2 := (T).Mv; f2(t, 7) |
| 3644 |
</pre> |
| 3645 |
|
| 3646 |
<p> |
| 3647 |
Similarly, the expression |
| 3648 |
</p> |
| 3649 |
|
| 3650 |
<pre> |
| 3651 |
(*T).Mp |
| 3652 |
</pre> |
| 3653 |
|
| 3654 |
<p> |
| 3655 |
yields a function value representing <code>Mp</code> with signature |
| 3656 |
</p> |
| 3657 |
|
| 3658 |
<pre> |
| 3659 |
func(tp *T, f float32) float32 |
| 3660 |
</pre> |
| 3661 |
|
| 3662 |
<p> |
| 3663 |
For a method with a value receiver, one can derive a function |
| 3664 |
with an explicit pointer receiver, so |
| 3665 |
</p> |
| 3666 |
|
| 3667 |
<pre> |
| 3668 |
(*T).Mv |
| 3669 |
</pre> |
| 3670 |
|
| 3671 |
<p> |
| 3672 |
yields a function value representing <code>Mv</code> with signature |
| 3673 |
</p> |
| 3674 |
|
| 3675 |
<pre> |
| 3676 |
func(tv *T, a int) int |
| 3677 |
</pre> |
| 3678 |
|
| 3679 |
<p> |
| 3680 |
Such a function indirects through the receiver to create a value |
| 3681 |
to pass as the receiver to the underlying method; |
| 3682 |
the method does not overwrite the value whose address is passed in |
| 3683 |
the function call. |
| 3684 |
</p> |
| 3685 |
|
| 3686 |
<p> |
| 3687 |
The final case, a value-receiver function for a pointer-receiver method, |
| 3688 |
is illegal because pointer-receiver methods are not in the method set |
| 3689 |
of the value type. |
| 3690 |
</p> |
| 3691 |
|
| 3692 |
<p> |
| 3693 |
Function values derived from methods are called with function call syntax; |
| 3694 |
the receiver is provided as the first argument to the call. |
| 3695 |
That is, given <code>f := T.Mv</code>, <code>f</code> is invoked |
| 3696 |
as <code>f(t, 7)</code> not <code>t.f(7)</code>. |
| 3697 |
To construct a function that binds the receiver, use a |
| 3698 |
<a href="#Function_literals">function literal</a> or |
| 3699 |
<a href="#Method_values">method value</a>. |
| 3700 |
</p> |
| 3701 |
|
| 3702 |
<p> |
| 3703 |
It is legal to derive a function value from a method of an interface type. |
| 3704 |
The resulting function takes an explicit receiver of that interface type. |
| 3705 |
</p> |
| 3706 |
|
| 3707 |
<h3 id="Method_values">Method values</h3> |
| 3708 |
|
| 3709 |
<p> |
| 3710 |
If the expression <code>x</code> has static type <code>T</code> and |
| 3711 |
<code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>, |
| 3712 |
<code>x.M</code> is called a <i>method value</i>. |
| 3713 |
The method value <code>x.M</code> is a function value that is callable |
| 3714 |
with the same arguments as a method call of <code>x.M</code>. |
| 3715 |
The expression <code>x</code> is evaluated and saved during the evaluation of the |
| 3716 |
method value; the saved copy is then used as the receiver in any calls, |
| 3717 |
which may be executed later. |
| 3718 |
</p> |
| 3719 |
|
| 3720 |
<pre> |
| 3721 |
type S struct { *T } |
| 3722 |
type T int |
| 3723 |
func (t T) M() { print(t) } |
| 3724 |
|
| 3725 |
t := new(T) |
| 3726 |
s := S{T: t} |
| 3727 |
f := t.M // receiver *t is evaluated and stored in f |
| 3728 |
g := s.M // receiver *(s.T) is evaluated and stored in g |
| 3729 |
*t = 42 // does not affect stored receivers in f and g |
| 3730 |
</pre> |
| 3731 |
|
| 3732 |
<p> |
| 3733 |
The type <code>T</code> may be an interface or non-interface type. |
| 3734 |
</p> |
| 3735 |
|
| 3736 |
<p> |
| 3737 |
As in the discussion of <a href="#Method_expressions">method expressions</a> above, |
| 3738 |
consider a struct type <code>T</code> with two methods, |
| 3739 |
<code>Mv</code>, whose receiver is of type <code>T</code>, and |
| 3740 |
<code>Mp</code>, whose receiver is of type <code>*T</code>. |
| 3741 |
</p> |
| 3742 |
|
| 3743 |
<pre> |
| 3744 |
type T struct { |
| 3745 |
a int |
| 3746 |
} |
| 3747 |
func (tv T) Mv(a int) int { return 0 } // value receiver |
| 3748 |
func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver |
| 3749 |
|
| 3750 |
var t T |
| 3751 |
var pt *T |
| 3752 |
func makeT() T |
| 3753 |
</pre> |
| 3754 |
|
| 3755 |
<p> |
| 3756 |
The expression |
| 3757 |
</p> |
| 3758 |
|
| 3759 |
<pre> |
| 3760 |
t.Mv |
| 3761 |
</pre> |
| 3762 |
|
| 3763 |
<p> |
| 3764 |
yields a function value of type |
| 3765 |
</p> |
| 3766 |
|
| 3767 |
<pre> |
| 3768 |
func(int) int |
| 3769 |
</pre> |
| 3770 |
|
| 3771 |
<p> |
| 3772 |
These two invocations are equivalent: |
| 3773 |
</p> |
| 3774 |
|
| 3775 |
<pre> |
| 3776 |
t.Mv(7) |
| 3777 |
f := t.Mv; f(7) |
| 3778 |
</pre> |
| 3779 |
|
| 3780 |
<p> |
| 3781 |
Similarly, the expression |
| 3782 |
</p> |
| 3783 |
|
| 3784 |
<pre> |
| 3785 |
pt.Mp |
| 3786 |
</pre> |
| 3787 |
|
| 3788 |
<p> |
| 3789 |
yields a function value of type |
| 3790 |
</p> |
| 3791 |
|
| 3792 |
<pre> |
| 3793 |
func(float32) float32 |
| 3794 |
</pre> |
| 3795 |
|
| 3796 |
<p> |
| 3797 |
As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver |
| 3798 |
using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>. |
| 3799 |
</p> |
| 3800 |
|
| 3801 |
<p> |
| 3802 |
As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver |
| 3803 |
using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&t).Mp</code>. |
| 3804 |
</p> |
| 3805 |
|
| 3806 |
<pre> |
| 3807 |
f := t.Mv; f(7) // like t.Mv(7) |
| 3808 |
f := pt.Mp; f(7) // like pt.Mp(7) |
| 3809 |
f := pt.Mv; f(7) // like (*pt).Mv(7) |
| 3810 |
f := t.Mp; f(7) // like (&t).Mp(7) |
| 3811 |
f := makeT().Mp // invalid: result of makeT() is not addressable |
| 3812 |
</pre> |
| 3813 |
|
| 3814 |
<p> |
| 3815 |
Although the examples above use non-interface types, it is also legal to create a method value |
| 3816 |
from a value of interface type. |
| 3817 |
</p> |
| 3818 |
|
| 3819 |
<pre> |
| 3820 |
var i interface { M(int) } = myVal |
| 3821 |
f := i.M; f(7) // like i.M(7) |
| 3822 |
</pre> |
| 3823 |
|
| 3824 |
|
| 3825 |
<h3 id="Index_expressions">Index expressions</h3> |
| 3826 |
|
| 3827 |
<p> |
| 3828 |
A primary expression of the form |
| 3829 |
</p> |
| 3830 |
|
| 3831 |
<pre> |
| 3832 |
a[x] |
| 3833 |
</pre> |
| 3834 |
|
| 3835 |
<p> |
| 3836 |
denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>. |
| 3837 |
The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively. |
| 3838 |
The following rules apply: |
| 3839 |
</p> |
| 3840 |
|
| 3841 |
<p> |
| 3842 |
If <code>a</code> is neither a map nor a <a href="#Type_parameter_declarations">type parameter</a>: |
| 3843 |
</p> |
| 3844 |
<ul> |
| 3845 |
<li>the index <code>x</code> must be an untyped constant, or its type must be |
| 3846 |
an <a href="#Numeric_types">integer</a> or a type parameter whose type set |
| 3847 |
contains only integer types</li> |
| 3848 |
<li>a constant index must be non-negative and |
| 3849 |
<a href="#Representability">representable</a> by a value of type <code>int</code></li> |
| 3850 |
<li>a constant index that is untyped is given type <code>int</code></li> |
| 3851 |
<li>the index <code>x</code> is <i>in range</i> if <code>0 <= x < len(a)</code>, |
| 3852 |
otherwise it is <i>out of range</i></li> |
| 3853 |
</ul> |
| 3854 |
|
| 3855 |
<p> |
| 3856 |
For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>: |
| 3857 |
</p> |
| 3858 |
<ul> |
| 3859 |
<li>a <a href="#Constants">constant</a> index must be in range</li> |
| 3860 |
<li>if <code>x</code> is out of range at run time, |
| 3861 |
a <a href="#Run_time_panics">run-time panic</a> occurs</li> |
| 3862 |
<li><code>a[x]</code> is the array element at index <code>x</code> and the type of |
| 3863 |
<code>a[x]</code> is the element type of <code>A</code></li> |
| 3864 |
</ul> |
| 3865 |
|
| 3866 |
<p> |
| 3867 |
For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type: |
| 3868 |
</p> |
| 3869 |
<ul> |
| 3870 |
<li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li> |
| 3871 |
</ul> |
| 3872 |
|
| 3873 |
<p> |
| 3874 |
For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>: |
| 3875 |
</p> |
| 3876 |
<ul> |
| 3877 |
<li>if <code>x</code> is out of range at run time, |
| 3878 |
a <a href="#Run_time_panics">run-time panic</a> occurs</li> |
| 3879 |
<li><code>a[x]</code> is the slice element at index <code>x</code> and the type of |
| 3880 |
<code>a[x]</code> is the element type of <code>S</code></li> |
| 3881 |
</ul> |
| 3882 |
|
| 3883 |
<p> |
| 3884 |
For <code>a</code> of <a href="#String_types">string type</a>: |
| 3885 |
</p> |
| 3886 |
<ul> |
| 3887 |
<li>a <a href="#Constants">constant</a> index must be in range |
| 3888 |
if the string <code>a</code> is also constant</li> |
| 3889 |
<li>if <code>x</code> is out of range at run time, |
| 3890 |
a <a href="#Run_time_panics">run-time panic</a> occurs</li> |
| 3891 |
<li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of |
| 3892 |
<code>a[x]</code> is <code>byte</code></li> |
| 3893 |
<li><code>a[x]</code> may not be assigned to</li> |
| 3894 |
</ul> |
| 3895 |
|
| 3896 |
<p> |
| 3897 |
For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>: |
| 3898 |
</p> |
| 3899 |
<ul> |
| 3900 |
<li><code>x</code>'s type must be |
| 3901 |
<a href="#Assignability">assignable</a> |
| 3902 |
to the key type of <code>M</code></li> |
| 3903 |
<li>if the map contains an entry with key <code>x</code>, |
| 3904 |
<code>a[x]</code> is the map element with key <code>x</code> |
| 3905 |
and the type of <code>a[x]</code> is the element type of <code>M</code></li> |
| 3906 |
<li>if the map is <code>nil</code> or does not contain such an entry, |
| 3907 |
<code>a[x]</code> is the <a href="#The_zero_value">zero value</a> |
| 3908 |
for the element type of <code>M</code></li> |
| 3909 |
</ul> |
| 3910 |
|
| 3911 |
<p> |
| 3912 |
For <code>a</code> of <a href="#Type_parameter_declarations">type parameter type</a> <code>P</code>: |
| 3913 |
</p> |
| 3914 |
<ul> |
| 3915 |
<li>The index expression <code>a[x]</code> must be valid for values |
| 3916 |
of all types in <code>P</code>'s type set.</li> |
| 3917 |
<li>The element types of all types in <code>P</code>'s type set must be identical. |
| 3918 |
In this context, the element type of a string type is <code>byte</code>.</li> |
| 3919 |
<li>If there is a map type in the type set of <code>P</code>, |
| 3920 |
all types in that type set must be map types, and the respective key types |
| 3921 |
must be all identical.</li> |
| 3922 |
<li><code>a[x]</code> is the array, slice, or string element at index <code>x</code>, |
| 3923 |
or the map element with key <code>x</code> of the type argument |
| 3924 |
that <code>P</code> is instantiated with, and the type of <code>a[x]</code> is |
| 3925 |
the type of the (identical) element types.</li> |
| 3926 |
<li><code>a[x]</code> may not be assigned to if <code>P</code>'s type set |
| 3927 |
includes string types.</li> |
| 3928 |
</ul> |
| 3929 |
|
| 3930 |
<p> |
| 3931 |
Otherwise <code>a[x]</code> is illegal. |
| 3932 |
</p> |
| 3933 |
|
| 3934 |
<p> |
| 3935 |
An index expression on a map <code>a</code> of type <code>map[K]V</code> |
| 3936 |
used in an <a href="#Assignment_statements">assignment statement</a> or initialization of the special form |
| 3937 |
</p> |
| 3938 |
|
| 3939 |
<pre> |
| 3940 |
v, ok = a[x] |
| 3941 |
v, ok := a[x] |
| 3942 |
var v, ok = a[x] |
| 3943 |
</pre> |
| 3944 |
|
| 3945 |
<p> |
| 3946 |
yields an additional untyped boolean value. The value of <code>ok</code> is |
| 3947 |
<code>true</code> if the key <code>x</code> is present in the map, and |
| 3948 |
<code>false</code> otherwise. |
| 3949 |
</p> |
| 3950 |
|
| 3951 |
<p> |
| 3952 |
Assigning to an element of a <code>nil</code> map causes a |
| 3953 |
<a href="#Run_time_panics">run-time panic</a>. |
| 3954 |
</p> |
| 3955 |
|
| 3956 |
|
| 3957 |
<h3 id="Slice_expressions">Slice expressions</h3> |
| 3958 |
|
| 3959 |
<p> |
| 3960 |
Slice expressions construct a substring or slice from a string, array, pointer |
| 3961 |
to array, or slice operand. |
| 3962 |
There are two variants: a simple form that specifies a low |
| 3963 |
and high bound, and a full form that also specifies a bound on the capacity. |
| 3964 |
</p> |
| 3965 |
|
| 3966 |
<p> |
| 3967 |
If the operand type is a <a href="#Type_parameter_declarations">type parameter</a>, |
| 3968 |
unless its type set contains string types, |
| 3969 |
all types in the type set must have the same underlying type, and the slice expression |
| 3970 |
must be valid for an operand of that type. |
| 3971 |
If the type set contains string types it may also contain byte slices with underlying |
| 3972 |
type <code>[]byte</code>. |
| 3973 |
In this case, the slice expression must be valid for an operand of <code>string</code> |
| 3974 |
type. |
| 3975 |
</p> |
| 3976 |
|
| 3977 |
<h4>Simple slice expressions</h4> |
| 3978 |
|
| 3979 |
<p> |
| 3980 |
For a string, array, pointer to array, or slice <code>a</code>, the primary expression |
| 3981 |
</p> |
| 3982 |
|
| 3983 |
<pre> |
| 3984 |
a[low : high] |
| 3985 |
</pre> |
| 3986 |
|
| 3987 |
<p> |
| 3988 |
constructs a substring or slice. |
| 3989 |
The <i>indices</i> <code>low</code> and |
| 3990 |
<code>high</code> select which elements of operand <code>a</code> appear |
| 3991 |
in the result. The result has indices starting at 0 and length equal to |
| 3992 |
<code>high</code> - <code>low</code>. |
| 3993 |
After slicing the array <code>a</code> |
| 3994 |
</p> |
| 3995 |
|
| 3996 |
<pre> |
| 3997 |
a := [5]int{1, 2, 3, 4, 5} |
| 3998 |
s := a[1:4] |
| 3999 |
</pre> |
| 4000 |
|
| 4001 |
<p> |
| 4002 |
the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements |
| 4003 |
</p> |
| 4004 |
|
| 4005 |
<pre> |
| 4006 |
s[0] == 2 |
| 4007 |
s[1] == 3 |
| 4008 |
s[2] == 4 |
| 4009 |
</pre> |
| 4010 |
|
| 4011 |
<p> |
| 4012 |
For convenience, any of the indices may be omitted. A missing <code>low</code> |
| 4013 |
index defaults to zero; a missing <code>high</code> index defaults to the length of the |
| 4014 |
sliced operand: |
| 4015 |
</p> |
| 4016 |
|
| 4017 |
<pre> |
| 4018 |
a[2:] // same as a[2 : len(a)] |
| 4019 |
a[:3] // same as a[0 : 3] |
| 4020 |
a[:] // same as a[0 : len(a)] |
| 4021 |
</pre> |
| 4022 |
|
| 4023 |
<p> |
| 4024 |
If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for |
| 4025 |
<code>(*a)[low : high]</code>. |
| 4026 |
</p> |
| 4027 |
|
| 4028 |
<p> |
| 4029 |
For arrays or strings, the indices are <i>in range</i> if |
| 4030 |
<code>0</code> <= <code>low</code> <= <code>high</code> <= <code>len(a)</code>, |
| 4031 |
otherwise they are <i>out of range</i>. |
| 4032 |
For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length. |
| 4033 |
A <a href="#Constants">constant</a> index must be non-negative and |
| 4034 |
<a href="#Representability">representable</a> by a value of type |
| 4035 |
<code>int</code>; for arrays or constant strings, constant indices must also be in range. |
| 4036 |
If both indices are constant, they must satisfy <code>low <= high</code>. |
| 4037 |
If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. |
| 4038 |
</p> |
| 4039 |
|
| 4040 |
<p> |
| 4041 |
Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice, |
| 4042 |
the result of the slice operation is a non-constant value of the same type as the operand. |
| 4043 |
For untyped string operands the result is a non-constant value of type <code>string</code>. |
| 4044 |
If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a> |
| 4045 |
and the result of the slice operation is a slice with the same element type as the array. |
| 4046 |
</p> |
| 4047 |
|
| 4048 |
<p> |
| 4049 |
If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result |
| 4050 |
is a <code>nil</code> slice. Otherwise, if the result is a slice, it shares its underlying |
| 4051 |
array with the operand. |
| 4052 |
</p> |
| 4053 |
|
| 4054 |
<pre> |
| 4055 |
var a [10]int |
| 4056 |
s1 := a[3:7] // underlying array of s1 is array a; &s1[2] == &a[5] |
| 4057 |
s2 := s1[1:4] // underlying array of s2 is underlying array of s1 which is array a; &s2[1] == &a[5] |
| 4058 |
s2[1] = 42 // s2[1] == s1[2] == a[5] == 42; they all refer to the same underlying array element |
| 4059 |
|
| 4060 |
var s []int |
| 4061 |
s3 := s[:0] // s3 == nil |
| 4062 |
</pre> |
| 4063 |
|
| 4064 |
|
| 4065 |
<h4>Full slice expressions</h4> |
| 4066 |
|
| 4067 |
<p> |
| 4068 |
For an array, pointer to array, or slice <code>a</code> (but not a string), the primary expression |
| 4069 |
</p> |
| 4070 |
|
| 4071 |
<pre> |
| 4072 |
a[low : high : max] |
| 4073 |
</pre> |
| 4074 |
|
| 4075 |
<p> |
| 4076 |
constructs a slice of the same type, and with the same length and elements as the simple slice |
| 4077 |
expression <code>a[low : high]</code>. Additionally, it controls the resulting slice's capacity |
| 4078 |
by setting it to <code>max - low</code>. Only the first index may be omitted; it defaults to 0. |
| 4079 |
After slicing the array <code>a</code> |
| 4080 |
</p> |
| 4081 |
|
| 4082 |
<pre> |
| 4083 |
a := [5]int{1, 2, 3, 4, 5} |
| 4084 |
t := a[1:3:5] |
| 4085 |
</pre> |
| 4086 |
|
| 4087 |
<p> |
| 4088 |
the slice <code>t</code> has type <code>[]int</code>, length 2, capacity 4, and elements |
| 4089 |
</p> |
| 4090 |
|
| 4091 |
<pre> |
| 4092 |
t[0] == 2 |
| 4093 |
t[1] == 3 |
| 4094 |
</pre> |
| 4095 |
|
| 4096 |
<p> |
| 4097 |
As for simple slice expressions, if <code>a</code> is a pointer to an array, |
| 4098 |
<code>a[low : high : max]</code> is shorthand for <code>(*a)[low : high : max]</code>. |
| 4099 |
If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>. |
| 4100 |
</p> |
| 4101 |
|
| 4102 |
<p> |
| 4103 |
The indices are <i>in range</i> if <code>0 <= low <= high <= max <= cap(a)</code>, |
| 4104 |
otherwise they are <i>out of range</i>. |
| 4105 |
A <a href="#Constants">constant</a> index must be non-negative and |
| 4106 |
<a href="#Representability">representable</a> by a value of type |
| 4107 |
<code>int</code>; for arrays, constant indices must also be in range. |
| 4108 |
If multiple indices are constant, the constants that are present must be in range relative to each |
| 4109 |
other. |
| 4110 |
If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. |
| 4111 |
</p> |
| 4112 |
|
| 4113 |
<h3 id="Type_assertions">Type assertions</h3> |
| 4114 |
|
| 4115 |
<p> |
| 4116 |
For an expression <code>x</code> of <a href="#Interface_types">interface type</a>, |
| 4117 |
but not a <a href="#Type_parameter_declarations">type parameter</a>, and a type <code>T</code>, |
| 4118 |
the primary expression |
| 4119 |
</p> |
| 4120 |
|
| 4121 |
<pre> |
| 4122 |
x.(T) |
| 4123 |
</pre> |
| 4124 |
|
| 4125 |
<p> |
| 4126 |
asserts that <code>x</code> is not <code>nil</code> |
| 4127 |
and that the value stored in <code>x</code> is of type <code>T</code>. |
| 4128 |
The notation <code>x.(T)</code> is called a <i>type assertion</i>. |
| 4129 |
</p> |
| 4130 |
<p> |
| 4131 |
More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts |
| 4132 |
that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a> |
| 4133 |
to the type <code>T</code>. |
| 4134 |
In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>; |
| 4135 |
otherwise the type assertion is invalid since it is not possible for <code>x</code> |
| 4136 |
to store a value of type <code>T</code>. |
| 4137 |
If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type |
| 4138 |
of <code>x</code> <a href="#Implementing_an_interface">implements</a> the interface <code>T</code>. |
| 4139 |
</p> |
| 4140 |
<p> |
| 4141 |
If the type assertion holds, the value of the expression is the value |
| 4142 |
stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false, |
| 4143 |
a <a href="#Run_time_panics">run-time panic</a> occurs. |
| 4144 |
In other words, even though the dynamic type of <code>x</code> |
| 4145 |
is known only at run time, the type of <code>x.(T)</code> is |
| 4146 |
known to be <code>T</code> in a correct program. |
| 4147 |
</p> |
| 4148 |
|
| 4149 |
<pre> |
| 4150 |
var x interface{} = 7 // x has dynamic type int and value 7 |
| 4151 |
i := x.(int) // i has type int and value 7 |
| 4152 |
|
| 4153 |
type I interface { m() } |
| 4154 |
|
| 4155 |
func f(y I) { |
| 4156 |
s := y.(string) // illegal: string does not implement I (missing method m) |
| 4157 |
r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader |
| 4158 |
… |
| 4159 |
} |
| 4160 |
</pre> |
| 4161 |
|
| 4162 |
<p> |
| 4163 |
A type assertion used in an <a href="#Assignment_statements">assignment statement</a> or initialization of the special form |
| 4164 |
</p> |
| 4165 |
|
| 4166 |
<pre> |
| 4167 |
v, ok = x.(T) |
| 4168 |
v, ok := x.(T) |
| 4169 |
var v, ok = x.(T) |
| 4170 |
var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool |
| 4171 |
</pre> |
| 4172 |
|
| 4173 |
<p> |
| 4174 |
yields an additional untyped boolean value. The value of <code>ok</code> is <code>true</code> |
| 4175 |
if the assertion holds. Otherwise it is <code>false</code> and the value of <code>v</code> is |
| 4176 |
the <a href="#The_zero_value">zero value</a> for type <code>T</code>. |
| 4177 |
No <a href="#Run_time_panics">run-time panic</a> occurs in this case. |
| 4178 |
</p> |
| 4179 |
|
| 4180 |
|
| 4181 |
<h3 id="Calls">Calls</h3> |
| 4182 |
|
| 4183 |
<p> |
| 4184 |
Given an expression <code>f</code> of <a href="#Function_types">function type</a> |
| 4185 |
<code>F</code>, |
| 4186 |
</p> |
| 4187 |
|
| 4188 |
<pre> |
| 4189 |
f(a1, a2, … an) |
| 4190 |
</pre> |
| 4191 |
|
| 4192 |
<p> |
| 4193 |
calls <code>f</code> with arguments <code>a1, a2, … an</code>. |
| 4194 |
Except for one special case, arguments must be single-valued expressions |
| 4195 |
<a href="#Assignability">assignable</a> to the parameter types of |
| 4196 |
<code>F</code> and are evaluated before the function is called. |
| 4197 |
The type of the expression is the result type of <code>F</code>. |
| 4198 |
A method invocation is similar but the method itself |
| 4199 |
is specified as a selector upon a value of the receiver type for |
| 4200 |
the method. |
| 4201 |
</p> |
| 4202 |
|
| 4203 |
<pre> |
| 4204 |
math.Atan2(x, y) // function call |
| 4205 |
var pt *Point |
| 4206 |
pt.Scale(3.5) // method call with receiver pt |
| 4207 |
</pre> |
| 4208 |
|
| 4209 |
<p> |
| 4210 |
If <code>f</code> denotes a generic function, it must be |
| 4211 |
<a href="#Instantiations">instantiated</a> before it can be called |
| 4212 |
or used as a function value. |
| 4213 |
</p> |
| 4214 |
|
| 4215 |
<p> |
| 4216 |
If the type of <code>f</code> is a <a href="#Type_parameter_declarations">type parameter</a>, |
| 4217 |
all types in its type set must have the same underlying type, which must be a function type, |
| 4218 |
and the function call must be valid for that type. |
| 4219 |
</p> |
| 4220 |
|
| 4221 |
<p> |
| 4222 |
In a function call, the function value and arguments are evaluated in |
| 4223 |
<a href="#Order_of_evaluation">the usual order</a>. |
| 4224 |
After they are evaluated, new storage is allocated for the function's |
| 4225 |
<a href="#Variables">variables</a>, which includes its parameters |
| 4226 |
and results. |
| 4227 |
Then, the arguments of the call are <i>passed</i> to the function, |
| 4228 |
which means that they are <a href="#Assignment_statements">assigned</a> |
| 4229 |
to their corresponding function parameters, |
| 4230 |
and the called function begins execution. |
| 4231 |
The return parameters of the function are passed |
| 4232 |
back to the caller when the function returns. |
| 4233 |
</p> |
| 4234 |
|
| 4235 |
<p> |
| 4236 |
Calling a <code>nil</code> function value |
| 4237 |
causes a <a href="#Run_time_panics">run-time panic</a>. |
| 4238 |
</p> |
| 4239 |
|
| 4240 |
<p> |
| 4241 |
As a special case, if the return values of a function or method |
| 4242 |
<code>g</code> are equal in number and individually |
| 4243 |
assignable to the parameters of another function or method |
| 4244 |
<code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code> |
| 4245 |
will invoke <code>f</code> after passing the return values of |
| 4246 |
<code>g</code> to the parameters of <code>f</code> in order. |
| 4247 |
The call of <code>f</code> must contain no parameters other than the call of <code>g</code>, |
| 4248 |
and <code>g</code> must have at least one return value. |
| 4249 |
If <code>f</code> has a final <code>...</code> parameter, it is |
| 4250 |
assigned the return values of <code>g</code> that remain after |
| 4251 |
assignment of regular parameters. |
| 4252 |
</p> |
| 4253 |
|
| 4254 |
<pre> |
| 4255 |
func Split(s string, pos int) (string, string) { |
| 4256 |
return s[0:pos], s[pos:] |
| 4257 |
} |
| 4258 |
|
| 4259 |
func Join(s, t string) string { |
| 4260 |
return s + t |
| 4261 |
} |
| 4262 |
|
| 4263 |
if Join(Split(value, len(value)/2)) != value { |
| 4264 |
log.Panic("test fails") |
| 4265 |
} |
| 4266 |
</pre> |
| 4267 |
|
| 4268 |
<p> |
| 4269 |
A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a> |
| 4270 |
of (the type of) <code>x</code> contains <code>m</code> and the |
| 4271 |
argument list can be assigned to the parameter list of <code>m</code>. |
| 4272 |
If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&x</code>'s method |
| 4273 |
set contains <code>m</code>, <code>x.m()</code> is shorthand |
| 4274 |
for <code>(&x).m()</code>: |
| 4275 |
</p> |
| 4276 |
|
| 4277 |
<pre> |
| 4278 |
var p Point |
| 4279 |
p.Scale(3.5) |
| 4280 |
</pre> |
| 4281 |
|
| 4282 |
<p> |
| 4283 |
There is no distinct method type and there are no method literals. |
| 4284 |
</p> |
| 4285 |
|
| 4286 |
<h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3> |
| 4287 |
|
| 4288 |
<p> |
| 4289 |
If <code>f</code> is <a href="#Function_types">variadic</a> with a final |
| 4290 |
parameter <code>p</code> of type <code>...T</code>, then within <code>f</code> |
| 4291 |
the type of <code>p</code> is equivalent to type <code>[]T</code>. |
| 4292 |
If <code>f</code> is invoked with no actual arguments for <code>p</code>, |
| 4293 |
the value <a href="#Calls">passed</a> to <code>p</code> is <code>nil</code>. |
| 4294 |
Otherwise, the value passed is a new slice |
| 4295 |
of type <code>[]T</code> with a new underlying array whose successive elements |
| 4296 |
are the actual arguments, which all must be <a href="#Assignability">assignable</a> |
| 4297 |
to <code>T</code>. The length and capacity of the slice is therefore |
| 4298 |
the number of arguments bound to <code>p</code> and may differ for each |
| 4299 |
call site. |
| 4300 |
</p> |
| 4301 |
|
| 4302 |
<p> |
| 4303 |
Given the function and calls |
| 4304 |
</p> |
| 4305 |
<pre> |
| 4306 |
func Greeting(prefix string, who ...string) |
| 4307 |
Greeting("nobody") |
| 4308 |
Greeting("hello:", "Joe", "Anna", "Eileen") |
| 4309 |
</pre> |
| 4310 |
|
| 4311 |
<p> |
| 4312 |
within <code>Greeting</code>, <code>who</code> will have the value |
| 4313 |
<code>nil</code> in the first call, and |
| 4314 |
<code>[]string{"Joe", "Anna", "Eileen"}</code> in the second. |
| 4315 |
</p> |
| 4316 |
|
| 4317 |
<p> |
| 4318 |
If the final argument is assignable to a slice type <code>[]T</code> and |
| 4319 |
is followed by <code>...</code>, it is passed unchanged as the value |
| 4320 |
for a <code>...T</code> parameter. In this case no new slice is created. |
| 4321 |
</p> |
| 4322 |
|
| 4323 |
<p> |
| 4324 |
Given the slice <code>s</code> and call |
| 4325 |
</p> |
| 4326 |
|
| 4327 |
<pre> |
| 4328 |
s := []string{"James", "Jasmine"} |
| 4329 |
Greeting("goodbye:", s...) |
| 4330 |
</pre> |
| 4331 |
|
| 4332 |
<p> |
| 4333 |
within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code> |
| 4334 |
with the same underlying array. |
| 4335 |
</p> |
| 4336 |
|
| 4337 |
<h3 id="Instantiations">Instantiations</h3> |
| 4338 |
|
| 4339 |
<p> |
| 4340 |
A generic function or type is <i>instantiated</i> by substituting <i>type arguments</i> |
| 4341 |
for the type parameters [<a href="#Go_1.18">Go 1.18</a>]. |
| 4342 |
Instantiation proceeds in two steps: |
| 4343 |
</p> |
| 4344 |
|
| 4345 |
<ol> |
| 4346 |
<li> |
| 4347 |
Each type argument is substituted for its corresponding type parameter in the generic |
| 4348 |
declaration. |
| 4349 |
This substitution happens across the entire function or type declaration, |
| 4350 |
including the type parameter list itself and any types in that list. |
| 4351 |
</li> |
| 4352 |
|
| 4353 |
<li> |
| 4354 |
After substitution, each type argument must <a href="#Satisfying_a_type_constraint">satisfy</a> |
| 4355 |
the <a href="#Type_parameter_declarations">constraint</a> (instantiated, if necessary) |
| 4356 |
of the corresponding type parameter. Otherwise instantiation fails. |
| 4357 |
</li> |
| 4358 |
</ol> |
| 4359 |
|
| 4360 |
<p> |
| 4361 |
Instantiating a type results in a new non-generic <a href="#Types">named type</a>; |
| 4362 |
instantiating a function produces a new non-generic function. |
| 4363 |
</p> |
| 4364 |
|
| 4365 |
<pre> |
| 4366 |
type parameter list type arguments after substitution |
| 4367 |
|
| 4368 |
[P any] int int satisfies any |
| 4369 |
[S ~[]E, E any] []int, int []int satisfies ~[]int, int satisfies any |
| 4370 |
[P io.Writer] string illegal: string doesn't satisfy io.Writer |
| 4371 |
[P comparable] any any satisfies (but does not implement) comparable |
| 4372 |
</pre> |
| 4373 |
|
| 4374 |
<p> |
| 4375 |
When using a generic function, type arguments may be provided explicitly, |
| 4376 |
or they may be partially or completely <a href="#Type_inference">inferred</a> |
| 4377 |
from the context in which the function is used. |
| 4378 |
Provided that they can be inferred, type argument lists may be omitted entirely if the function is: |
| 4379 |
</p> |
| 4380 |
|
| 4381 |
<ul> |
| 4382 |
<li> |
| 4383 |
<a href="#Calls">called</a> with ordinary arguments, |
| 4384 |
</li> |
| 4385 |
<li> |
| 4386 |
<a href="#Assignment_statements">assigned</a> to a variable with a known type |
| 4387 |
</li> |
| 4388 |
<li> |
| 4389 |
<a href="#Calls">passed as an argument</a> to another function, or |
| 4390 |
</li> |
| 4391 |
<li> |
| 4392 |
<a href="#Return_statements">returned as a result</a>. |
| 4393 |
</li> |
| 4394 |
</ul> |
| 4395 |
|
| 4396 |
<p> |
| 4397 |
In all other cases, a (possibly partial) type argument list must be present. |
| 4398 |
If a type argument list is absent or partial, all missing type arguments |
| 4399 |
must be inferrable from the context in which the function is used. |
| 4400 |
</p> |
| 4401 |
|
| 4402 |
<pre> |
| 4403 |
// sum returns the sum (concatenation, for strings) of its arguments. |
| 4404 |
func sum[T ~int | ~float64 | ~string](x... T) T { … } |
| 4405 |
|
| 4406 |
x := sum // illegal: the type of x is unknown |
| 4407 |
intSum := sum[int] // intSum has type func(x... int) int |
| 4408 |
a := intSum(2, 3) // a has value 5 of type int |
| 4409 |
b := sum[float64](2.0, 3) // b has value 5.0 of type float64 |
| 4410 |
c := sum(b, -1) // c has value 4.0 of type float64 |
| 4411 |
|
| 4412 |
type sumFunc func(x... string) string |
| 4413 |
var f sumFunc = sum // same as var f sumFunc = sum[string] |
| 4414 |
f = sum // same as f = sum[string] |
| 4415 |
</pre> |
| 4416 |
|
| 4417 |
<p> |
| 4418 |
A partial type argument list cannot be empty; at least the first argument must be present. |
| 4419 |
The list is a prefix of the full list of type arguments, leaving the remaining arguments |
| 4420 |
to be inferred. Loosely speaking, type arguments may be omitted from "right to left". |
| 4421 |
</p> |
| 4422 |
|
| 4423 |
<pre> |
| 4424 |
func apply[S ~[]E, E any](s S, f func(E) E) S { … } |
| 4425 |
|
| 4426 |
f0 := apply[] // illegal: type argument list cannot be empty |
| 4427 |
f1 := apply[[]int] // type argument for S explicitly provided, type argument for E inferred |
| 4428 |
f2 := apply[[]string, string] // both type arguments explicitly provided |
| 4429 |
|
| 4430 |
var bytes []byte |
| 4431 |
r := apply(bytes, func(byte) byte { … }) // both type arguments inferred from the function arguments |
| 4432 |
</pre> |
| 4433 |
|
| 4434 |
<p> |
| 4435 |
For a generic type, all type arguments must always be provided explicitly. |
| 4436 |
</p> |
| 4437 |
|
| 4438 |
<h3 id="Type_inference">Type inference</h3> |
| 4439 |
|
| 4440 |
<p> |
| 4441 |
A use of a generic function may omit some or all type arguments if they can be |
| 4442 |
<i>inferred</i> from the context within which the function is used, including |
| 4443 |
the constraints of the function's type parameters. |
| 4444 |
Type inference succeeds if it can infer the missing type arguments |
| 4445 |
and <a href="#Instantiations">instantiation</a> succeeds with the |
| 4446 |
inferred type arguments. |
| 4447 |
Otherwise, type inference fails and the program is invalid. |
| 4448 |
</p> |
| 4449 |
|
| 4450 |
<p> |
| 4451 |
Type inference uses the type relationships between pairs of types for inference: |
| 4452 |
For instance, a function argument must be <a href="#Assignability">assignable</a> |
| 4453 |
to its respective function parameter; this establishes a relationship between the |
| 4454 |
type of the argument and the type of the parameter. |
| 4455 |
If either of these two types contains type parameters, type inference looks for the |
| 4456 |
type arguments to substitute the type parameters with such that the assignability |
| 4457 |
relationship is satisfied. |
| 4458 |
Similarly, type inference uses the fact that a type argument must |
| 4459 |
<a href="#Satisfying_a_type_constraint">satisfy</a> the constraint of its respective |
| 4460 |
type parameter. |
| 4461 |
</p> |
| 4462 |
|
| 4463 |
<p> |
| 4464 |
Each such pair of matched types corresponds to a <i>type equation</i> containing |
| 4465 |
one or multiple type parameters, from one or possibly multiple generic functions. |
| 4466 |
Inferring the missing type arguments means solving the resulting set of type |
| 4467 |
equations for the respective type parameters. |
| 4468 |
</p> |
| 4469 |
|
| 4470 |
<p> |
| 4471 |
For example, given |
| 4472 |
</p> |
| 4473 |
|
| 4474 |
<pre> |
| 4475 |
// dedup returns a copy of the argument slice with any duplicate entries removed. |
| 4476 |
func dedup[S ~[]E, E comparable](S) S { … } |
| 4477 |
|
| 4478 |
type Slice []int |
| 4479 |
var s Slice |
| 4480 |
s = dedup(s) // same as s = dedup[Slice, int](s) |
| 4481 |
</pre> |
| 4482 |
|
| 4483 |
<p> |
| 4484 |
the variable <code>s</code> of type <code>Slice</code> must be assignable to |
| 4485 |
the function parameter type <code>S</code> for the program to be valid. |
| 4486 |
To reduce complexity, type inference ignores the directionality of assignments, |
| 4487 |
so the type relationship between <code>Slice</code> and <code>S</code> can be |
| 4488 |
expressed via the (symmetric) type equation <code>Slice ≡<sub>A</sub> S</code> |
| 4489 |
(or <code>S ≡<sub>A</sub> Slice</code> for that matter), |
| 4490 |
where the <code><sub>A</sub></code> in <code>≡<sub>A</sub></code> |
| 4491 |
indicates that the LHS and RHS types must match per assignability rules |
| 4492 |
(see the section on <a href="#Type_unification">type unification</a> for |
| 4493 |
details). |
| 4494 |
Similarly, the type parameter <code>S</code> must satisfy its constraint |
| 4495 |
<code>~[]E</code>. This can be expressed as <code>S ≡<sub>C</sub> ~[]E</code> |
| 4496 |
where <code>X ≡<sub>C</sub> Y</code> stands for |
| 4497 |
"<code>X</code> satisfies constraint <code>Y</code>". |
| 4498 |
These observations lead to a set of two equations |
| 4499 |
</p> |
| 4500 |
|
| 4501 |
<pre> |
| 4502 |
Slice ≡<sub>A</sub> S (1) |
| 4503 |
S ≡<sub>C</sub> ~[]E (2) |
| 4504 |
</pre> |
| 4505 |
|
| 4506 |
<p> |
| 4507 |
which now can be solved for the type parameters <code>S</code> and <code>E</code>. |
| 4508 |
From (1) a compiler can infer that the type argument for <code>S</code> is <code>Slice</code>. |
| 4509 |
Similarly, because the underlying type of <code>Slice</code> is <code>[]int</code> |
| 4510 |
and <code>[]int</code> must match <code>[]E</code> of the constraint, |
| 4511 |
a compiler can infer that <code>E</code> must be <code>int</code>. |
| 4512 |
Thus, for these two equations, type inference infers |
| 4513 |
</p> |
| 4514 |
|
| 4515 |
<pre> |
| 4516 |
S ➞ Slice |
| 4517 |
E ➞ int |
| 4518 |
</pre> |
| 4519 |
|
| 4520 |
<p> |
| 4521 |
Given a set of type equations, the type parameters to solve for are |
| 4522 |
the type parameters of the functions that need to be instantiated |
| 4523 |
and for which no explicit type arguments is provided. |
| 4524 |
These type parameters are called <i>bound</i> type parameters. |
| 4525 |
For instance, in the <code>dedup</code> example above, the type parameters |
| 4526 |
<code>S</code> and <code>E</code> are bound to <code>dedup</code>. |
| 4527 |
An argument to a generic function call may be a generic function itself. |
| 4528 |
The type parameters of that function are included in the set of bound |
| 4529 |
type parameters. |
| 4530 |
The types of function arguments may contain type parameters from other |
| 4531 |
functions (such as a generic function enclosing a function call). |
| 4532 |
Those type parameters may also appear in type equations but they are |
| 4533 |
not bound in that context. |
| 4534 |
Type equations are always solved for the bound type parameters only. |
| 4535 |
</p> |
| 4536 |
|
| 4537 |
<p> |
| 4538 |
Type inference supports calls of generic functions and assignments |
| 4539 |
of generic functions to (explicitly function-typed) variables. |
| 4540 |
This includes passing generic functions as arguments to other |
| 4541 |
(possibly also generic) functions, and returning generic functions |
| 4542 |
as results. |
| 4543 |
Type inference operates on a set of equations specific to each of |
| 4544 |
these cases. |
| 4545 |
The equations are as follows (type argument lists are omitted for clarity): |
| 4546 |
</p> |
| 4547 |
|
| 4548 |
<ul> |
| 4549 |
<li> |
| 4550 |
<p> |
| 4551 |
For a function call <code>f(a<sub>0</sub>, a<sub>1</sub>, …)</code> where |
| 4552 |
<code>f</code> or a function argument <code>a<sub>i</sub></code> is |
| 4553 |
a generic function: |
| 4554 |
<br> |
| 4555 |
Each pair <code>(a<sub>i</sub>, p<sub>i</sub>)</code> of corresponding |
| 4556 |
function arguments and parameters where <code>a<sub>i</sub></code> is not an |
| 4557 |
<a href="#Constants">untyped constant</a> yields an equation |
| 4558 |
<code>typeof(p<sub>i</sub>) ≡<sub>A</sub> typeof(a<sub>i</sub>)</code>. |
| 4559 |
<br> |
| 4560 |
If <code>a<sub>i</sub></code> is an untyped constant <code>c<sub>j</sub></code>, |
| 4561 |
and <code>typeof(p<sub>i</sub>)</code> is a bound type parameter <code>P<sub>k</sub></code>, |
| 4562 |
the pair <code>(c<sub>j</sub>, P<sub>k</sub>)</code> is collected separately from |
| 4563 |
the type equations. |
| 4564 |
</p> |
| 4565 |
</li> |
| 4566 |
<li> |
| 4567 |
<p> |
| 4568 |
For an assignment <code>v = f</code> of a generic function <code>f</code> to a |
| 4569 |
(non-generic) variable <code>v</code> of function type: |
| 4570 |
<br> |
| 4571 |
<code>typeof(v) ≡<sub>A</sub> typeof(f)</code>. |
| 4572 |
</p> |
| 4573 |
</li> |
| 4574 |
<li> |
| 4575 |
<p> |
| 4576 |
For a return statement <code>return …, f, … </code> where <code>f</code> is a |
| 4577 |
generic function returned as a result to a (non-generic) result variable |
| 4578 |
<code>r</code> of function type: |
| 4579 |
<br> |
| 4580 |
<code>typeof(r) ≡<sub>A</sub> typeof(f)</code>. |
| 4581 |
</p> |
| 4582 |
</li> |
| 4583 |
</ul> |
| 4584 |
|
| 4585 |
<p> |
| 4586 |
Additionally, each type parameter <code>P<sub>k</sub></code> and corresponding type constraint |
| 4587 |
<code>C<sub>k</sub></code> yields the type equation |
| 4588 |
<code>P<sub>k</sub> ≡<sub>C</sub> C<sub>k</sub></code>. |
| 4589 |
</p> |
| 4590 |
|
| 4591 |
<p> |
| 4592 |
Type inference gives precedence to type information obtained from typed operands |
| 4593 |
before considering untyped constants. |
| 4594 |
Therefore, inference proceeds in two phases: |
| 4595 |
</p> |
| 4596 |
|
| 4597 |
<ol> |
| 4598 |
<li> |
| 4599 |
<p> |
| 4600 |
The type equations are solved for the bound |
| 4601 |
type parameters using <a href="#Type_unification">type unification</a>. |
| 4602 |
If unification fails, type inference fails. |
| 4603 |
</p> |
| 4604 |
</li> |
| 4605 |
<li> |
| 4606 |
<p> |
| 4607 |
For each bound type parameter <code>P<sub>k</sub></code> for which no type argument |
| 4608 |
has been inferred yet and for which one or more pairs |
| 4609 |
<code>(c<sub>j</sub>, P<sub>k</sub>)</code> with that same type parameter |
| 4610 |
were collected, determine the <a href="#Constant_expressions">constant kind</a> |
| 4611 |
of the constants <code>c<sub>j</sub></code> in all those pairs the same way as for |
| 4612 |
<a href="#Constant_expressions">constant expressions</a>. |
| 4613 |
The type argument for <code>P<sub>k</sub></code> is the |
| 4614 |
<a href="#Constants">default type</a> for the determined constant kind. |
| 4615 |
If a constant kind cannot be determined due to conflicting constant kinds, |
| 4616 |
type inference fails. |
| 4617 |
</p> |
| 4618 |
</li> |
| 4619 |
</ol> |
| 4620 |
|
| 4621 |
<p> |
| 4622 |
If not all type arguments have been found after these two phases, type inference fails. |
| 4623 |
</p> |
| 4624 |
|
| 4625 |
<p> |
| 4626 |
If the two phases are successful, type inference determined a type argument for each |
| 4627 |
bound type parameter: |
| 4628 |
</p> |
| 4629 |
|
| 4630 |
<pre> |
| 4631 |
P<sub>k</sub> ➞ A<sub>k</sub> |
| 4632 |
</pre> |
| 4633 |
|
| 4634 |
<p> |
| 4635 |
A type argument <code>A<sub>k</sub></code> may be a composite type, |
| 4636 |
containing other bound type parameters <code>P<sub>k</sub></code> as element types |
| 4637 |
(or even be just another bound type parameter). |
| 4638 |
In a process of repeated simplification, the bound type parameters in each type |
| 4639 |
argument are substituted with the respective type arguments for those type |
| 4640 |
parameters until each type argument is free of bound type parameters. |
| 4641 |
</p> |
| 4642 |
|
| 4643 |
<p> |
| 4644 |
If type arguments contain cyclic references to themselves |
| 4645 |
through bound type parameters, simplification and thus type |
| 4646 |
inference fails. |
| 4647 |
Otherwise, type inference succeeds. |
| 4648 |
</p> |
| 4649 |
|
| 4650 |
<h4 id="Type_unification">Type unification</h4> |
| 4651 |
|
| 4652 |
<p> |
| 4653 |
Type inference solves type equations through <i>type unification</i>. |
| 4654 |
Type unification recursively compares the LHS and RHS types of an |
| 4655 |
equation, where either or both types may be or contain bound type parameters, |
| 4656 |
and looks for type arguments for those type parameters such that the LHS |
| 4657 |
and RHS match (become identical or assignment-compatible, depending on |
| 4658 |
context). |
| 4659 |
To that effect, type inference maintains a map of bound type parameters |
| 4660 |
to inferred type arguments; this map is consulted and updated during type unification. |
| 4661 |
Initially, the bound type parameters are known but the map is empty. |
| 4662 |
During type unification, if a new type argument <code>A</code> is inferred, |
| 4663 |
the respective mapping <code>P ➞ A</code> from type parameter to argument |
| 4664 |
is added to the map. |
| 4665 |
Conversely, when comparing types, a known type argument |
| 4666 |
(a type argument for which a map entry already exists) |
| 4667 |
takes the place of its corresponding type parameter. |
| 4668 |
As type inference progresses, the map is populated more and more |
| 4669 |
until all equations have been considered, or until unification fails. |
| 4670 |
Type inference succeeds if no unification step fails and the map has |
| 4671 |
an entry for each type parameter. |
| 4672 |
</p> |
| 4673 |
|
| 4674 |
<p> |
| 4675 |
For example, given the type equation with the bound type parameter |
| 4676 |
<code>P</code> |
| 4677 |
</p> |
| 4678 |
|
| 4679 |
<pre> |
| 4680 |
[10]struct{ elem P, list []P } ≡<sub>A</sub> [10]struct{ elem string; list []string } |
| 4681 |
</pre> |
| 4682 |
|
| 4683 |
<p> |
| 4684 |
type inference starts with an empty map. |
| 4685 |
Unification first compares the top-level structure of the LHS and RHS |
| 4686 |
types. |
| 4687 |
Both are arrays of the same length; they unify if the element types unify. |
| 4688 |
Both element types are structs; they unify if they have |
| 4689 |
the same number of fields with the same names and if the |
| 4690 |
field types unify. |
| 4691 |
The type argument for <code>P</code> is not known yet (there is no map entry), |
| 4692 |
so unifying <code>P</code> with <code>string</code> adds |
| 4693 |
the mapping <code>P ➞ string</code> to the map. |
| 4694 |
Unifying the types of the <code>list</code> field requires |
| 4695 |
unifying <code>[]P</code> and <code>[]string</code> and |
| 4696 |
thus <code>P</code> and <code>string</code>. |
| 4697 |
Since the type argument for <code>P</code> is known at this point |
| 4698 |
(there is a map entry for <code>P</code>), its type argument |
| 4699 |
<code>string</code> takes the place of <code>P</code>. |
| 4700 |
And since <code>string</code> is identical to <code>string</code>, |
| 4701 |
this unification step succeeds as well. |
| 4702 |
Unification of the LHS and RHS of the equation is now finished. |
| 4703 |
Type inference succeeds because there is only one type equation, |
| 4704 |
no unification step failed, and the map is fully populated. |
| 4705 |
</p> |
| 4706 |
|
| 4707 |
<p> |
| 4708 |
Unification uses a combination of <i>exact</i> and <i>loose</i> |
| 4709 |
unification depending on whether two types have to be |
| 4710 |
<a href="#Type_identity">identical</a>, |
| 4711 |
<a href="#Assignability">assignment-compatible</a>, or |
| 4712 |
only structurally equal. |
| 4713 |
The respective <a href="#Type_unification_rules">type unification rules</a> |
| 4714 |
are spelled out in detail in the <a href="#Appendix">Appendix</a>. |
| 4715 |
</p> |
| 4716 |
|
| 4717 |
<p> |
| 4718 |
For an equation of the form <code>X ≡<sub>A</sub> Y</code>, |
| 4719 |
where <code>X</code> and <code>Y</code> are types involved |
| 4720 |
in an assignment (including parameter passing and return statements), |
| 4721 |
the top-level type structures may unify loosely but element types |
| 4722 |
must unify exactly, matching the rules for assignments. |
| 4723 |
</p> |
| 4724 |
|
| 4725 |
<p> |
| 4726 |
For an equation of the form <code>P ≡<sub>C</sub> C</code>, |
| 4727 |
where <code>P</code> is a type parameter and <code>C</code> |
| 4728 |
its corresponding constraint, the unification rules are bit |
| 4729 |
more complicated: |
| 4730 |
</p> |
| 4731 |
|
| 4732 |
<ul> |
| 4733 |
<li> |
| 4734 |
If all types in <code>C</code>'s type set have the same |
| 4735 |
underlying type <code>U</code>, |
| 4736 |
and <code>P</code> has a known type argument <code>A</code>, |
| 4737 |
<code>U</code> and <code>A</code> must unify loosely. |
| 4738 |
</li> |
| 4739 |
<li> |
| 4740 |
Similarly, if all types in <code>C</code>'s type set are |
| 4741 |
channel types with the same element type and non-conflicting |
| 4742 |
channel directions, |
| 4743 |
and <code>P</code> has a known type argument <code>A</code>, |
| 4744 |
the most restrictive channel type in <code>C</code>'s type |
| 4745 |
set and <code>A</code> must unify loosely. |
| 4746 |
</li> |
| 4747 |
<li> |
| 4748 |
If <code>P</code> does not have a known type argument |
| 4749 |
and <code>C</code> contains exactly one type term <code>T</code> |
| 4750 |
that is not an underlying (tilde) type, unification adds the |
| 4751 |
mapping <code>P ➞ T</code> to the map. |
| 4752 |
</li> |
| 4753 |
<li> |
| 4754 |
If <code>C</code> does not have a type <code>U</code> |
| 4755 |
as described above |
| 4756 |
and <code>P</code> has a known type argument <code>A</code>, |
| 4757 |
<code>A</code> must have all methods of <code>C</code>, if any, |
| 4758 |
and corresponding method types must unify exactly. |
| 4759 |
</li> |
| 4760 |
</ul> |
| 4761 |
|
| 4762 |
<p> |
| 4763 |
When solving type equations from type constraints, |
| 4764 |
solving one equation may infer additional type arguments, |
| 4765 |
which in turn may enable solving other equations that depend |
| 4766 |
on those type arguments. |
| 4767 |
Type inference repeats type unification as long as new type |
| 4768 |
arguments are inferred. |
| 4769 |
</p> |
| 4770 |
|
| 4771 |
<h3 id="Operators">Operators</h3> |
| 4772 |
|
| 4773 |
<p> |
| 4774 |
Operators combine operands into expressions. |
| 4775 |
</p> |
| 4776 |
|
| 4777 |
<pre class="ebnf"> |
| 4778 |
Expression = UnaryExpr | Expression binary_op Expression . |
| 4779 |
UnaryExpr = PrimaryExpr | unary_op UnaryExpr . |
| 4780 |
|
| 4781 |
binary_op = "||" | "&&" | rel_op | add_op | mul_op . |
| 4782 |
rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" . |
| 4783 |
add_op = "+" | "-" | "|" | "^" . |
| 4784 |
mul_op = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" . |
| 4785 |
|
| 4786 |
unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-" . |
| 4787 |
</pre> |
| 4788 |
|
| 4789 |
<p> |
| 4790 |
Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>. |
| 4791 |
For other binary operators, the operand types must be <a href="#Type_identity">identical</a> |
| 4792 |
unless the operation involves shifts or untyped <a href="#Constants">constants</a>. |
| 4793 |
For operations involving constants only, see the section on |
| 4794 |
<a href="#Constant_expressions">constant expressions</a>. |
| 4795 |
</p> |
| 4796 |
|
| 4797 |
<p> |
| 4798 |
Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a> |
| 4799 |
and the other operand is not, the constant is implicitly <a href="#Conversions">converted</a> |
| 4800 |
to the type of the other operand. |
| 4801 |
</p> |
| 4802 |
|
| 4803 |
<p> |
| 4804 |
The right operand in a shift expression must have <a href="#Numeric_types">integer type</a> |
| 4805 |
[<a href="#Go_1.13">Go 1.13</a>] |
| 4806 |
or be an untyped constant <a href="#Representability">representable</a> by a |
| 4807 |
value of type <code>uint</code>. |
| 4808 |
If the left operand of a non-constant shift expression is an untyped constant, |
| 4809 |
it is first implicitly converted to the type it would assume if the shift expression were |
| 4810 |
replaced by its left operand alone. |
| 4811 |
</p> |
| 4812 |
|
| 4813 |
<pre> |
| 4814 |
var a [1024]byte |
| 4815 |
var s uint = 33 |
| 4816 |
|
| 4817 |
// The results of the following examples are given for 64-bit ints. |
| 4818 |
var i = 1<<s // 1 has type int |
| 4819 |
var j int32 = 1<<s // 1 has type int32; j == 0 |
| 4820 |
var k = uint64(1<<s) // 1 has type uint64; k == 1<<33 |
| 4821 |
var m int = 1.0<<s // 1.0 has type int; m == 1<<33 |
| 4822 |
var n = 1.0<<s == j // 1.0 has type int32; n == true |
| 4823 |
var o = 1<<s == 2<<s // 1 and 2 have type int; o == false |
| 4824 |
var p = 1<<s == 1<<33 // 1 has type int; p == true |
| 4825 |
var u = 1.0<<s // illegal: 1.0 has type float64, cannot shift |
| 4826 |
var u1 = 1.0<<s != 0 // illegal: 1.0 has type float64, cannot shift |
| 4827 |
var u2 = 1<<s != 1.0 // illegal: 1 has type float64, cannot shift |
| 4828 |
var v1 float32 = 1<<s // illegal: 1 has type float32, cannot shift |
| 4829 |
var v2 = string(1<<s) // illegal: 1 is converted to a string, cannot shift |
| 4830 |
var w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression; w == 1<<33 |
| 4831 |
var x = a[1.0<<s] // panics: 1.0 has type int, but 1<<33 overflows array bounds |
| 4832 |
var b = make([]byte, 1.0<<s) // 1.0 has type int; len(b) == 1<<33 |
| 4833 |
|
| 4834 |
// The results of the following examples are given for 32-bit ints, |
| 4835 |
// which means the shifts will overflow. |
| 4836 |
var mm int = 1.0<<s // 1.0 has type int; mm == 0 |
| 4837 |
var oo = 1<<s == 2<<s // 1 and 2 have type int; oo == true |
| 4838 |
var pp = 1<<s == 1<<33 // illegal: 1 has type int, but 1<<33 overflows int |
| 4839 |
var xx = a[1.0<<s] // 1.0 has type int; xx == a[0] |
| 4840 |
var bb = make([]byte, 1.0<<s) // 1.0 has type int; len(bb) == 0 |
| 4841 |
</pre> |
| 4842 |
|
| 4843 |
<h4 id="Operator_precedence">Operator precedence</h4> |
| 4844 |
<p> |
| 4845 |
Unary operators have the highest precedence. |
| 4846 |
As the <code>++</code> and <code>--</code> operators form |
| 4847 |
statements, not expressions, they fall |
| 4848 |
outside the operator hierarchy. |
| 4849 |
As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>. |
| 4850 |
</p> |
| 4851 |
<p> |
| 4852 |
There are five precedence levels for binary operators. |
| 4853 |
Multiplication operators bind strongest, followed by addition |
| 4854 |
operators, comparison operators, <code>&&</code> (logical AND), |
| 4855 |
and finally <code>||</code> (logical OR): |
| 4856 |
</p> |
| 4857 |
|
| 4858 |
<pre class="grammar"> |
| 4859 |
Precedence Operator |
| 4860 |
5 * / % << >> & &^ |
| 4861 |
4 + - | ^ |
| 4862 |
3 == != < <= > >= |
| 4863 |
2 && |
| 4864 |
1 || |
| 4865 |
</pre> |
| 4866 |
|
| 4867 |
<p> |
| 4868 |
Binary operators of the same precedence associate from left to right. |
| 4869 |
For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>. |
| 4870 |
</p> |
| 4871 |
|
| 4872 |
<pre> |
| 4873 |
+x // x |
| 4874 |
42 + a - b // (42 + a) - b |
| 4875 |
23 + 3*x[i] // 23 + (3 * x[i]) |
| 4876 |
x <= f() // x <= f() |
| 4877 |
^a >> b // (^a) >> b |
| 4878 |
f() || g() // f() || g() |
| 4879 |
x == y+1 && <-chanInt > 0 // (x == (y+1)) && ((<-chanInt) > 0) |
| 4880 |
</pre> |
| 4881 |
|
| 4882 |
|
| 4883 |
<h3 id="Arithmetic_operators">Arithmetic operators</h3> |
| 4884 |
<p> |
| 4885 |
Arithmetic operators apply to numeric values and yield a result of the same |
| 4886 |
type as the first operand. The four standard arithmetic operators (<code>+</code>, |
| 4887 |
<code>-</code>, <code>*</code>, <code>/</code>) apply to |
| 4888 |
<a href="#Numeric_types">integer</a>, <a href="#Numeric_types">floating-point</a>, and |
| 4889 |
<a href="#Numeric_types">complex</a> types; <code>+</code> also applies to <a href="#String_types">strings</a>. |
| 4890 |
The bitwise logical and shift operators apply to integers only. |
| 4891 |
</p> |
| 4892 |
|
| 4893 |
<pre class="grammar"> |
| 4894 |
+ sum integers, floats, complex values, strings |
| 4895 |
- difference integers, floats, complex values |
| 4896 |
* product integers, floats, complex values |
| 4897 |
/ quotient integers, floats, complex values |
| 4898 |
% remainder integers |
| 4899 |
|
| 4900 |
& bitwise AND integers |
| 4901 |
| bitwise OR integers |
| 4902 |
^ bitwise XOR integers |
| 4903 |
&^ bit clear (AND NOT) integers |
| 4904 |
|
| 4905 |
<< left shift integer << integer >= 0 |
| 4906 |
>> right shift integer >> integer >= 0 |
| 4907 |
</pre> |
| 4908 |
|
| 4909 |
<p> |
| 4910 |
If the operand type is a <a href="#Type_parameter_declarations">type parameter</a>, |
| 4911 |
the operator must apply to each type in that type set. |
| 4912 |
The operands are represented as values of the type argument that the type parameter |
| 4913 |
is <a href="#Instantiations">instantiated</a> with, and the operation is computed |
| 4914 |
with the precision of that type argument. For example, given the function: |
| 4915 |
</p> |
| 4916 |
|
| 4917 |
<pre> |
| 4918 |
func dotProduct[F ~float32|~float64](v1, v2 []F) F { |
| 4919 |
var s F |
| 4920 |
for i, x := range v1 { |
| 4921 |
y := v2[i] |
| 4922 |
s += x * y |
| 4923 |
} |
| 4924 |
return s |
| 4925 |
} |
| 4926 |
</pre> |
| 4927 |
|
| 4928 |
<p> |
| 4929 |
the product <code>x * y</code> and the addition <code>s += x * y</code> |
| 4930 |
are computed with <code>float32</code> or <code>float64</code> precision, |
| 4931 |
respectively, depending on the type argument for <code>F</code>. |
| 4932 |
</p> |
| 4933 |
|
| 4934 |
<h4 id="Integer_operators">Integer operators</h4> |
| 4935 |
|
| 4936 |
<p> |
| 4937 |
For two integer values <code>x</code> and <code>y</code>, the integer quotient |
| 4938 |
<code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following |
| 4939 |
relationships: |
| 4940 |
</p> |
| 4941 |
|
| 4942 |
<pre> |
| 4943 |
x = q*y + r and |r| < |y| |
| 4944 |
</pre> |
| 4945 |
|
| 4946 |
<p> |
| 4947 |
with <code>x / y</code> truncated towards zero |
| 4948 |
(<a href="https://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>). |
| 4949 |
</p> |
| 4950 |
|
| 4951 |
<pre> |
| 4952 |
x y x / y x % y |
| 4953 |
5 3 1 2 |
| 4954 |
-5 3 -1 -2 |
| 4955 |
5 -3 -1 2 |
| 4956 |
-5 -3 1 -2 |
| 4957 |
</pre> |
| 4958 |
|
| 4959 |
<p> |
| 4960 |
The one exception to this rule is that if the dividend <code>x</code> is |
| 4961 |
the most negative value for the int type of <code>x</code>, the quotient |
| 4962 |
<code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>) |
| 4963 |
due to two's-complement <a href="#Integer_overflow">integer overflow</a>: |
| 4964 |
</p> |
| 4965 |
|
| 4966 |
<pre> |
| 4967 |
x, q |
| 4968 |
int8 -128 |
| 4969 |
int16 -32768 |
| 4970 |
int32 -2147483648 |
| 4971 |
int64 -9223372036854775808 |
| 4972 |
</pre> |
| 4973 |
|
| 4974 |
<p> |
| 4975 |
If the divisor is a <a href="#Constants">constant</a>, it must not be zero. |
| 4976 |
If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. |
| 4977 |
If the dividend is non-negative and the divisor is a constant power of 2, |
| 4978 |
the division may be replaced by a right shift, and computing the remainder may |
| 4979 |
be replaced by a bitwise AND operation: |
| 4980 |
</p> |
| 4981 |
|
| 4982 |
<pre> |
| 4983 |
x x / 4 x % 4 x >> 2 x & 3 |
| 4984 |
11 2 3 2 3 |
| 4985 |
-11 -2 -3 -3 1 |
| 4986 |
</pre> |
| 4987 |
|
| 4988 |
<p> |
| 4989 |
The shift operators shift the left operand by the shift count specified by the |
| 4990 |
right operand, which must be non-negative. If the shift count is negative at run time, |
| 4991 |
a <a href="#Run_time_panics">run-time panic</a> occurs. |
| 4992 |
The shift operators implement arithmetic shifts if the left operand is a signed |
| 4993 |
integer and logical shifts if it is an unsigned integer. |
| 4994 |
There is no upper limit on the shift count. Shifts behave |
| 4995 |
as if the left operand is shifted <code>n</code> times by 1 for a shift |
| 4996 |
count of <code>n</code>. |
| 4997 |
As a result, <code>x << 1</code> is the same as <code>x*2</code> |
| 4998 |
and <code>x >> 1</code> is the same as |
| 4999 |
<code>x/2</code> but truncated towards negative infinity. |
| 5000 |
</p> |
| 5001 |
|
| 5002 |
<p> |
| 5003 |
For integer operands, the unary operators |
| 5004 |
<code>+</code>, <code>-</code>, and <code>^</code> are defined as |
| 5005 |
follows: |
| 5006 |
</p> |
| 5007 |
|
| 5008 |
<pre class="grammar"> |
| 5009 |
+x is 0 + x |
| 5010 |
-x negation is 0 - x |
| 5011 |
^x bitwise complement is m ^ x with m = "all bits set to 1" for unsigned x |
| 5012 |
and m = -1 for signed x |
| 5013 |
</pre> |
| 5014 |
|
| 5015 |
|
| 5016 |
<h4 id="Integer_overflow">Integer overflow</h4> |
| 5017 |
|
| 5018 |
<p> |
| 5019 |
For <a href="#Numeric_types">unsigned integer</a> values, the operations <code>+</code>, |
| 5020 |
<code>-</code>, <code>*</code>, and <code><<</code> are |
| 5021 |
computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of |
| 5022 |
the unsigned integer's type. |
| 5023 |
Loosely speaking, these unsigned integer operations |
| 5024 |
discard high bits upon overflow, and programs may rely on "wrap around". |
| 5025 |
</p> |
| 5026 |
|
| 5027 |
<p> |
| 5028 |
For signed integers, the operations <code>+</code>, |
| 5029 |
<code>-</code>, <code>*</code>, <code>/</code>, and <code><<</code> may legally |
| 5030 |
overflow and the resulting value exists and is deterministically defined |
| 5031 |
by the signed integer representation, the operation, and its operands. |
| 5032 |
Overflow does not cause a <a href="#Run_time_panics">run-time panic</a>. |
| 5033 |
A compiler may not optimize code under the assumption that overflow does |
| 5034 |
not occur. For instance, it may not assume that <code>x < x + 1</code> is always true. |
| 5035 |
</p> |
| 5036 |
|
| 5037 |
<h4 id="Floating_point_operators">Floating-point operators</h4> |
| 5038 |
|
| 5039 |
<p> |
| 5040 |
For floating-point and complex numbers, |
| 5041 |
<code>+x</code> is the same as <code>x</code>, |
| 5042 |
while <code>-x</code> is the negation of <code>x</code>. |
| 5043 |
The result of a floating-point or complex division by zero is not specified beyond the |
| 5044 |
IEEE 754 standard; whether a <a href="#Run_time_panics">run-time panic</a> |
| 5045 |
occurs is implementation-specific. |
| 5046 |
</p> |
| 5047 |
|
| 5048 |
<p> |
| 5049 |
An implementation may combine multiple floating-point operations into a single |
| 5050 |
fused operation, possibly across statements, and produce a result that differs |
| 5051 |
from the value obtained by executing and rounding the instructions individually. |
| 5052 |
An explicit <a href="#Numeric_types">floating-point type</a> <a href="#Conversions">conversion</a> rounds to |
| 5053 |
the precision of the target type, preventing fusion that would discard that rounding. |
| 5054 |
</p> |
| 5055 |
|
| 5056 |
<p> |
| 5057 |
For instance, some architectures provide a "fused multiply and add" (FMA) instruction |
| 5058 |
that computes <code>x*y + z</code> without rounding the intermediate result <code>x*y</code>. |
| 5059 |
These examples show when a Go implementation can use that instruction: |
| 5060 |
</p> |
| 5061 |
|
| 5062 |
<pre> |
| 5063 |
// FMA allowed for computing r, because x*y is not explicitly rounded: |
| 5064 |
r = x*y + z |
| 5065 |
r = z; r += x*y |
| 5066 |
t = x*y; r = t + z |
| 5067 |
*p = x*y; r = *p + z |
| 5068 |
r = x*y + float64(z) |
| 5069 |
|
| 5070 |
// FMA disallowed for computing r, because it would omit rounding of x*y: |
| 5071 |
r = float64(x*y) + z |
| 5072 |
r = z; r += float64(x*y) |
| 5073 |
t = float64(x*y); r = t + z |
| 5074 |
</pre> |
| 5075 |
|
| 5076 |
<h4 id="String_concatenation">String concatenation</h4> |
| 5077 |
|
| 5078 |
<p> |
| 5079 |
Strings can be concatenated using the <code>+</code> operator |
| 5080 |
or the <code>+=</code> assignment operator: |
| 5081 |
</p> |
| 5082 |
|
| 5083 |
<pre> |
| 5084 |
s := "hi" + string(c) |
| 5085 |
s += " and good bye" |
| 5086 |
</pre> |
| 5087 |
|
| 5088 |
<p> |
| 5089 |
String addition creates a new string by concatenating the operands. |
| 5090 |
</p> |
| 5091 |
|
| 5092 |
<h3 id="Comparison_operators">Comparison operators</h3> |
| 5093 |
|
| 5094 |
<p> |
| 5095 |
Comparison operators compare two operands and yield an untyped boolean value. |
| 5096 |
</p> |
| 5097 |
|
| 5098 |
<pre class="grammar"> |
| 5099 |
== equal |
| 5100 |
!= not equal |
| 5101 |
< less |
| 5102 |
<= less or equal |
| 5103 |
> greater |
| 5104 |
>= greater or equal |
| 5105 |
</pre> |
| 5106 |
|
| 5107 |
<p> |
| 5108 |
In any comparison, the first operand |
| 5109 |
must be <a href="#Assignability">assignable</a> |
| 5110 |
to the type of the second operand, or vice versa. |
| 5111 |
</p> |
| 5112 |
<p> |
| 5113 |
The equality operators <code>==</code> and <code>!=</code> apply |
| 5114 |
to operands of <i>comparable</i> types. |
| 5115 |
The ordering operators <code><</code>, <code><=</code>, <code>></code>, and <code>>=</code> |
| 5116 |
apply to operands of <i>ordered</i> types. |
| 5117 |
These terms and the result of the comparisons are defined as follows: |
| 5118 |
</p> |
| 5119 |
|
| 5120 |
<ul> |
| 5121 |
<li> |
| 5122 |
Boolean types are comparable. |
| 5123 |
Two boolean values are equal if they are either both |
| 5124 |
<code>true</code> or both <code>false</code>. |
| 5125 |
</li> |
| 5126 |
|
| 5127 |
<li> |
| 5128 |
Integer types are comparable and ordered. |
| 5129 |
Two integer values are compared in the usual way. |
| 5130 |
</li> |
| 5131 |
|
| 5132 |
<li> |
| 5133 |
Floating-point types are comparable and ordered. |
| 5134 |
Two floating-point values are compared as defined by the IEEE 754 standard. |
| 5135 |
</li> |
| 5136 |
|
| 5137 |
<li> |
| 5138 |
Complex types are comparable. |
| 5139 |
Two complex values <code>u</code> and <code>v</code> are |
| 5140 |
equal if both <code>real(u) == real(v)</code> and |
| 5141 |
<code>imag(u) == imag(v)</code>. |
| 5142 |
</li> |
| 5143 |
|
| 5144 |
<li> |
| 5145 |
String types are comparable and ordered. |
| 5146 |
Two string values are compared lexically byte-wise. |
| 5147 |
</li> |
| 5148 |
|
| 5149 |
<li> |
| 5150 |
Pointer types are comparable. |
| 5151 |
Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>. |
| 5152 |
Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal. |
| 5153 |
</li> |
| 5154 |
|
| 5155 |
<li> |
| 5156 |
Channel types are comparable. |
| 5157 |
Two channel values are equal if they were created by the same call to |
| 5158 |
<a href="#Making_slices_maps_and_channels"><code>make</code></a> |
| 5159 |
or if both have value <code>nil</code>. |
| 5160 |
</li> |
| 5161 |
|
| 5162 |
<li> |
| 5163 |
Interface types that are not type parameters are comparable. |
| 5164 |
Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types |
| 5165 |
and equal dynamic values or if both have value <code>nil</code>. |
| 5166 |
</li> |
| 5167 |
|
| 5168 |
<li> |
| 5169 |
A value <code>x</code> of non-interface type <code>X</code> and |
| 5170 |
a value <code>t</code> of interface type <code>T</code> can be compared |
| 5171 |
if type <code>X</code> is comparable and |
| 5172 |
<code>X</code> <a href="#Implementing_an_interface">implements</a> <code>T</code>. |
| 5173 |
They are equal if <code>t</code>'s dynamic type is identical to <code>X</code> |
| 5174 |
and <code>t</code>'s dynamic value is equal to <code>x</code>. |
| 5175 |
</li> |
| 5176 |
|
| 5177 |
<li> |
| 5178 |
Struct types are comparable if all their field types are comparable. |
| 5179 |
Two struct values are equal if their corresponding |
| 5180 |
non-<a href="#Blank_identifier">blank</a> field values are equal. |
| 5181 |
The fields are compared in source order, and comparison stops as |
| 5182 |
soon as two field values differ (or all fields have been compared). |
| 5183 |
</li> |
| 5184 |
|
| 5185 |
<li> |
| 5186 |
Array types are comparable if their array element types are comparable. |
| 5187 |
Two array values are equal if their corresponding element values are equal. |
| 5188 |
The elements are compared in ascending index order, and comparison stops |
| 5189 |
as soon as two element values differ (or all elements have been compared). |
| 5190 |
</li> |
| 5191 |
|
| 5192 |
<li> |
| 5193 |
Type parameters are comparable if they are strictly comparable (see below). |
| 5194 |
</li> |
| 5195 |
</ul> |
| 5196 |
|
| 5197 |
<p> |
| 5198 |
A comparison of two interface values with identical dynamic types |
| 5199 |
causes a <a href="#Run_time_panics">run-time panic</a> if that type |
| 5200 |
is not comparable. This behavior applies not only to direct interface |
| 5201 |
value comparisons but also when comparing arrays of interface values |
| 5202 |
or structs with interface-valued fields. |
| 5203 |
</p> |
| 5204 |
|
| 5205 |
<p> |
| 5206 |
Slice, map, and function types are not comparable. |
| 5207 |
However, as a special case, a slice, map, or function value may |
| 5208 |
be compared to the predeclared identifier <code>nil</code>. |
| 5209 |
Comparison of pointer, channel, and interface values to <code>nil</code> |
| 5210 |
is also allowed and follows from the general rules above. |
| 5211 |
</p> |
| 5212 |
|
| 5213 |
<pre> |
| 5214 |
const c = 3 < 4 // c is the untyped boolean constant true |
| 5215 |
|
| 5216 |
type MyBool bool |
| 5217 |
var x, y int |
| 5218 |
var ( |
| 5219 |
// The result of a comparison is an untyped boolean. |
| 5220 |
// The usual assignment rules apply. |
| 5221 |
b3 = x == y // b3 has type bool |
| 5222 |
b4 bool = x == y // b4 has type bool |
| 5223 |
b5 MyBool = x == y // b5 has type MyBool |
| 5224 |
) |
| 5225 |
</pre> |
| 5226 |
|
| 5227 |
<p> |
| 5228 |
A type is <i>strictly comparable</i> if it is comparable and not an interface |
| 5229 |
type nor composed of interface types. |
| 5230 |
Specifically: |
| 5231 |
</p> |
| 5232 |
|
| 5233 |
<ul> |
| 5234 |
<li> |
| 5235 |
Boolean, numeric, string, pointer, and channel types are strictly comparable. |
| 5236 |
</li> |
| 5237 |
|
| 5238 |
<li> |
| 5239 |
Struct types are strictly comparable if all their field types are strictly comparable. |
| 5240 |
</li> |
| 5241 |
|
| 5242 |
<li> |
| 5243 |
Array types are strictly comparable if their array element types are strictly comparable. |
| 5244 |
</li> |
| 5245 |
|
| 5246 |
<li> |
| 5247 |
Type parameters are strictly comparable if all types in their type set are strictly comparable. |
| 5248 |
</li> |
| 5249 |
</ul> |
| 5250 |
|
| 5251 |
<h3 id="Logical_operators">Logical operators</h3> |
| 5252 |
|
| 5253 |
<p> |
| 5254 |
Logical operators apply to <a href="#Boolean_types">boolean</a> values |
| 5255 |
and yield a result of the same type as the operands. |
| 5256 |
The left operand is evaluated, and then the right if the condition requires it. |
| 5257 |
</p> |
| 5258 |
|
| 5259 |
<pre class="grammar"> |
| 5260 |
&& conditional AND p && q is "if p then q else false" |
| 5261 |
|| conditional OR p || q is "if p then true else q" |
| 5262 |
! NOT !p is "not p" |
| 5263 |
</pre> |
| 5264 |
|
| 5265 |
|
| 5266 |
<h3 id="Address_operators">Address operators</h3> |
| 5267 |
|
| 5268 |
<p> |
| 5269 |
For an operand <code>x</code> of type <code>T</code>, the address operation |
| 5270 |
<code>&x</code> generates a pointer of type <code>*T</code> to <code>x</code>. |
| 5271 |
The operand must be <i>addressable</i>, |
| 5272 |
that is, either a variable, pointer indirection, or slice indexing |
| 5273 |
operation; or a field selector of an addressable struct operand; |
| 5274 |
or an array indexing operation of an addressable array. |
| 5275 |
As an exception to the addressability requirement, <code>x</code> may also be a |
| 5276 |
(possibly parenthesized) |
| 5277 |
<a href="#Composite_literals">composite literal</a>. |
| 5278 |
If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>, |
| 5279 |
then the evaluation of <code>&x</code> does too. |
| 5280 |
</p> |
| 5281 |
|
| 5282 |
<p> |
| 5283 |
For an operand <code>x</code> of pointer type <code>*T</code>, the pointer |
| 5284 |
indirection <code>*x</code> denotes the <a href="#Variables">variable</a> of type <code>T</code> pointed |
| 5285 |
to by <code>x</code>. |
| 5286 |
If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code> |
| 5287 |
will cause a <a href="#Run_time_panics">run-time panic</a>. |
| 5288 |
</p> |
| 5289 |
|
| 5290 |
<pre> |
| 5291 |
&x |
| 5292 |
&a[f(2)] |
| 5293 |
&Point{2, 3} |
| 5294 |
*p |
| 5295 |
*pf(x) |
| 5296 |
|
| 5297 |
var x *int = nil |
| 5298 |
*x // causes a run-time panic |
| 5299 |
&*x // causes a run-time panic |
| 5300 |
</pre> |
| 5301 |
|
| 5302 |
|
| 5303 |
<h3 id="Receive_operator">Receive operator</h3> |
| 5304 |
|
| 5305 |
<p> |
| 5306 |
For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>, |
| 5307 |
the value of the receive operation <code><-ch</code> is the value received |
| 5308 |
from the channel <code>ch</code>. |
| 5309 |
The channel direction must permit receive operations, |
| 5310 |
and the type of the receive operation is the element type of the channel. |
| 5311 |
The expression blocks until a value is available. |
| 5312 |
Receiving from a <code>nil</code> channel blocks forever. |
| 5313 |
A receive operation on a <a href="#Close">closed</a> channel can always proceed |
| 5314 |
immediately, yielding the element type's <a href="#The_zero_value">zero value</a> |
| 5315 |
after any previously sent values have been received. |
| 5316 |
</p> |
| 5317 |
|
| 5318 |
<pre> |
| 5319 |
v1 := <-ch |
| 5320 |
v2 = <-ch |
| 5321 |
f(<-ch) |
| 5322 |
<-strobe // wait until clock pulse and discard received value |
| 5323 |
</pre> |
| 5324 |
|
| 5325 |
<p> |
| 5326 |
If the operand type is a <a href="#Type_parameter_declarations">type parameter</a>, |
| 5327 |
all types in its type set must be channel types that permit receive operations, and |
| 5328 |
they must all have the same element type, which is the type of the receive operation. |
| 5329 |
</p> |
| 5330 |
|
| 5331 |
<p> |
| 5332 |
A receive expression used in an <a href="#Assignment_statements">assignment statement</a> or initialization of the special form |
| 5333 |
</p> |
| 5334 |
|
| 5335 |
<pre> |
| 5336 |
x, ok = <-ch |
| 5337 |
x, ok := <-ch |
| 5338 |
var x, ok = <-ch |
| 5339 |
var x, ok T = <-ch |
| 5340 |
</pre> |
| 5341 |
|
| 5342 |
<p> |
| 5343 |
yields an additional untyped boolean result reporting whether the |
| 5344 |
communication succeeded. The value of <code>ok</code> is <code>true</code> |
| 5345 |
if the value received was delivered by a successful send operation to the |
| 5346 |
channel, or <code>false</code> if it is a zero value generated because the |
| 5347 |
channel is closed and empty. |
| 5348 |
</p> |
| 5349 |
|
| 5350 |
|
| 5351 |
<h3 id="Conversions">Conversions</h3> |
| 5352 |
|
| 5353 |
<p> |
| 5354 |
A conversion changes the <a href="#Types">type</a> of an expression |
| 5355 |
to the type specified by the conversion. |
| 5356 |
A conversion may appear literally in the source, or it may be <i>implied</i> |
| 5357 |
by the context in which an expression appears. |
| 5358 |
</p> |
| 5359 |
|
| 5360 |
<p> |
| 5361 |
An <i>explicit</i> conversion is an expression of the form <code>T(x)</code> |
| 5362 |
where <code>T</code> is a type and <code>x</code> is an expression |
| 5363 |
that can be converted to type <code>T</code>. |
| 5364 |
</p> |
| 5365 |
|
| 5366 |
<pre class="ebnf"> |
| 5367 |
Conversion = Type "(" Expression [ "," ] ")" . |
| 5368 |
</pre> |
| 5369 |
|
| 5370 |
<p> |
| 5371 |
If the type starts with the operator <code>*</code> or <code><-</code>, |
| 5372 |
or if the type starts with the keyword <code>func</code> |
| 5373 |
and has no result list, it must be parenthesized when |
| 5374 |
necessary to avoid ambiguity: |
| 5375 |
</p> |
| 5376 |
|
| 5377 |
<pre> |
| 5378 |
*Point(p) // same as *(Point(p)) |
| 5379 |
(*Point)(p) // p is converted to *Point |
| 5380 |
<-chan int(c) // same as <-(chan int(c)) |
| 5381 |
(<-chan int)(c) // c is converted to <-chan int |
| 5382 |
func()(x) // function signature func() x |
| 5383 |
(func())(x) // x is converted to func() |
| 5384 |
(func() int)(x) // x is converted to func() int |
| 5385 |
func() int(x) // x is converted to func() int (unambiguous) |
| 5386 |
</pre> |
| 5387 |
|
| 5388 |
<p> |
| 5389 |
A <a href="#Constants">constant</a> value <code>x</code> can be converted to |
| 5390 |
type <code>T</code> if <code>x</code> is <a href="#Representability">representable</a> |
| 5391 |
by a value of <code>T</code>. |
| 5392 |
As a special case, an integer constant <code>x</code> can be explicitly converted to a |
| 5393 |
<a href="#String_types">string type</a> using the |
| 5394 |
<a href="#Conversions_to_and_from_a_string_type">same rule</a> |
| 5395 |
as for non-constant <code>x</code>. |
| 5396 |
</p> |
| 5397 |
|
| 5398 |
<p> |
| 5399 |
Converting a constant to a type that is not a <a href="#Type_parameter_declarations">type parameter</a> |
| 5400 |
yields a typed constant. |
| 5401 |
</p> |
| 5402 |
|
| 5403 |
<pre> |
| 5404 |
uint(iota) // iota value of type uint |
| 5405 |
float32(2.718281828) // 2.718281828 of type float32 |
| 5406 |
complex128(1) // 1.0 + 0.0i of type complex128 |
| 5407 |
float32(0.49999999) // 0.5 of type float32 |
| 5408 |
float64(-1e-1000) // 0.0 of type float64 |
| 5409 |
string('x') // "x" of type string |
| 5410 |
string(0x266c) // "♬" of type string |
| 5411 |
myString("foo" + "bar") // "foobar" of type myString |
| 5412 |
string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant |
| 5413 |
(*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type |
| 5414 |
int(1.2) // illegal: 1.2 cannot be represented as an int |
| 5415 |
string(65.0) // illegal: 65.0 is not an integer constant |
| 5416 |
</pre> |
| 5417 |
|
| 5418 |
<p> |
| 5419 |
Converting a constant to a type parameter yields a <i>non-constant</i> value of that type, |
| 5420 |
with the value represented as a value of the type argument that the type parameter |
| 5421 |
is <a href="#Instantiations">instantiated</a> with. |
| 5422 |
For example, given the function: |
| 5423 |
</p> |
| 5424 |
|
| 5425 |
<pre> |
| 5426 |
func f[P ~float32|~float64]() { |
| 5427 |
… P(1.1) … |
| 5428 |
} |
| 5429 |
</pre> |
| 5430 |
|
| 5431 |
<p> |
| 5432 |
the conversion <code>P(1.1)</code> results in a non-constant value of type <code>P</code> |
| 5433 |
and the value <code>1.1</code> is represented as a <code>float32</code> or a <code>float64</code> |
| 5434 |
depending on the type argument for <code>f</code>. |
| 5435 |
Accordingly, if <code>f</code> is instantiated with a <code>float32</code> type, |
| 5436 |
the numeric value of the expression <code>P(1.1) + 1.2</code> will be computed |
| 5437 |
with the same precision as the corresponding non-constant <code>float32</code> |
| 5438 |
addition. |
| 5439 |
</p> |
| 5440 |
|
| 5441 |
<p> |
| 5442 |
A non-constant value <code>x</code> can be converted to type <code>T</code> |
| 5443 |
in any of these cases: |
| 5444 |
</p> |
| 5445 |
|
| 5446 |
<ul> |
| 5447 |
<li> |
| 5448 |
<code>x</code> is <a href="#Assignability">assignable</a> |
| 5449 |
to <code>T</code>. |
| 5450 |
</li> |
| 5451 |
<li> |
| 5452 |
ignoring struct tags (see below), |
| 5453 |
<code>x</code>'s type and <code>T</code> are not |
| 5454 |
<a href="#Type_parameter_declarations">type parameters</a> but have |
| 5455 |
<a href="#Type_identity">identical</a> <a href="#Underlying_types">underlying types</a>. |
| 5456 |
</li> |
| 5457 |
<li> |
| 5458 |
ignoring struct tags (see below), |
| 5459 |
<code>x</code>'s type and <code>T</code> are pointer types |
| 5460 |
that are not <a href="#Types">named types</a>, |
| 5461 |
and their pointer base types are not type parameters but |
| 5462 |
have identical underlying types. |
| 5463 |
</li> |
| 5464 |
<li> |
| 5465 |
<code>x</code>'s type and <code>T</code> are both integer or floating |
| 5466 |
point types. |
| 5467 |
</li> |
| 5468 |
<li> |
| 5469 |
<code>x</code>'s type and <code>T</code> are both complex types. |
| 5470 |
</li> |
| 5471 |
<li> |
| 5472 |
<code>x</code> is an integer or a slice of bytes or runes |
| 5473 |
and <code>T</code> is a string type. |
| 5474 |
</li> |
| 5475 |
<li> |
| 5476 |
<code>x</code> is a string and <code>T</code> is a slice of bytes or runes. |
| 5477 |
</li> |
| 5478 |
<li> |
| 5479 |
<code>x</code> is a slice, <code>T</code> is an array [<a href="#Go_1.20">Go 1.20</a>] |
| 5480 |
or a pointer to an array [<a href="#Go_1.17">Go 1.17</a>], |
| 5481 |
and the slice and array types have <a href="#Type_identity">identical</a> element types. |
| 5482 |
</li> |
| 5483 |
</ul> |
| 5484 |
|
| 5485 |
<p> |
| 5486 |
Additionally, if <code>T</code> or <code>x</code>'s type <code>V</code> are type |
| 5487 |
parameters, <code>x</code> |
| 5488 |
can also be converted to type <code>T</code> if one of the following conditions applies: |
| 5489 |
</p> |
| 5490 |
|
| 5491 |
<ul> |
| 5492 |
<li> |
| 5493 |
Both <code>V</code> and <code>T</code> are type parameters and a value of each |
| 5494 |
type in <code>V</code>'s type set can be converted to each type in <code>T</code>'s |
| 5495 |
type set. |
| 5496 |
</li> |
| 5497 |
<li> |
| 5498 |
Only <code>V</code> is a type parameter and a value of each |
| 5499 |
type in <code>V</code>'s type set can be converted to <code>T</code>. |
| 5500 |
</li> |
| 5501 |
<li> |
| 5502 |
Only <code>T</code> is a type parameter and <code>x</code> can be converted to each |
| 5503 |
type in <code>T</code>'s type set. |
| 5504 |
</li> |
| 5505 |
</ul> |
| 5506 |
|
| 5507 |
<p> |
| 5508 |
<a href="#Struct_types">Struct tags</a> are ignored when comparing struct types |
| 5509 |
for identity for the purpose of conversion: |
| 5510 |
</p> |
| 5511 |
|
| 5512 |
<pre> |
| 5513 |
type Person struct { |
| 5514 |
Name string |
| 5515 |
Address *struct { |
| 5516 |
Street string |
| 5517 |
City string |
| 5518 |
} |
| 5519 |
} |
| 5520 |
|
| 5521 |
var data *struct { |
| 5522 |
Name string `json:"name"` |
| 5523 |
Address *struct { |
| 5524 |
Street string `json:"street"` |
| 5525 |
City string `json:"city"` |
| 5526 |
} `json:"address"` |
| 5527 |
} |
| 5528 |
|
| 5529 |
var person = (*Person)(data) // ignoring tags, the underlying types are identical |
| 5530 |
</pre> |
| 5531 |
|
| 5532 |
<p> |
| 5533 |
Specific rules apply to (non-constant) conversions between numeric types or |
| 5534 |
to and from a string type. |
| 5535 |
These conversions may change the representation of <code>x</code> |
| 5536 |
and incur a run-time cost. |
| 5537 |
All other conversions only change the type but not the representation |
| 5538 |
of <code>x</code>. |
| 5539 |
</p> |
| 5540 |
|
| 5541 |
<p> |
| 5542 |
There is no linguistic mechanism to convert between pointers and integers. |
| 5543 |
The package <a href="#Package_unsafe"><code>unsafe</code></a> |
| 5544 |
implements this functionality under restricted circumstances. |
| 5545 |
</p> |
| 5546 |
|
| 5547 |
<h4>Conversions between numeric types</h4> |
| 5548 |
|
| 5549 |
<p> |
| 5550 |
For the conversion of non-constant numeric values, the following rules apply: |
| 5551 |
</p> |
| 5552 |
|
| 5553 |
<ol> |
| 5554 |
<li> |
| 5555 |
When converting between <a href="#Numeric_types">integer types</a>, if the value is a signed integer, it is |
| 5556 |
sign extended to implicit infinite precision; otherwise it is zero extended. |
| 5557 |
It is then truncated to fit in the result type's size. |
| 5558 |
For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>. |
| 5559 |
The conversion always yields a valid value; there is no indication of overflow. |
| 5560 |
</li> |
| 5561 |
<li> |
| 5562 |
When converting a <a href="#Numeric_types">floating-point number</a> to an integer, the fraction is discarded |
| 5563 |
(truncation towards zero). |
| 5564 |
</li> |
| 5565 |
<li> |
| 5566 |
When converting an integer or floating-point number to a floating-point type, |
| 5567 |
or a <a href="#Numeric_types">complex number</a> to another complex type, the result value is rounded |
| 5568 |
to the precision specified by the destination type. |
| 5569 |
For instance, the value of a variable <code>x</code> of type <code>float32</code> |
| 5570 |
may be stored using additional precision beyond that of an IEEE 754 32-bit number, |
| 5571 |
but float32(x) represents the result of rounding <code>x</code>'s value to |
| 5572 |
32-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits |
| 5573 |
of precision, but <code>float32(x + 0.1)</code> does not. |
| 5574 |
</li> |
| 5575 |
</ol> |
| 5576 |
|
| 5577 |
<p> |
| 5578 |
In all non-constant conversions involving floating-point or complex values, |
| 5579 |
if the result type cannot represent the value the conversion |
| 5580 |
succeeds but the result value is implementation-dependent. |
| 5581 |
</p> |
| 5582 |
|
| 5583 |
<h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4> |
| 5584 |
|
| 5585 |
<ol> |
| 5586 |
<li> |
| 5587 |
Converting a slice of bytes to a string type yields |
| 5588 |
a string whose successive bytes are the elements of the slice. |
| 5589 |
|
| 5590 |
<pre> |
| 5591 |
string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø" |
| 5592 |
string([]byte{}) // "" |
| 5593 |
string([]byte(nil)) // "" |
| 5594 |
|
| 5595 |
type bytes []byte |
| 5596 |
string(bytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø" |
| 5597 |
|
| 5598 |
type myByte byte |
| 5599 |
string([]myByte{'w', 'o', 'r', 'l', 'd', '!'}) // "world!" |
| 5600 |
myString([]myByte{'\xf0', '\x9f', '\x8c', '\x8d'}) // "🌍" |
| 5601 |
</pre> |
| 5602 |
</li> |
| 5603 |
|
| 5604 |
<li> |
| 5605 |
Converting a slice of runes to a string type yields |
| 5606 |
a string that is the concatenation of the individual rune values |
| 5607 |
converted to strings. |
| 5608 |
|
| 5609 |
<pre> |
| 5610 |
string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" |
| 5611 |
string([]rune{}) // "" |
| 5612 |
string([]rune(nil)) // "" |
| 5613 |
|
| 5614 |
type runes []rune |
| 5615 |
string(runes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" |
| 5616 |
|
| 5617 |
type myRune rune |
| 5618 |
string([]myRune{0x266b, 0x266c}) // "\u266b\u266c" == "♫♬" |
| 5619 |
myString([]myRune{0x1f30e}) // "\U0001f30e" == "🌎" |
| 5620 |
</pre> |
| 5621 |
</li> |
| 5622 |
|
| 5623 |
<li> |
| 5624 |
Converting a value of a string type to a slice of bytes type |
| 5625 |
yields a non-nil slice whose successive elements are the bytes of the string. |
| 5626 |
The <a href="#Length_and_capacity">capacity</a> of the resulting slice is |
| 5627 |
implementation-specific and may be larger than the slice length. |
| 5628 |
|
| 5629 |
<pre> |
| 5630 |
[]byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} |
| 5631 |
[]byte("") // []byte{} |
| 5632 |
|
| 5633 |
bytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} |
| 5634 |
|
| 5635 |
[]myByte("world!") // []myByte{'w', 'o', 'r', 'l', 'd', '!'} |
| 5636 |
[]myByte(myString("🌏")) // []myByte{'\xf0', '\x9f', '\x8c', '\x8f'} |
| 5637 |
</pre> |
| 5638 |
</li> |
| 5639 |
|
| 5640 |
<li> |
| 5641 |
Converting a value of a string type to a slice of runes type |
| 5642 |
yields a slice containing the individual Unicode code points of the string. |
| 5643 |
The <a href="#Length_and_capacity">capacity</a> of the resulting slice is |
| 5644 |
implementation-specific and may be larger than the slice length. |
| 5645 |
|
| 5646 |
<pre> |
| 5647 |
[]rune(myString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4} |
| 5648 |
[]rune("") // []rune{} |
| 5649 |
|
| 5650 |
runes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4} |
| 5651 |
|
| 5652 |
[]myRune("♫♬") // []myRune{0x266b, 0x266c} |
| 5653 |
[]myRune(myString("🌐")) // []myRune{0x1f310} |
| 5654 |
</pre> |
| 5655 |
</li> |
| 5656 |
|
| 5657 |
<li> |
| 5658 |
Finally, for historical reasons, an integer value may be converted to a string type. |
| 5659 |
This form of conversion yields a string containing the (possibly multi-byte) UTF-8 |
| 5660 |
representation of the Unicode code point with the given integer value. |
| 5661 |
Values outside the range of valid Unicode code points are converted to <code>"\uFFFD"</code>. |
| 5662 |
|
| 5663 |
<pre> |
| 5664 |
string('a') // "a" |
| 5665 |
string(65) // "A" |
| 5666 |
string('\xf8') // "\u00f8" == "ø" == "\xc3\xb8" |
| 5667 |
string(-1) // "\ufffd" == "\xef\xbf\xbd" |
| 5668 |
|
| 5669 |
type myString string |
| 5670 |
myString('\u65e5') // "\u65e5" == "日" == "\xe6\x97\xa5" |
| 5671 |
</pre> |
| 5672 |
|
| 5673 |
Note: This form of conversion may eventually be removed from the language. |
| 5674 |
The <a href="/pkg/cmd/vet"><code>go vet</code></a> tool flags certain |
| 5675 |
integer-to-string conversions as potential errors. |
| 5676 |
Library functions such as |
| 5677 |
<a href="/pkg/unicode/utf8#AppendRune"><code>utf8.AppendRune</code></a> or |
| 5678 |
<a href="/pkg/unicode/utf8#EncodeRune"><code>utf8.EncodeRune</code></a> |
| 5679 |
should be used instead. |
| 5680 |
</li> |
| 5681 |
</ol> |
| 5682 |
|
| 5683 |
<h4 id="Conversions_from_slice_to_array_or_array_pointer">Conversions from slice to array or array pointer</h4> |
| 5684 |
|
| 5685 |
<p> |
| 5686 |
Converting a slice to an array yields an array containing the elements of the underlying array of the slice. |
| 5687 |
Similarly, converting a slice to an array pointer yields a pointer to the underlying array of the slice. |
| 5688 |
In both cases, if the <a href="#Length_and_capacity">length</a> of the slice is less than the length of the array, |
| 5689 |
a <a href="#Run_time_panics">run-time panic</a> occurs. |
| 5690 |
</p> |
| 5691 |
|
| 5692 |
<pre> |
| 5693 |
s := make([]byte, 2, 4) |
| 5694 |
|
| 5695 |
a0 := [0]byte(s) |
| 5696 |
a1 := [1]byte(s[1:]) // a1[0] == s[1] |
| 5697 |
a2 := [2]byte(s) // a2[0] == s[0] |
| 5698 |
a4 := [4]byte(s) // panics: len([4]byte) > len(s) |
| 5699 |
|
| 5700 |
s0 := (*[0]byte)(s) // s0 != nil |
| 5701 |
s1 := (*[1]byte)(s[1:]) // &s1[0] == &s[1] |
| 5702 |
s2 := (*[2]byte)(s) // &s2[0] == &s[0] |
| 5703 |
s4 := (*[4]byte)(s) // panics: len([4]byte) > len(s) |
| 5704 |
|
| 5705 |
var t []string |
| 5706 |
t0 := [0]string(t) // ok for nil slice t |
| 5707 |
t1 := (*[0]string)(t) // t1 == nil |
| 5708 |
t2 := (*[1]string)(t) // panics: len([1]string) > len(t) |
| 5709 |
|
| 5710 |
u := make([]byte, 0) |
| 5711 |
u0 := (*[0]byte)(u) // u0 != nil |
| 5712 |
</pre> |
| 5713 |
|
| 5714 |
<h3 id="Constant_expressions">Constant expressions</h3> |
| 5715 |
|
| 5716 |
<p> |
| 5717 |
Constant expressions may contain only <a href="#Constants">constant</a> |
| 5718 |
operands and are evaluated at compile time. |
| 5719 |
</p> |
| 5720 |
|
| 5721 |
<p> |
| 5722 |
Untyped boolean, numeric, and string constants may be used as operands |
| 5723 |
wherever it is legal to use an operand of boolean, numeric, or string type, |
| 5724 |
respectively. |
| 5725 |
</p> |
| 5726 |
|
| 5727 |
<p> |
| 5728 |
A constant <a href="#Comparison_operators">comparison</a> always yields |
| 5729 |
an untyped boolean constant. If the left operand of a constant |
| 5730 |
<a href="#Operators">shift expression</a> is an untyped constant, the |
| 5731 |
result is an integer constant; otherwise it is a constant of the same |
| 5732 |
type as the left operand, which must be of |
| 5733 |
<a href="#Numeric_types">integer type</a>. |
| 5734 |
</p> |
| 5735 |
|
| 5736 |
<p> |
| 5737 |
Any other operation on untyped constants results in an untyped constant of the |
| 5738 |
same kind; that is, a boolean, integer, floating-point, complex, or string |
| 5739 |
constant. |
| 5740 |
If the untyped operands of a binary operation (other than a shift) are of |
| 5741 |
different kinds, the result is of the operand's kind that appears later in this |
| 5742 |
list: integer, rune, floating-point, complex. |
| 5743 |
For example, an untyped integer constant divided by an |
| 5744 |
untyped complex constant yields an untyped complex constant. |
| 5745 |
</p> |
| 5746 |
|
| 5747 |
<pre> |
| 5748 |
const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant) |
| 5749 |
const b = 15 / 4 // b == 3 (untyped integer constant) |
| 5750 |
const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant) |
| 5751 |
const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division) |
| 5752 |
const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division) |
| 5753 |
const d = 1 << 3.0 // d == 8 (untyped integer constant) |
| 5754 |
const e = 1.0 << 3 // e == 8 (untyped integer constant) |
| 5755 |
const f = int32(1) << 33 // illegal (constant 8589934592 overflows int32) |
| 5756 |
const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant) |
| 5757 |
const h = "foo" > "bar" // h == true (untyped boolean constant) |
| 5758 |
const j = true // j == true (untyped boolean constant) |
| 5759 |
const k = 'w' + 1 // k == 'x' (untyped rune constant) |
| 5760 |
const l = "hi" // l == "hi" (untyped string constant) |
| 5761 |
const m = string(k) // m == "x" (type string) |
| 5762 |
const Σ = 1 - 0.707i // (untyped complex constant) |
| 5763 |
const Δ = Σ + 2.0e-4 // (untyped complex constant) |
| 5764 |
const Φ = iota*1i - 1/1i // (untyped complex constant) |
| 5765 |
</pre> |
| 5766 |
|
| 5767 |
<p> |
| 5768 |
Applying the built-in function <code>complex</code> to untyped |
| 5769 |
integer, rune, or floating-point constants yields |
| 5770 |
an untyped complex constant. |
| 5771 |
</p> |
| 5772 |
|
| 5773 |
<pre> |
| 5774 |
const ic = complex(0, c) // ic == 3.75i (untyped complex constant) |
| 5775 |
const iΘ = complex(0, Θ) // iΘ == 1i (type complex128) |
| 5776 |
</pre> |
| 5777 |
|
| 5778 |
<p> |
| 5779 |
Constant expressions are always evaluated exactly; intermediate values and the |
| 5780 |
constants themselves may require precision significantly larger than supported |
| 5781 |
by any predeclared type in the language. The following are legal declarations: |
| 5782 |
</p> |
| 5783 |
|
| 5784 |
<pre> |
| 5785 |
const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (untyped integer constant) |
| 5786 |
const Four int8 = Huge >> 98 // Four == 4 (type int8) |
| 5787 |
</pre> |
| 5788 |
|
| 5789 |
<p> |
| 5790 |
The divisor of a constant division or remainder operation must not be zero: |
| 5791 |
</p> |
| 5792 |
|
| 5793 |
<pre> |
| 5794 |
3.14 / 0.0 // illegal: division by zero |
| 5795 |
</pre> |
| 5796 |
|
| 5797 |
<p> |
| 5798 |
The values of <i>typed</i> constants must always be accurately |
| 5799 |
<a href="#Representability">representable</a> by values |
| 5800 |
of the constant type. The following constant expressions are illegal: |
| 5801 |
</p> |
| 5802 |
|
| 5803 |
<pre> |
| 5804 |
uint(-1) // -1 cannot be represented as a uint |
| 5805 |
int(3.14) // 3.14 cannot be represented as an int |
| 5806 |
int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64 |
| 5807 |
Four * 300 // operand 300 cannot be represented as an int8 (type of Four) |
| 5808 |
Four * 100 // product 400 cannot be represented as an int8 (type of Four) |
| 5809 |
</pre> |
| 5810 |
|
| 5811 |
<p> |
| 5812 |
The mask used by the unary bitwise complement operator <code>^</code> matches |
| 5813 |
the rule for non-constants: the mask is all 1s for unsigned constants |
| 5814 |
and -1 for signed and untyped constants. |
| 5815 |
</p> |
| 5816 |
|
| 5817 |
<pre> |
| 5818 |
^1 // untyped integer constant, equal to -2 |
| 5819 |
uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8 |
| 5820 |
^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE) |
| 5821 |
int8(^1) // same as int8(-2) |
| 5822 |
^int8(1) // same as -1 ^ int8(1) = -2 |
| 5823 |
</pre> |
| 5824 |
|
| 5825 |
<p> |
| 5826 |
Implementation restriction: A compiler may use rounding while |
| 5827 |
computing untyped floating-point or complex constant expressions; see |
| 5828 |
the implementation restriction in the section |
| 5829 |
on <a href="#Constants">constants</a>. This rounding may cause a |
| 5830 |
floating-point constant expression to be invalid in an integer |
| 5831 |
context, even if it would be integral when calculated using infinite |
| 5832 |
precision, and vice versa. |
| 5833 |
</p> |
| 5834 |
|
| 5835 |
|
| 5836 |
<h3 id="Order_of_evaluation">Order of evaluation</h3> |
| 5837 |
|
| 5838 |
<p> |
| 5839 |
At package level, <a href="#Package_initialization">initialization dependencies</a> |
| 5840 |
determine the evaluation order of individual initialization expressions in |
| 5841 |
<a href="#Variable_declarations">variable declarations</a>. |
| 5842 |
Otherwise, when evaluating the <a href="#Operands">operands</a> of an |
| 5843 |
expression, assignment, or |
| 5844 |
<a href="#Return_statements">return statement</a>, |
| 5845 |
all function calls, method calls, |
| 5846 |
<a href="#Receive_operator">receive operations</a>, |
| 5847 |
and <a href="#Logical_operators">binary logical operations</a> |
| 5848 |
are evaluated in lexical left-to-right order. |
| 5849 |
</p> |
| 5850 |
|
| 5851 |
<p> |
| 5852 |
For example, in the (function-local) assignment |
| 5853 |
</p> |
| 5854 |
<pre> |
| 5855 |
y[f()], ok = g(z || h(), i()+x[j()], <-c), k() |
| 5856 |
</pre> |
| 5857 |
<p> |
| 5858 |
the function calls and communication happen in the order |
| 5859 |
<code>f()</code>, <code>h()</code> (if <code>z</code> |
| 5860 |
evaluates to false), <code>i()</code>, <code>j()</code>, |
| 5861 |
<code><-c</code>, <code>g()</code>, and <code>k()</code>. |
| 5862 |
However, the order of those events compared to the evaluation |
| 5863 |
and indexing of <code>x</code> and the evaluation |
| 5864 |
of <code>y</code> and <code>z</code> is not specified, |
| 5865 |
except as required lexically. For instance, <code>g</code> |
| 5866 |
cannot be called before its arguments are evaluated. |
| 5867 |
</p> |
| 5868 |
|
| 5869 |
<pre> |
| 5870 |
a := 1 |
| 5871 |
f := func() int { a++; return a } |
| 5872 |
x := []int{a, f()} // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified |
| 5873 |
m := map[int]int{a: 1, a: 2} // m may be {2: 1} or {2: 2}: evaluation order between the two map assignments is not specified |
| 5874 |
n := map[int]int{a: f()} // n may be {2: 3} or {3: 3}: evaluation order between the key and the value is not specified |
| 5875 |
</pre> |
| 5876 |
|
| 5877 |
<p> |
| 5878 |
At package level, initialization dependencies override the left-to-right rule |
| 5879 |
for individual initialization expressions, but not for operands within each |
| 5880 |
expression: |
| 5881 |
</p> |
| 5882 |
|
| 5883 |
<pre> |
| 5884 |
var a, b, c = f() + v(), g(), sqr(u()) + v() |
| 5885 |
|
| 5886 |
func f() int { return c } |
| 5887 |
func g() int { return a } |
| 5888 |
func sqr(x int) int { return x*x } |
| 5889 |
|
| 5890 |
// functions u and v are independent of all other variables and functions |
| 5891 |
</pre> |
| 5892 |
|
| 5893 |
<p> |
| 5894 |
The function calls happen in the order |
| 5895 |
<code>u()</code>, <code>sqr()</code>, <code>v()</code>, |
| 5896 |
<code>f()</code>, <code>v()</code>, and <code>g()</code>. |
| 5897 |
</p> |
| 5898 |
|
| 5899 |
<p> |
| 5900 |
Floating-point operations within a single expression are evaluated according to |
| 5901 |
the associativity of the operators. Explicit parentheses affect the evaluation |
| 5902 |
by overriding the default associativity. |
| 5903 |
In the expression <code>x + (y + z)</code> the addition <code>y + z</code> |
| 5904 |
is performed before adding <code>x</code>. |
| 5905 |
</p> |
| 5906 |
|
| 5907 |
<h2 id="Statements">Statements</h2> |
| 5908 |
|
| 5909 |
<p> |
| 5910 |
Statements control execution. |
| 5911 |
</p> |
| 5912 |
|
| 5913 |
<pre class="ebnf"> |
| 5914 |
Statement = Declaration | LabeledStmt | SimpleStmt | |
| 5915 |
GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt | |
| 5916 |
FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt | |
| 5917 |
DeferStmt . |
| 5918 |
|
| 5919 |
SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl . |
| 5920 |
</pre> |
| 5921 |
|
| 5922 |
<h3 id="Terminating_statements">Terminating statements</h3> |
| 5923 |
|
| 5924 |
<p> |
| 5925 |
A <i>terminating statement</i> interrupts the regular flow of control in |
| 5926 |
a <a href="#Blocks">block</a>. The following statements are terminating: |
| 5927 |
</p> |
| 5928 |
|
| 5929 |
<ol> |
| 5930 |
<li> |
| 5931 |
A <a href="#Return_statements">"return"</a> or |
| 5932 |
<a href="#Goto_statements">"goto"</a> statement. |
| 5933 |
<!-- ul below only for regular layout --> |
| 5934 |
<ul> </ul> |
| 5935 |
</li> |
| 5936 |
|
| 5937 |
<li> |
| 5938 |
A call to the built-in function |
| 5939 |
<a href="#Handling_panics"><code>panic</code></a>. |
| 5940 |
<!-- ul below only for regular layout --> |
| 5941 |
<ul> </ul> |
| 5942 |
</li> |
| 5943 |
|
| 5944 |
<li> |
| 5945 |
A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement. |
| 5946 |
<!-- ul below only for regular layout --> |
| 5947 |
<ul> </ul> |
| 5948 |
</li> |
| 5949 |
|
| 5950 |
<li> |
| 5951 |
An <a href="#If_statements">"if" statement</a> in which: |
| 5952 |
<ul> |
| 5953 |
<li>the "else" branch is present, and</li> |
| 5954 |
<li>both branches are terminating statements.</li> |
| 5955 |
</ul> |
| 5956 |
</li> |
| 5957 |
|
| 5958 |
<li> |
| 5959 |
A <a href="#For_statements">"for" statement</a> in which: |
| 5960 |
<ul> |
| 5961 |
<li>there are no "break" statements referring to the "for" statement, and</li> |
| 5962 |
<li>the loop condition is absent, and</li> |
| 5963 |
<li>the "for" statement does not use a range clause.</li> |
| 5964 |
</ul> |
| 5965 |
</li> |
| 5966 |
|
| 5967 |
<li> |
| 5968 |
A <a href="#Switch_statements">"switch" statement</a> in which: |
| 5969 |
<ul> |
| 5970 |
<li>there are no "break" statements referring to the "switch" statement,</li> |
| 5971 |
<li>there is a default case, and</li> |
| 5972 |
<li>the statement lists in each case, including the default, end in a terminating |
| 5973 |
statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough" |
| 5974 |
statement</a>.</li> |
| 5975 |
</ul> |
| 5976 |
</li> |
| 5977 |
|
| 5978 |
<li> |
| 5979 |
A <a href="#Select_statements">"select" statement</a> in which: |
| 5980 |
<ul> |
| 5981 |
<li>there are no "break" statements referring to the "select" statement, and</li> |
| 5982 |
<li>the statement lists in each case, including the default if present, |
| 5983 |
end in a terminating statement.</li> |
| 5984 |
</ul> |
| 5985 |
</li> |
| 5986 |
|
| 5987 |
<li> |
| 5988 |
A <a href="#Labeled_statements">labeled statement</a> labeling |
| 5989 |
a terminating statement. |
| 5990 |
</li> |
| 5991 |
</ol> |
| 5992 |
|
| 5993 |
<p> |
| 5994 |
All other statements are not terminating. |
| 5995 |
</p> |
| 5996 |
|
| 5997 |
<p> |
| 5998 |
A <a href="#Blocks">statement list</a> ends in a terminating statement if the list |
| 5999 |
is not empty and its final non-empty statement is terminating. |
| 6000 |
</p> |
| 6001 |
|
| 6002 |
|
| 6003 |
<h3 id="Empty_statements">Empty statements</h3> |
| 6004 |
|
| 6005 |
<p> |
| 6006 |
The empty statement does nothing. |
| 6007 |
</p> |
| 6008 |
|
| 6009 |
<pre class="ebnf"> |
| 6010 |
EmptyStmt = . |
| 6011 |
</pre> |
| 6012 |
|
| 6013 |
|
| 6014 |
<h3 id="Labeled_statements">Labeled statements</h3> |
| 6015 |
|
| 6016 |
<p> |
| 6017 |
A labeled statement may be the target of a <code>goto</code>, |
| 6018 |
<code>break</code> or <code>continue</code> statement. |
| 6019 |
</p> |
| 6020 |
|
| 6021 |
<pre class="ebnf"> |
| 6022 |
LabeledStmt = Label ":" Statement . |
| 6023 |
Label = identifier . |
| 6024 |
</pre> |
| 6025 |
|
| 6026 |
<pre> |
| 6027 |
Error: log.Panic("error encountered") |
| 6028 |
</pre> |
| 6029 |
|
| 6030 |
|
| 6031 |
<h3 id="Expression_statements">Expression statements</h3> |
| 6032 |
|
| 6033 |
<p> |
| 6034 |
With the exception of specific built-in functions, |
| 6035 |
function and method <a href="#Calls">calls</a> and |
| 6036 |
<a href="#Receive_operator">receive operations</a> |
| 6037 |
can appear in statement context. Such statements may be parenthesized. |
| 6038 |
</p> |
| 6039 |
|
| 6040 |
<pre class="ebnf"> |
| 6041 |
ExpressionStmt = Expression . |
| 6042 |
</pre> |
| 6043 |
|
| 6044 |
<p> |
| 6045 |
The following built-in functions are not permitted in statement context: |
| 6046 |
</p> |
| 6047 |
|
| 6048 |
<pre> |
| 6049 |
append cap complex imag len make new real |
| 6050 |
unsafe.Add unsafe.Alignof unsafe.Offsetof unsafe.Sizeof unsafe.Slice unsafe.SliceData unsafe.String unsafe.StringData |
| 6051 |
</pre> |
| 6052 |
|
| 6053 |
<pre> |
| 6054 |
h(x+y) |
| 6055 |
f.Close() |
| 6056 |
<-ch |
| 6057 |
(<-ch) |
| 6058 |
len("foo") // illegal if len is the built-in function |
| 6059 |
</pre> |
| 6060 |
|
| 6061 |
|
| 6062 |
<h3 id="Send_statements">Send statements</h3> |
| 6063 |
|
| 6064 |
<p> |
| 6065 |
A send statement sends a value on a channel. |
| 6066 |
The channel expression must be of <a href="#Channel_types">channel type</a>, |
| 6067 |
the channel direction must permit send operations, |
| 6068 |
and the type of the value to be sent must be <a href="#Assignability">assignable</a> |
| 6069 |
to the channel's element type. |
| 6070 |
</p> |
| 6071 |
|
| 6072 |
<pre class="ebnf"> |
| 6073 |
SendStmt = Channel "<-" Expression . |
| 6074 |
Channel = Expression . |
| 6075 |
</pre> |
| 6076 |
|
| 6077 |
<p> |
| 6078 |
Both the channel and the value expression are evaluated before communication |
| 6079 |
begins. Communication blocks until the send can proceed. |
| 6080 |
A send on an unbuffered channel can proceed if a receiver is ready. |
| 6081 |
A send on a buffered channel can proceed if there is room in the buffer. |
| 6082 |
A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>. |
| 6083 |
A send on a <code>nil</code> channel blocks forever. |
| 6084 |
</p> |
| 6085 |
|
| 6086 |
<pre> |
| 6087 |
ch <- 3 // send value 3 to channel ch |
| 6088 |
</pre> |
| 6089 |
|
| 6090 |
<p> |
| 6091 |
If the type of the channel expression is a |
| 6092 |
<a href="#Type_parameter_declarations">type parameter</a>, |
| 6093 |
all types in its type set must be channel types that permit send operations, |
| 6094 |
they must all have the same element type, |
| 6095 |
and the type of the value to be sent must be assignable to that element type. |
| 6096 |
</p> |
| 6097 |
|
| 6098 |
<h3 id="IncDec_statements">IncDec statements</h3> |
| 6099 |
|
| 6100 |
<p> |
| 6101 |
The "++" and "--" statements increment or decrement their operands |
| 6102 |
by the untyped <a href="#Constants">constant</a> <code>1</code>. |
| 6103 |
As with an assignment, the operand must be <a href="#Address_operators">addressable</a> |
| 6104 |
or a map index expression. |
| 6105 |
</p> |
| 6106 |
|
| 6107 |
<pre class="ebnf"> |
| 6108 |
IncDecStmt = Expression ( "++" | "--" ) . |
| 6109 |
</pre> |
| 6110 |
|
| 6111 |
<p> |
| 6112 |
The following <a href="#Assignment_statements">assignment statements</a> are semantically |
| 6113 |
equivalent: |
| 6114 |
</p> |
| 6115 |
|
| 6116 |
<pre class="grammar"> |
| 6117 |
IncDec statement Assignment |
| 6118 |
x++ x += 1 |
| 6119 |
x-- x -= 1 |
| 6120 |
</pre> |
| 6121 |
|
| 6122 |
|
| 6123 |
<h3 id="Assignment_statements">Assignment statements</h3> |
| 6124 |
|
| 6125 |
<p> |
| 6126 |
An <i>assignment</i> replaces the current value stored in a <a href="#Variables">variable</a> |
| 6127 |
with a new value specified by an <a href="#Expressions">expression</a>. |
| 6128 |
An assignment statement may assign a single value to a single variable, or multiple values to a |
| 6129 |
matching number of variables. |
| 6130 |
</p> |
| 6131 |
|
| 6132 |
<pre class="ebnf"> |
| 6133 |
Assignment = ExpressionList assign_op ExpressionList . |
| 6134 |
|
| 6135 |
assign_op = [ add_op | mul_op ] "=" . |
| 6136 |
</pre> |
| 6137 |
|
| 6138 |
<p> |
| 6139 |
Each left-hand side operand must be <a href="#Address_operators">addressable</a>, |
| 6140 |
a map index expression, or (for <code>=</code> assignments only) the |
| 6141 |
<a href="#Blank_identifier">blank identifier</a>. |
| 6142 |
Operands may be parenthesized. |
| 6143 |
</p> |
| 6144 |
|
| 6145 |
<pre> |
| 6146 |
x = 1 |
| 6147 |
*p = f() |
| 6148 |
a[i] = 23 |
| 6149 |
(k) = <-ch // same as: k = <-ch |
| 6150 |
</pre> |
| 6151 |
|
| 6152 |
<p> |
| 6153 |
An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code> |
| 6154 |
<code>y</code> where <i>op</i> is a binary <a href="#Arithmetic_operators">arithmetic operator</a> |
| 6155 |
is equivalent to <code>x</code> <code>=</code> <code>x</code> <i>op</i> |
| 6156 |
<code>(y)</code> but evaluates <code>x</code> |
| 6157 |
only once. The <i>op</i><code>=</code> construct is a single token. |
| 6158 |
In assignment operations, both the left- and right-hand expression lists |
| 6159 |
must contain exactly one single-valued expression, and the left-hand |
| 6160 |
expression must not be the blank identifier. |
| 6161 |
</p> |
| 6162 |
|
| 6163 |
<pre> |
| 6164 |
a[i] <<= 2 |
| 6165 |
i &^= 1<<n |
| 6166 |
</pre> |
| 6167 |
|
| 6168 |
<p> |
| 6169 |
A tuple assignment assigns the individual elements of a multi-valued |
| 6170 |
operation to a list of variables. There are two forms. In the |
| 6171 |
first, the right hand operand is a single multi-valued expression |
| 6172 |
such as a function call, a <a href="#Channel_types">channel</a> or |
| 6173 |
<a href="#Map_types">map</a> operation, or a <a href="#Type_assertions">type assertion</a>. |
| 6174 |
The number of operands on the left |
| 6175 |
hand side must match the number of values. For instance, if |
| 6176 |
<code>f</code> is a function returning two values, |
| 6177 |
</p> |
| 6178 |
|
| 6179 |
<pre> |
| 6180 |
x, y = f() |
| 6181 |
</pre> |
| 6182 |
|
| 6183 |
<p> |
| 6184 |
assigns the first value to <code>x</code> and the second to <code>y</code>. |
| 6185 |
In the second form, the number of operands on the left must equal the number |
| 6186 |
of expressions on the right, each of which must be single-valued, and the |
| 6187 |
<i>n</i>th expression on the right is assigned to the <i>n</i>th |
| 6188 |
operand on the left: |
| 6189 |
</p> |
| 6190 |
|
| 6191 |
<pre> |
| 6192 |
one, two, three = '一', '二', '三' |
| 6193 |
</pre> |
| 6194 |
|
| 6195 |
<p> |
| 6196 |
The <a href="#Blank_identifier">blank identifier</a> provides a way to |
| 6197 |
ignore right-hand side values in an assignment: |
| 6198 |
</p> |
| 6199 |
|
| 6200 |
<pre> |
| 6201 |
_ = x // evaluate x but ignore it |
| 6202 |
x, _ = f() // evaluate f() but ignore second result value |
| 6203 |
</pre> |
| 6204 |
|
| 6205 |
<p> |
| 6206 |
The assignment proceeds in two phases. |
| 6207 |
First, the operands of <a href="#Index_expressions">index expressions</a> |
| 6208 |
and <a href="#Address_operators">pointer indirections</a> |
| 6209 |
(including implicit pointer indirections in <a href="#Selectors">selectors</a>) |
| 6210 |
on the left and the expressions on the right are all |
| 6211 |
<a href="#Order_of_evaluation">evaluated in the usual order</a>. |
| 6212 |
Second, the assignments are carried out in left-to-right order. |
| 6213 |
</p> |
| 6214 |
|
| 6215 |
<pre> |
| 6216 |
a, b = b, a // exchange a and b |
| 6217 |
|
| 6218 |
x := []int{1, 2, 3} |
| 6219 |
i := 0 |
| 6220 |
i, x[i] = 1, 2 // set i = 1, x[0] = 2 |
| 6221 |
|
| 6222 |
i = 0 |
| 6223 |
x[i], i = 2, 1 // set x[0] = 2, i = 1 |
| 6224 |
|
| 6225 |
x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end) |
| 6226 |
|
| 6227 |
x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5. |
| 6228 |
|
| 6229 |
type Point struct { x, y int } |
| 6230 |
var p *Point |
| 6231 |
x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7 |
| 6232 |
|
| 6233 |
i = 2 |
| 6234 |
x = []int{3, 5, 7} |
| 6235 |
for i, x[i] = range x { // set i, x[2] = 0, x[0] |
| 6236 |
break |
| 6237 |
} |
| 6238 |
// after this loop, i == 0 and x is []int{3, 5, 3} |
| 6239 |
</pre> |
| 6240 |
|
| 6241 |
<p> |
| 6242 |
In assignments, each value must be <a href="#Assignability">assignable</a> |
| 6243 |
to the type of the operand to which it is assigned, with the following special cases: |
| 6244 |
</p> |
| 6245 |
|
| 6246 |
<ol> |
| 6247 |
<li> |
| 6248 |
Any typed value may be assigned to the blank identifier. |
| 6249 |
</li> |
| 6250 |
|
| 6251 |
<li> |
| 6252 |
If an untyped constant |
| 6253 |
is assigned to a variable of interface type or the blank identifier, |
| 6254 |
the constant is first implicitly <a href="#Conversions">converted</a> to its |
| 6255 |
<a href="#Constants">default type</a>. |
| 6256 |
</li> |
| 6257 |
|
| 6258 |
<li> |
| 6259 |
If an untyped boolean value is assigned to a variable of interface type or |
| 6260 |
the blank identifier, it is first implicitly converted to type <code>bool</code>. |
| 6261 |
</li> |
| 6262 |
</ol> |
| 6263 |
|
| 6264 |
<p> |
| 6265 |
When a value is assigned to a variable, only the data that is stored in the variable |
| 6266 |
is replaced. If the value contains a <a href="#Representation_of_values">reference</a>, |
| 6267 |
the assignment copies the reference but does not make a copy of the referenced data |
| 6268 |
(such as the underlying array of a slice). |
| 6269 |
</p> |
| 6270 |
|
| 6271 |
<pre> |
| 6272 |
var s1 = []int{1, 2, 3} |
| 6273 |
var s2 = s1 // s2 stores the slice descriptor of s1 |
| 6274 |
s1 = s1[:1] // s1's length is 1 but it still shares its underlying array with s2 |
| 6275 |
s2[0] = 42 // setting s2[0] changes s1[0] as well |
| 6276 |
fmt.Println(s1, s2) // prints [42] [42 2 3] |
| 6277 |
|
| 6278 |
var m1 = make(map[string]int) |
| 6279 |
var m2 = m1 // m2 stores the map descriptor of m1 |
| 6280 |
m1["foo"] = 42 // setting m1["foo"] changes m2["foo"] as well |
| 6281 |
fmt.Println(m2["foo"]) // prints 42 |
| 6282 |
</pre> |
| 6283 |
|
| 6284 |
<h3 id="If_statements">If statements</h3> |
| 6285 |
|
| 6286 |
<p> |
| 6287 |
"If" statements specify the conditional execution of two branches |
| 6288 |
according to the value of a boolean expression. If the expression |
| 6289 |
evaluates to true, the "if" branch is executed, otherwise, if |
| 6290 |
present, the "else" branch is executed. |
| 6291 |
</p> |
| 6292 |
|
| 6293 |
<pre class="ebnf"> |
| 6294 |
IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] . |
| 6295 |
</pre> |
| 6296 |
|
| 6297 |
<pre> |
| 6298 |
if x > max { |
| 6299 |
x = max |
| 6300 |
} |
| 6301 |
</pre> |
| 6302 |
|
| 6303 |
<p> |
| 6304 |
The expression may be preceded by a simple statement, which |
| 6305 |
executes before the expression is evaluated. |
| 6306 |
</p> |
| 6307 |
|
| 6308 |
<pre> |
| 6309 |
if x := f(); x < y { |
| 6310 |
return x |
| 6311 |
} else if x > z { |
| 6312 |
return z |
| 6313 |
} else { |
| 6314 |
return y |
| 6315 |
} |
| 6316 |
</pre> |
| 6317 |
|
| 6318 |
|
| 6319 |
<h3 id="Switch_statements">Switch statements</h3> |
| 6320 |
|
| 6321 |
<p> |
| 6322 |
"Switch" statements provide multi-way execution. |
| 6323 |
An expression or type is compared to the "cases" |
| 6324 |
inside the "switch" to determine which branch |
| 6325 |
to execute. |
| 6326 |
</p> |
| 6327 |
|
| 6328 |
<pre class="ebnf"> |
| 6329 |
SwitchStmt = ExprSwitchStmt | TypeSwitchStmt . |
| 6330 |
</pre> |
| 6331 |
|
| 6332 |
<p> |
| 6333 |
There are two forms: expression switches and type switches. |
| 6334 |
In an expression switch, the cases contain expressions that are compared |
| 6335 |
against the value of the switch expression. |
| 6336 |
In a type switch, the cases contain types that are compared against the |
| 6337 |
type of a specially annotated switch expression. |
| 6338 |
The switch expression is evaluated exactly once in a switch statement. |
| 6339 |
</p> |
| 6340 |
|
| 6341 |
<h4 id="Expression_switches">Expression switches</h4> |
| 6342 |
|
| 6343 |
<p> |
| 6344 |
In an expression switch, |
| 6345 |
the switch expression is evaluated and |
| 6346 |
the case expressions, which need not be constants, |
| 6347 |
are evaluated left-to-right and top-to-bottom; the first one that equals the |
| 6348 |
switch expression |
| 6349 |
triggers execution of the statements of the associated case; |
| 6350 |
the other cases are skipped. |
| 6351 |
If no case matches and there is a "default" case, |
| 6352 |
its statements are executed. |
| 6353 |
There can be at most one default case and it may appear anywhere in the |
| 6354 |
"switch" statement. |
| 6355 |
A missing switch expression is equivalent to the boolean value |
| 6356 |
<code>true</code>. |
| 6357 |
</p> |
| 6358 |
|
| 6359 |
<pre class="ebnf"> |
| 6360 |
ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" . |
| 6361 |
ExprCaseClause = ExprSwitchCase ":" StatementList . |
| 6362 |
ExprSwitchCase = "case" ExpressionList | "default" . |
| 6363 |
</pre> |
| 6364 |
|
| 6365 |
<p> |
| 6366 |
If the switch expression evaluates to an untyped constant, it is first implicitly |
| 6367 |
<a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>. |
| 6368 |
The predeclared untyped value <code>nil</code> cannot be used as a switch expression. |
| 6369 |
The switch expression type must be <a href="#Comparison_operators">comparable</a>. |
| 6370 |
</p> |
| 6371 |
|
| 6372 |
<p> |
| 6373 |
If a case expression is untyped, it is first implicitly <a href="#Conversions">converted</a> |
| 6374 |
to the type of the switch expression. |
| 6375 |
For each (possibly converted) case expression <code>x</code> and the value <code>t</code> |
| 6376 |
of the switch expression, <code>x == t</code> must be a valid <a href="#Comparison_operators">comparison</a>. |
| 6377 |
</p> |
| 6378 |
|
| 6379 |
<p> |
| 6380 |
In other words, the switch expression is treated as if it were used to declare and |
| 6381 |
initialize a temporary variable <code>t</code> without explicit type; it is that |
| 6382 |
value of <code>t</code> against which each case expression <code>x</code> is tested |
| 6383 |
for equality. |
| 6384 |
</p> |
| 6385 |
|
| 6386 |
<p> |
| 6387 |
In a case or default clause, the last non-empty statement |
| 6388 |
may be a (possibly <a href="#Labeled_statements">labeled</a>) |
| 6389 |
<a href="#Fallthrough_statements">"fallthrough" statement</a> to |
| 6390 |
indicate that control should flow from the end of this clause to |
| 6391 |
the first statement of the next clause. |
| 6392 |
Otherwise control flows to the end of the "switch" statement. |
| 6393 |
A "fallthrough" statement may appear as the last statement of all |
| 6394 |
but the last clause of an expression switch. |
| 6395 |
</p> |
| 6396 |
|
| 6397 |
<p> |
| 6398 |
The switch expression may be preceded by a simple statement, which |
| 6399 |
executes before the expression is evaluated. |
| 6400 |
</p> |
| 6401 |
|
| 6402 |
<pre> |
| 6403 |
switch tag { |
| 6404 |
default: s3() |
| 6405 |
case 0, 1, 2, 3: s1() |
| 6406 |
case 4, 5, 6, 7: s2() |
| 6407 |
} |
| 6408 |
|
| 6409 |
switch x := f(); { // missing switch expression means "true" |
| 6410 |
case x < 0: return -x |
| 6411 |
default: return x |
| 6412 |
} |
| 6413 |
|
| 6414 |
switch { |
| 6415 |
case x < y: f1() |
| 6416 |
case x < z: f2() |
| 6417 |
case x == 4: f3() |
| 6418 |
} |
| 6419 |
</pre> |
| 6420 |
|
| 6421 |
<p> |
| 6422 |
Implementation restriction: A compiler may disallow multiple case |
| 6423 |
expressions evaluating to the same constant. |
| 6424 |
For instance, the current compilers disallow duplicate integer, |
| 6425 |
floating point, or string constants in case expressions. |
| 6426 |
</p> |
| 6427 |
|
| 6428 |
<h4 id="Type_switches">Type switches</h4> |
| 6429 |
|
| 6430 |
<p> |
| 6431 |
A type switch compares types rather than values. It is otherwise similar |
| 6432 |
to an expression switch. It is marked by a special switch expression that |
| 6433 |
has the form of a <a href="#Type_assertions">type assertion</a> |
| 6434 |
using the keyword <code>type</code> rather than an actual type: |
| 6435 |
</p> |
| 6436 |
|
| 6437 |
<pre> |
| 6438 |
switch x.(type) { |
| 6439 |
// cases |
| 6440 |
} |
| 6441 |
</pre> |
| 6442 |
|
| 6443 |
<p> |
| 6444 |
Cases then match actual types <code>T</code> against the dynamic type of the |
| 6445 |
expression <code>x</code>. As with type assertions, <code>x</code> must be of |
| 6446 |
<a href="#Interface_types">interface type</a>, but not a |
| 6447 |
<a href="#Type_parameter_declarations">type parameter</a>, and each non-interface type |
| 6448 |
<code>T</code> listed in a case must implement the type of <code>x</code>. |
| 6449 |
The types listed in the cases of a type switch must all be |
| 6450 |
<a href="#Type_identity">different</a>. |
| 6451 |
</p> |
| 6452 |
|
| 6453 |
<pre class="ebnf"> |
| 6454 |
TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" . |
| 6455 |
TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" . |
| 6456 |
TypeCaseClause = TypeSwitchCase ":" StatementList . |
| 6457 |
TypeSwitchCase = "case" TypeList | "default" . |
| 6458 |
</pre> |
| 6459 |
|
| 6460 |
<p> |
| 6461 |
The TypeSwitchGuard may include a |
| 6462 |
<a href="#Short_variable_declarations">short variable declaration</a>. |
| 6463 |
When that form is used, the variable is declared at the end of the |
| 6464 |
TypeSwitchCase in the <a href="#Blocks">implicit block</a> of each clause. |
| 6465 |
In clauses with a case listing exactly one type, the variable |
| 6466 |
has that type; otherwise, the variable has the type of the expression |
| 6467 |
in the TypeSwitchGuard. |
| 6468 |
</p> |
| 6469 |
|
| 6470 |
<p> |
| 6471 |
Instead of a type, a case may use the predeclared identifier |
| 6472 |
<a href="#Predeclared_identifiers"><code>nil</code></a>; |
| 6473 |
that case is selected when the expression in the TypeSwitchGuard |
| 6474 |
is a <code>nil</code> interface value. |
| 6475 |
There may be at most one <code>nil</code> case. |
| 6476 |
</p> |
| 6477 |
|
| 6478 |
<p> |
| 6479 |
Given an expression <code>x</code> of type <code>interface{}</code>, |
| 6480 |
the following type switch: |
| 6481 |
</p> |
| 6482 |
|
| 6483 |
<pre> |
| 6484 |
switch i := x.(type) { |
| 6485 |
case nil: |
| 6486 |
printString("x is nil") // type of i is type of x (interface{}) |
| 6487 |
case int: |
| 6488 |
printInt(i) // type of i is int |
| 6489 |
case float64: |
| 6490 |
printFloat64(i) // type of i is float64 |
| 6491 |
case func(int) float64: |
| 6492 |
printFunction(i) // type of i is func(int) float64 |
| 6493 |
case bool, string: |
| 6494 |
printString("type is bool or string") // type of i is type of x (interface{}) |
| 6495 |
default: |
| 6496 |
printString("don't know the type") // type of i is type of x (interface{}) |
| 6497 |
} |
| 6498 |
</pre> |
| 6499 |
|
| 6500 |
<p> |
| 6501 |
could be rewritten: |
| 6502 |
</p> |
| 6503 |
|
| 6504 |
<pre> |
| 6505 |
v := x // x is evaluated exactly once |
| 6506 |
if v == nil { |
| 6507 |
i := v // type of i is type of x (interface{}) |
| 6508 |
printString("x is nil") |
| 6509 |
} else if i, isInt := v.(int); isInt { |
| 6510 |
printInt(i) // type of i is int |
| 6511 |
} else if i, isFloat64 := v.(float64); isFloat64 { |
| 6512 |
printFloat64(i) // type of i is float64 |
| 6513 |
} else if i, isFunc := v.(func(int) float64); isFunc { |
| 6514 |
printFunction(i) // type of i is func(int) float64 |
| 6515 |
} else { |
| 6516 |
_, isBool := v.(bool) |
| 6517 |
_, isString := v.(string) |
| 6518 |
if isBool || isString { |
| 6519 |
i := v // type of i is type of x (interface{}) |
| 6520 |
printString("type is bool or string") |
| 6521 |
} else { |
| 6522 |
i := v // type of i is type of x (interface{}) |
| 6523 |
printString("don't know the type") |
| 6524 |
} |
| 6525 |
} |
| 6526 |
</pre> |
| 6527 |
|
| 6528 |
<p> |
| 6529 |
A <a href="#Type_parameter_declarations">type parameter</a> or a <a href="#Type_declarations">generic type</a> |
| 6530 |
may be used as a type in a case. If upon <a href="#Instantiations">instantiation</a> that type turns |
| 6531 |
out to duplicate another entry in the switch, the first matching case is chosen. |
| 6532 |
</p> |
| 6533 |
|
| 6534 |
<pre> |
| 6535 |
func f[P any](x any) int { |
| 6536 |
switch x.(type) { |
| 6537 |
case P: |
| 6538 |
return 0 |
| 6539 |
case string: |
| 6540 |
return 1 |
| 6541 |
case []P: |
| 6542 |
return 2 |
| 6543 |
case []byte: |
| 6544 |
return 3 |
| 6545 |
default: |
| 6546 |
return 4 |
| 6547 |
} |
| 6548 |
} |
| 6549 |
|
| 6550 |
var v1 = f[string]("foo") // v1 == 0 |
| 6551 |
var v2 = f[byte]([]byte{}) // v2 == 2 |
| 6552 |
</pre> |
| 6553 |
|
| 6554 |
<p> |
| 6555 |
The type switch guard may be preceded by a simple statement, which |
| 6556 |
executes before the guard is evaluated. |
| 6557 |
</p> |
| 6558 |
|
| 6559 |
<p> |
| 6560 |
The "fallthrough" statement is not permitted in a type switch. |
| 6561 |
</p> |
| 6562 |
|
| 6563 |
<h3 id="For_statements">For statements</h3> |
| 6564 |
|
| 6565 |
<p> |
| 6566 |
A "for" statement specifies repeated execution of a block. There are three forms: |
| 6567 |
The iteration may be controlled by a single condition, a "for" clause, or a "range" clause. |
| 6568 |
</p> |
| 6569 |
|
| 6570 |
<pre class="ebnf"> |
| 6571 |
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block . |
| 6572 |
Condition = Expression . |
| 6573 |
</pre> |
| 6574 |
|
| 6575 |
<h4 id="For_condition">For statements with single condition</h4> |
| 6576 |
|
| 6577 |
<p> |
| 6578 |
In its simplest form, a "for" statement specifies the repeated execution of |
| 6579 |
a block as long as a boolean condition evaluates to true. |
| 6580 |
The condition is evaluated before each iteration. |
| 6581 |
If the condition is absent, it is equivalent to the boolean value |
| 6582 |
<code>true</code>. |
| 6583 |
</p> |
| 6584 |
|
| 6585 |
<pre> |
| 6586 |
for a < b { |
| 6587 |
a *= 2 |
| 6588 |
} |
| 6589 |
</pre> |
| 6590 |
|
| 6591 |
<h4 id="For_clause">For statements with <code>for</code> clause</h4> |
| 6592 |
|
| 6593 |
<p> |
| 6594 |
A "for" statement with a ForClause is also controlled by its condition, but |
| 6595 |
additionally it may specify an <i>init</i> |
| 6596 |
and a <i>post</i> statement, such as an assignment, |
| 6597 |
an increment or decrement statement. The init statement may be a |
| 6598 |
<a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not. |
| 6599 |
</p> |
| 6600 |
|
| 6601 |
<pre class="ebnf"> |
| 6602 |
ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] . |
| 6603 |
InitStmt = SimpleStmt . |
| 6604 |
PostStmt = SimpleStmt . |
| 6605 |
</pre> |
| 6606 |
|
| 6607 |
<pre> |
| 6608 |
for i := 0; i < 10; i++ { |
| 6609 |
f(i) |
| 6610 |
} |
| 6611 |
</pre> |
| 6612 |
|
| 6613 |
<p> |
| 6614 |
If non-empty, the init statement is executed once before evaluating the |
| 6615 |
condition for the first iteration; |
| 6616 |
the post statement is executed after each execution of the block (and |
| 6617 |
only if the block was executed). |
| 6618 |
Any element of the ForClause may be empty but the |
| 6619 |
<a href="#Semicolons">semicolons</a> are |
| 6620 |
required unless there is only a condition. |
| 6621 |
If the condition is absent, it is equivalent to the boolean value |
| 6622 |
<code>true</code>. |
| 6623 |
</p> |
| 6624 |
|
| 6625 |
<pre> |
| 6626 |
for cond { S() } is the same as for ; cond ; { S() } |
| 6627 |
for { S() } is the same as for true { S() } |
| 6628 |
</pre> |
| 6629 |
|
| 6630 |
<p> |
| 6631 |
Each iteration has its own separate declared variable (or variables) |
| 6632 |
[<a href="#Go_1.22">Go 1.22</a>]. |
| 6633 |
The variable used by the first iteration is declared by the init statement. |
| 6634 |
The variable used by each subsequent iteration is declared implicitly before |
| 6635 |
executing the post statement and initialized to the value of the previous |
| 6636 |
iteration's variable at that moment. |
| 6637 |
</p> |
| 6638 |
|
| 6639 |
<pre> |
| 6640 |
var prints []func() |
| 6641 |
for i := 0; i < 5; i++ { |
| 6642 |
prints = append(prints, func() { println(i) }) |
| 6643 |
i++ |
| 6644 |
} |
| 6645 |
for _, p := range prints { |
| 6646 |
p() |
| 6647 |
} |
| 6648 |
</pre> |
| 6649 |
|
| 6650 |
<p> |
| 6651 |
prints |
| 6652 |
</p> |
| 6653 |
|
| 6654 |
<pre> |
| 6655 |
1 |
| 6656 |
3 |
| 6657 |
5 |
| 6658 |
</pre> |
| 6659 |
|
| 6660 |
<p> |
| 6661 |
Prior to [<a href="#Go_1.22">Go 1.22</a>], iterations share one set of variables |
| 6662 |
instead of having their own separate variables. |
| 6663 |
In that case, the example above prints |
| 6664 |
</p> |
| 6665 |
|
| 6666 |
<pre> |
| 6667 |
6 |
| 6668 |
6 |
| 6669 |
6 |
| 6670 |
</pre> |
| 6671 |
|
| 6672 |
<h4 id="For_range">For statements with <code>range</code> clause</h4> |
| 6673 |
|
| 6674 |
<p> |
| 6675 |
A "for" statement with a "range" clause |
| 6676 |
iterates through all entries of an array, slice, string or map, values received on |
| 6677 |
a channel, integer values from zero to an upper limit [<a href="#Go_1.22">Go 1.22</a>], |
| 6678 |
or values passed to an iterator function's yield function [<a href="#Go_1.23">Go 1.23</a>]. |
| 6679 |
For each entry it assigns <i>iteration values</i> |
| 6680 |
to corresponding <i>iteration variables</i> if present and then executes the block. |
| 6681 |
</p> |
| 6682 |
|
| 6683 |
<pre class="ebnf"> |
| 6684 |
RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression . |
| 6685 |
</pre> |
| 6686 |
|
| 6687 |
<p> |
| 6688 |
The expression on the right in the "range" clause is called the <i>range expression</i>, |
| 6689 |
which may be an array, pointer to an array, slice, string, map, channel permitting |
| 6690 |
<a href="#Receive_operator">receive operations</a>, an integer, or |
| 6691 |
a function with specific signature (see below). |
| 6692 |
As with an assignment, if present the operands on the left must be |
| 6693 |
<a href="#Address_operators">addressable</a> or map index expressions; they |
| 6694 |
denote the iteration variables. |
| 6695 |
If the range expression is a function, the maximum number of iteration variables depends on |
| 6696 |
the function signature. |
| 6697 |
If the range expression is a channel or integer, at most one iteration variable is permitted; |
| 6698 |
otherwise there may be up to two. |
| 6699 |
If the last iteration variable is the <a href="#Blank_identifier">blank identifier</a>, |
| 6700 |
the range clause is equivalent to the same clause without that identifier. |
| 6701 |
</p> |
| 6702 |
|
| 6703 |
<p> |
| 6704 |
The range expression <code>x</code> is evaluated before beginning the loop, |
| 6705 |
with one exception: if at most one iteration variable is present and <code>x</code> or |
| 6706 |
<a href="#Length_and_capacity"><code>len(x)</code></a> is <a href="#Constants">constant</a>, |
| 6707 |
the range expression is not evaluated. |
| 6708 |
</p> |
| 6709 |
|
| 6710 |
<p> |
| 6711 |
Function calls on the left are evaluated once per iteration. |
| 6712 |
For each iteration, iteration values are produced as follows |
| 6713 |
if the respective iteration variables are present: |
| 6714 |
</p> |
| 6715 |
|
| 6716 |
<pre class="grammar"> |
| 6717 |
Range expression 1st value 2nd value |
| 6718 |
|
| 6719 |
array or slice a [n]E, *[n]E, or []E index i int a[i] E |
| 6720 |
string s string type index i int see below rune |
| 6721 |
map m map[K]V key k K m[k] V |
| 6722 |
channel c chan E, <-chan E element e E |
| 6723 |
integer value n integer type, or untyped int value i see below |
| 6724 |
function, 0 values f func(func() bool) |
| 6725 |
function, 1 value f func(func(V) bool) value v V |
| 6726 |
function, 2 values f func(func(K, V) bool) key k K v V |
| 6727 |
</pre> |
| 6728 |
|
| 6729 |
<ol> |
| 6730 |
<li> |
| 6731 |
For an array, pointer to array, or slice value <code>a</code>, the index iteration |
| 6732 |
values are produced in increasing order, starting at element index 0. |
| 6733 |
If at most one iteration variable is present, the range loop produces |
| 6734 |
iteration values from 0 up to <code>len(a)-1</code> and does not index into the array |
| 6735 |
or slice itself. For a <code>nil</code> slice, the number of iterations is 0. |
| 6736 |
</li> |
| 6737 |
|
| 6738 |
<li> |
| 6739 |
For a string value, the "range" clause iterates over the Unicode code points |
| 6740 |
in the string starting at byte index 0. On successive iterations, the index value will be the |
| 6741 |
index of the first byte of successive UTF-8-encoded code points in the string, |
| 6742 |
and the second value, of type <code>rune</code>, will be the value of |
| 6743 |
the corresponding code point. If the iteration encounters an invalid |
| 6744 |
UTF-8 sequence, the second value will be <code>0xFFFD</code>, |
| 6745 |
the Unicode replacement character, and the next iteration will advance |
| 6746 |
a single byte in the string. |
| 6747 |
</li> |
| 6748 |
|
| 6749 |
<li> |
| 6750 |
The iteration order over maps is not specified |
| 6751 |
and is not guaranteed to be the same from one iteration to the next. |
| 6752 |
If a map entry that has not yet been reached is removed during iteration, |
| 6753 |
the corresponding iteration value will not be produced. If a map entry is |
| 6754 |
created during iteration, that entry may be produced during the iteration or |
| 6755 |
may be skipped. The choice may vary for each entry created and from one |
| 6756 |
iteration to the next. |
| 6757 |
If the map is <code>nil</code>, the number of iterations is 0. |
| 6758 |
</li> |
| 6759 |
|
| 6760 |
<li> |
| 6761 |
For channels, the iteration values produced are the successive values sent on |
| 6762 |
the channel until the channel is <a href="#Close">closed</a>. If the channel |
| 6763 |
is <code>nil</code>, the range expression blocks forever. |
| 6764 |
</li> |
| 6765 |
|
| 6766 |
<li> |
| 6767 |
For an integer value <code>n</code>, where <code>n</code> is of <a href="#Numeric_types">integer type</a> |
| 6768 |
or an untyped <a href="#Constants">integer constant</a>, the iteration values 0 through <code>n-1</code> |
| 6769 |
are produced in increasing order. |
| 6770 |
If <code>n</code> is of integer type, the iteration values have that same type. |
| 6771 |
Otherwise, the type of <code>n</code> is determined as if it were assigned to the |
| 6772 |
iteration variable. |
| 6773 |
Specifically: |
| 6774 |
if the iteration variable is preexisting, the type of the iteration values is the type of the iteration |
| 6775 |
variable, which must be of integer type. |
| 6776 |
Otherwise, if the iteration variable is declared by the "range" clause or is absent, |
| 6777 |
the type of the iteration values is the <a href="#Constants">default type</a> for <code>n</code>. |
| 6778 |
If <code>n</code> <= 0, the loop does not run any iterations. |
| 6779 |
</li> |
| 6780 |
|
| 6781 |
<li> |
| 6782 |
For a function <code>f</code>, the iteration proceeds by calling <code>f</code> |
| 6783 |
with a new, synthesized <code>yield</code> function as its argument. |
| 6784 |
If <code>yield</code> is called before <code>f</code> returns, |
| 6785 |
the arguments to <code>yield</code> become the iteration values |
| 6786 |
for executing the loop body once. |
| 6787 |
After each successive loop iteration, <code>yield</code> returns true |
| 6788 |
and may be called again to continue the loop. |
| 6789 |
As long as the loop body does not terminate, the "range" clause will continue |
| 6790 |
to generate iteration values this way for each <code>yield</code> call until |
| 6791 |
<code>f</code> returns. |
| 6792 |
If the loop body terminates (such as by a <code>break</code> statement), |
| 6793 |
<code>yield</code> returns false and must not be called again. |
| 6794 |
</li> |
| 6795 |
</ol> |
| 6796 |
|
| 6797 |
<p> |
| 6798 |
The iteration variables may be declared by the "range" clause using a form of |
| 6799 |
<a href="#Short_variable_declarations">short variable declaration</a> |
| 6800 |
(<code>:=</code>). |
| 6801 |
In this case their <a href="#Declarations_and_scope">scope</a> is the block of the "for" statement |
| 6802 |
and each iteration has its own new variables [<a href="#Go_1.22">Go 1.22</a>] |
| 6803 |
(see also <a href="#For_clause">"for" statements with a ForClause</a>). |
| 6804 |
The variables have the types of their respective iteration values. |
| 6805 |
</p> |
| 6806 |
|
| 6807 |
<p> |
| 6808 |
If the iteration variables are not explicitly declared by the "range" clause, |
| 6809 |
they must be preexisting. |
| 6810 |
In this case, the iteration values are assigned to the respective variables |
| 6811 |
as in an <a href="#Assignment_statements">assignment statement</a>. |
| 6812 |
</p> |
| 6813 |
|
| 6814 |
<pre> |
| 6815 |
var testdata *struct { |
| 6816 |
a *[7]int |
| 6817 |
} |
| 6818 |
for i, _ := range testdata.a { |
| 6819 |
// testdata.a is never evaluated; len(testdata.a) is constant |
| 6820 |
// i ranges from 0 to 6 |
| 6821 |
f(i) |
| 6822 |
} |
| 6823 |
|
| 6824 |
var a [10]string |
| 6825 |
for i, s := range a { |
| 6826 |
// type of i is int |
| 6827 |
// type of s is string |
| 6828 |
// s == a[i] |
| 6829 |
g(i, s) |
| 6830 |
} |
| 6831 |
|
| 6832 |
var key string |
| 6833 |
var val interface{} // element type of m is assignable to val |
| 6834 |
m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6} |
| 6835 |
for key, val = range m { |
| 6836 |
h(key, val) |
| 6837 |
} |
| 6838 |
// key == last map key encountered in iteration |
| 6839 |
// val == map[key] |
| 6840 |
|
| 6841 |
var ch chan Work = producer() |
| 6842 |
for w := range ch { |
| 6843 |
doWork(w) |
| 6844 |
} |
| 6845 |
|
| 6846 |
// empty a channel |
| 6847 |
for range ch {} |
| 6848 |
|
| 6849 |
// call f(0), f(1), ... f(9) |
| 6850 |
for i := range 10 { |
| 6851 |
// type of i is int (default type for untyped constant 10) |
| 6852 |
f(i) |
| 6853 |
} |
| 6854 |
|
| 6855 |
// invalid: 256 cannot be assigned to uint8 |
| 6856 |
var u uint8 |
| 6857 |
for u = range 256 { |
| 6858 |
} |
| 6859 |
|
| 6860 |
// invalid: 1e3 is a floating-point constant |
| 6861 |
for range 1e3 { |
| 6862 |
} |
| 6863 |
|
| 6864 |
// fibo generates the Fibonacci sequence |
| 6865 |
fibo := func(yield func(x int) bool) { |
| 6866 |
f0, f1 := 0, 1 |
| 6867 |
for yield(f0) { |
| 6868 |
f0, f1 = f1, f0+f1 |
| 6869 |
} |
| 6870 |
} |
| 6871 |
|
| 6872 |
// print the Fibonacci numbers below 1000: |
| 6873 |
for x := range fibo { |
| 6874 |
if x >= 1000 { |
| 6875 |
break |
| 6876 |
} |
| 6877 |
fmt.Printf("%d ", x) |
| 6878 |
} |
| 6879 |
// output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 6880 |
|
| 6881 |
// iteration support for a recursive tree data structure |
| 6882 |
type Tree[K cmp.Ordered, V any] struct { |
| 6883 |
left, right *Tree[K, V] |
| 6884 |
key K |
| 6885 |
value V |
| 6886 |
} |
| 6887 |
|
| 6888 |
func (t *Tree[K, V]) walk(yield func(key K, val V) bool) bool { |
| 6889 |
return t == nil || t.left.walk(yield) && yield(t.key, t.value) && t.right.walk(yield) |
| 6890 |
} |
| 6891 |
|
| 6892 |
func (t *Tree[K, V]) Walk(yield func(key K, val V) bool) { |
| 6893 |
t.walk(yield) |
| 6894 |
} |
| 6895 |
|
| 6896 |
// walk tree t in-order |
| 6897 |
var t Tree[string, int] |
| 6898 |
for k, v := range t.Walk { |
| 6899 |
// process k, v |
| 6900 |
} |
| 6901 |
</pre> |
| 6902 |
|
| 6903 |
<p> |
| 6904 |
If the type of the range expression is a <a href="#Type_parameter_declarations">type parameter</a>, |
| 6905 |
all types in its type set must have the same underlying type and the range expression must be valid |
| 6906 |
for that type, or, if the type set contains channel types, it must only contain channel types with |
| 6907 |
identical element types, and all channel types must permit receive operations. |
| 6908 |
</p> |
| 6909 |
|
| 6910 |
<h3 id="Go_statements">Go statements</h3> |
| 6911 |
|
| 6912 |
<p> |
| 6913 |
A "go" statement starts the execution of a function call |
| 6914 |
as an independent concurrent thread of control, or <i>goroutine</i>, |
| 6915 |
within the same address space. |
| 6916 |
</p> |
| 6917 |
|
| 6918 |
<pre class="ebnf"> |
| 6919 |
GoStmt = "go" Expression . |
| 6920 |
</pre> |
| 6921 |
|
| 6922 |
<p> |
| 6923 |
The expression must be a function or method call; it cannot be parenthesized. |
| 6924 |
Calls of built-in functions are restricted as for |
| 6925 |
<a href="#Expression_statements">expression statements</a>. |
| 6926 |
</p> |
| 6927 |
|
| 6928 |
<p> |
| 6929 |
The function value and parameters are |
| 6930 |
<a href="#Calls">evaluated as usual</a> |
| 6931 |
in the calling goroutine, but |
| 6932 |
unlike with a regular call, program execution does not wait |
| 6933 |
for the invoked function to complete. |
| 6934 |
Instead, the function begins executing independently |
| 6935 |
in a new goroutine. |
| 6936 |
When the function terminates, its goroutine also terminates. |
| 6937 |
If the function has any return values, they are discarded when the |
| 6938 |
function completes. |
| 6939 |
</p> |
| 6940 |
|
| 6941 |
<pre> |
| 6942 |
go Server() |
| 6943 |
go func(ch chan<- bool) { for { sleep(10); ch <- true }} (c) |
| 6944 |
</pre> |
| 6945 |
|
| 6946 |
|
| 6947 |
<h3 id="Select_statements">Select statements</h3> |
| 6948 |
|
| 6949 |
<p> |
| 6950 |
A "select" statement chooses which of a set of possible |
| 6951 |
<a href="#Send_statements">send</a> or |
| 6952 |
<a href="#Receive_operator">receive</a> |
| 6953 |
operations will proceed. |
| 6954 |
It looks similar to a |
| 6955 |
<a href="#Switch_statements">"switch"</a> statement but with the |
| 6956 |
cases all referring to communication operations. |
| 6957 |
</p> |
| 6958 |
|
| 6959 |
<pre class="ebnf"> |
| 6960 |
SelectStmt = "select" "{" { CommClause } "}" . |
| 6961 |
CommClause = CommCase ":" StatementList . |
| 6962 |
CommCase = "case" ( SendStmt | RecvStmt ) | "default" . |
| 6963 |
RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr . |
| 6964 |
RecvExpr = Expression . |
| 6965 |
</pre> |
| 6966 |
|
| 6967 |
<p> |
| 6968 |
A case with a RecvStmt may assign the result of a RecvExpr to one or |
| 6969 |
two variables, which may be declared using a |
| 6970 |
<a href="#Short_variable_declarations">short variable declaration</a>. |
| 6971 |
The RecvExpr must be a (possibly parenthesized) receive operation. |
| 6972 |
There can be at most one default case and it may appear anywhere |
| 6973 |
in the list of cases. |
| 6974 |
</p> |
| 6975 |
|
| 6976 |
<p> |
| 6977 |
Execution of a "select" statement proceeds in several steps: |
| 6978 |
</p> |
| 6979 |
|
| 6980 |
<ol> |
| 6981 |
<li> |
| 6982 |
For all the cases in the statement, the channel operands of receive operations |
| 6983 |
and the channel and right-hand-side expressions of send statements are |
| 6984 |
evaluated exactly once, in source order, upon entering the "select" statement. |
| 6985 |
The result is a set of channels to receive from or send to, |
| 6986 |
and the corresponding values to send. |
| 6987 |
Any side effects in that evaluation will occur irrespective of which (if any) |
| 6988 |
communication operation is selected to proceed. |
| 6989 |
Expressions on the left-hand side of a RecvStmt with a short variable declaration |
| 6990 |
or assignment are not yet evaluated. |
| 6991 |
</li> |
| 6992 |
|
| 6993 |
<li> |
| 6994 |
If one or more of the communications can proceed, |
| 6995 |
a single one that can proceed is chosen via a uniform pseudo-random selection. |
| 6996 |
Otherwise, if there is a default case, that case is chosen. |
| 6997 |
If there is no default case, the "select" statement blocks until |
| 6998 |
at least one of the communications can proceed. |
| 6999 |
</li> |
| 7000 |
|
| 7001 |
<li> |
| 7002 |
Unless the selected case is the default case, the respective communication |
| 7003 |
operation is executed. |
| 7004 |
</li> |
| 7005 |
|
| 7006 |
<li> |
| 7007 |
If the selected case is a RecvStmt with a short variable declaration or |
| 7008 |
an assignment, the left-hand side expressions are evaluated and the |
| 7009 |
received value (or values) are assigned. |
| 7010 |
</li> |
| 7011 |
|
| 7012 |
<li> |
| 7013 |
The statement list of the selected case is executed. |
| 7014 |
</li> |
| 7015 |
</ol> |
| 7016 |
|
| 7017 |
<p> |
| 7018 |
Since communication on <code>nil</code> channels can never proceed, |
| 7019 |
a select with only <code>nil</code> channels and no default case blocks forever. |
| 7020 |
</p> |
| 7021 |
|
| 7022 |
<pre> |
| 7023 |
var a []int |
| 7024 |
var c, c1, c2, c3, c4 chan int |
| 7025 |
var i1, i2 int |
| 7026 |
select { |
| 7027 |
case i1 = <-c1: |
| 7028 |
print("received ", i1, " from c1\n") |
| 7029 |
case c2 <- i2: |
| 7030 |
print("sent ", i2, " to c2\n") |
| 7031 |
case i3, ok := (<-c3): // same as: i3, ok := <-c3 |
| 7032 |
if ok { |
| 7033 |
print("received ", i3, " from c3\n") |
| 7034 |
} else { |
| 7035 |
print("c3 is closed\n") |
| 7036 |
} |
| 7037 |
case a[f()] = <-c4: |
| 7038 |
// same as: |
| 7039 |
// case t := <-c4 |
| 7040 |
// a[f()] = t |
| 7041 |
default: |
| 7042 |
print("no communication\n") |
| 7043 |
} |
| 7044 |
|
| 7045 |
for { // send random sequence of bits to c |
| 7046 |
select { |
| 7047 |
case c <- 0: // note: no statement, no fallthrough, no folding of cases |
| 7048 |
case c <- 1: |
| 7049 |
} |
| 7050 |
} |
| 7051 |
|
| 7052 |
select {} // block forever |
| 7053 |
</pre> |
| 7054 |
|
| 7055 |
|
| 7056 |
<h3 id="Return_statements">Return statements</h3> |
| 7057 |
|
| 7058 |
<p> |
| 7059 |
A "return" statement in a function <code>F</code> terminates the execution |
| 7060 |
of <code>F</code>, and optionally provides one or more result values. |
| 7061 |
Any functions <a href="#Defer_statements">deferred</a> by <code>F</code> |
| 7062 |
are executed before <code>F</code> returns to its caller. |
| 7063 |
</p> |
| 7064 |
|
| 7065 |
<pre class="ebnf"> |
| 7066 |
ReturnStmt = "return" [ ExpressionList ] . |
| 7067 |
</pre> |
| 7068 |
|
| 7069 |
<p> |
| 7070 |
In a function without a result type, a "return" statement must not |
| 7071 |
specify any result values. |
| 7072 |
</p> |
| 7073 |
<pre> |
| 7074 |
func noResult() { |
| 7075 |
return |
| 7076 |
} |
| 7077 |
</pre> |
| 7078 |
|
| 7079 |
<p> |
| 7080 |
There are three ways to return values from a function with a result |
| 7081 |
type: |
| 7082 |
</p> |
| 7083 |
|
| 7084 |
<ol> |
| 7085 |
<li>The return value or values may be explicitly listed |
| 7086 |
in the "return" statement. Each expression must be single-valued |
| 7087 |
and <a href="#Assignability">assignable</a> |
| 7088 |
to the corresponding element of the function's result type. |
| 7089 |
<pre> |
| 7090 |
func simpleF() int { |
| 7091 |
return 2 |
| 7092 |
} |
| 7093 |
|
| 7094 |
func complexF1() (re float64, im float64) { |
| 7095 |
return -7.0, -4.0 |
| 7096 |
} |
| 7097 |
</pre> |
| 7098 |
</li> |
| 7099 |
<li>The expression list in the "return" statement may be a single |
| 7100 |
call to a multi-valued function. The effect is as if each value |
| 7101 |
returned from that function were assigned to a temporary |
| 7102 |
variable with the type of the respective value, followed by a |
| 7103 |
"return" statement listing these variables, at which point the |
| 7104 |
rules of the previous case apply. |
| 7105 |
<pre> |
| 7106 |
func complexF2() (re float64, im float64) { |
| 7107 |
return complexF1() |
| 7108 |
} |
| 7109 |
</pre> |
| 7110 |
</li> |
| 7111 |
<li>The expression list may be empty if the function's result |
| 7112 |
type specifies names for its <a href="#Function_types">result parameters</a>. |
| 7113 |
The result parameters act as ordinary local variables |
| 7114 |
and the function may assign values to them as necessary. |
| 7115 |
The "return" statement returns the values of these variables. |
| 7116 |
<pre> |
| 7117 |
func complexF3() (re float64, im float64) { |
| 7118 |
re = 7.0 |
| 7119 |
im = 4.0 |
| 7120 |
return |
| 7121 |
} |
| 7122 |
|
| 7123 |
func (devnull) Write(p []byte) (n int, _ error) { |
| 7124 |
n = len(p) |
| 7125 |
return |
| 7126 |
} |
| 7127 |
</pre> |
| 7128 |
</li> |
| 7129 |
</ol> |
| 7130 |
|
| 7131 |
<p> |
| 7132 |
Regardless of how they are declared, all the result values are initialized to |
| 7133 |
the <a href="#The_zero_value">zero values</a> for their type upon entry to the |
| 7134 |
function. A "return" statement that specifies results sets the result parameters before |
| 7135 |
any deferred functions are executed. |
| 7136 |
</p> |
| 7137 |
|
| 7138 |
<p> |
| 7139 |
Implementation restriction: A compiler may disallow an empty expression list |
| 7140 |
in a "return" statement if a different entity (constant, type, or variable) |
| 7141 |
with the same name as a result parameter is in |
| 7142 |
<a href="#Declarations_and_scope">scope</a> at the place of the return. |
| 7143 |
</p> |
| 7144 |
|
| 7145 |
<pre> |
| 7146 |
func f(n int) (res int, err error) { |
| 7147 |
if _, err := f(n-1); err != nil { |
| 7148 |
return // invalid return statement: err is shadowed |
| 7149 |
} |
| 7150 |
return |
| 7151 |
} |
| 7152 |
</pre> |
| 7153 |
|
| 7154 |
<h3 id="Break_statements">Break statements</h3> |
| 7155 |
|
| 7156 |
<p> |
| 7157 |
A "break" statement terminates execution of the innermost |
| 7158 |
<a href="#For_statements">"for"</a>, |
| 7159 |
<a href="#Switch_statements">"switch"</a>, or |
| 7160 |
<a href="#Select_statements">"select"</a> statement |
| 7161 |
within the same function. |
| 7162 |
</p> |
| 7163 |
|
| 7164 |
<pre class="ebnf"> |
| 7165 |
BreakStmt = "break" [ Label ] . |
| 7166 |
</pre> |
| 7167 |
|
| 7168 |
<p> |
| 7169 |
If there is a label, it must be that of an enclosing |
| 7170 |
"for", "switch", or "select" statement, |
| 7171 |
and that is the one whose execution terminates. |
| 7172 |
</p> |
| 7173 |
|
| 7174 |
<pre> |
| 7175 |
OuterLoop: |
| 7176 |
for i = 0; i < n; i++ { |
| 7177 |
for j = 0; j < m; j++ { |
| 7178 |
switch a[i][j] { |
| 7179 |
case nil: |
| 7180 |
state = Error |
| 7181 |
break OuterLoop |
| 7182 |
case item: |
| 7183 |
state = Found |
| 7184 |
break OuterLoop |
| 7185 |
} |
| 7186 |
} |
| 7187 |
} |
| 7188 |
</pre> |
| 7189 |
|
| 7190 |
<h3 id="Continue_statements">Continue statements</h3> |
| 7191 |
|
| 7192 |
<p> |
| 7193 |
A "continue" statement begins the next iteration of the |
| 7194 |
innermost enclosing <a href="#For_statements">"for" loop</a> |
| 7195 |
by advancing control to the end of the loop block. |
| 7196 |
The "for" loop must be within the same function. |
| 7197 |
</p> |
| 7198 |
|
| 7199 |
<pre class="ebnf"> |
| 7200 |
ContinueStmt = "continue" [ Label ] . |
| 7201 |
</pre> |
| 7202 |
|
| 7203 |
<p> |
| 7204 |
If there is a label, it must be that of an enclosing |
| 7205 |
"for" statement, and that is the one whose execution |
| 7206 |
advances. |
| 7207 |
</p> |
| 7208 |
|
| 7209 |
<pre> |
| 7210 |
RowLoop: |
| 7211 |
for y, row := range rows { |
| 7212 |
for x, data := range row { |
| 7213 |
if data == endOfRow { |
| 7214 |
continue RowLoop |
| 7215 |
} |
| 7216 |
row[x] = data + bias(x, y) |
| 7217 |
} |
| 7218 |
} |
| 7219 |
</pre> |
| 7220 |
|
| 7221 |
<h3 id="Goto_statements">Goto statements</h3> |
| 7222 |
|
| 7223 |
<p> |
| 7224 |
A "goto" statement transfers control to the statement with the corresponding label |
| 7225 |
within the same function. |
| 7226 |
</p> |
| 7227 |
|
| 7228 |
<pre class="ebnf"> |
| 7229 |
GotoStmt = "goto" Label . |
| 7230 |
</pre> |
| 7231 |
|
| 7232 |
<pre> |
| 7233 |
goto Error |
| 7234 |
</pre> |
| 7235 |
|
| 7236 |
<p> |
| 7237 |
Executing the "goto" statement must not cause any variables to come into |
| 7238 |
<a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto. |
| 7239 |
For instance, this example: |
| 7240 |
</p> |
| 7241 |
|
| 7242 |
<pre> |
| 7243 |
goto L // BAD |
| 7244 |
v := 3 |
| 7245 |
L: |
| 7246 |
</pre> |
| 7247 |
|
| 7248 |
<p> |
| 7249 |
is erroneous because the jump to label <code>L</code> skips |
| 7250 |
the creation of <code>v</code>. |
| 7251 |
</p> |
| 7252 |
|
| 7253 |
<p> |
| 7254 |
A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block. |
| 7255 |
For instance, this example: |
| 7256 |
</p> |
| 7257 |
|
| 7258 |
<pre> |
| 7259 |
if n%2 == 1 { |
| 7260 |
goto L1 |
| 7261 |
} |
| 7262 |
for n > 0 { |
| 7263 |
f() |
| 7264 |
n-- |
| 7265 |
L1: |
| 7266 |
f() |
| 7267 |
n-- |
| 7268 |
} |
| 7269 |
</pre> |
| 7270 |
|
| 7271 |
<p> |
| 7272 |
is erroneous because the label <code>L1</code> is inside |
| 7273 |
the "for" statement's block but the <code>goto</code> is not. |
| 7274 |
</p> |
| 7275 |
|
| 7276 |
<h3 id="Fallthrough_statements">Fallthrough statements</h3> |
| 7277 |
|
| 7278 |
<p> |
| 7279 |
A "fallthrough" statement transfers control to the first statement of the |
| 7280 |
next case clause in an <a href="#Expression_switches">expression "switch" statement</a>. |
| 7281 |
It may be used only as the final non-empty statement in such a clause. |
| 7282 |
</p> |
| 7283 |
|
| 7284 |
<pre class="ebnf"> |
| 7285 |
FallthroughStmt = "fallthrough" . |
| 7286 |
</pre> |
| 7287 |
|
| 7288 |
|
| 7289 |
<h3 id="Defer_statements">Defer statements</h3> |
| 7290 |
|
| 7291 |
<p> |
| 7292 |
A "defer" statement invokes a function whose execution is deferred |
| 7293 |
to the moment the surrounding function returns, either because the |
| 7294 |
surrounding function executed a <a href="#Return_statements">return statement</a>, |
| 7295 |
reached the end of its <a href="#Function_declarations">function body</a>, |
| 7296 |
or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>. |
| 7297 |
</p> |
| 7298 |
|
| 7299 |
<pre class="ebnf"> |
| 7300 |
DeferStmt = "defer" Expression . |
| 7301 |
</pre> |
| 7302 |
|
| 7303 |
<p> |
| 7304 |
The expression must be a function or method call; it cannot be parenthesized. |
| 7305 |
Calls of built-in functions are restricted as for |
| 7306 |
<a href="#Expression_statements">expression statements</a>. |
| 7307 |
</p> |
| 7308 |
|
| 7309 |
<p> |
| 7310 |
Each time a "defer" statement |
| 7311 |
executes, the function value and parameters to the call are |
| 7312 |
<a href="#Calls">evaluated as usual</a> |
| 7313 |
and saved anew but the actual function is not invoked. |
| 7314 |
Instead, deferred functions are invoked immediately before |
| 7315 |
the surrounding function returns, in the reverse order |
| 7316 |
they were deferred. That is, if the surrounding function |
| 7317 |
returns through an explicit <a href="#Return_statements">return statement</a>, |
| 7318 |
deferred functions are executed <i>after</i> any result parameters are set |
| 7319 |
by that return statement but <i>before</i> the function returns to its caller. |
| 7320 |
If a deferred function value evaluates |
| 7321 |
to <code>nil</code>, execution <a href="#Handling_panics">panics</a> |
| 7322 |
when the function is invoked, not when the "defer" statement is executed. |
| 7323 |
</p> |
| 7324 |
|
| 7325 |
<p> |
| 7326 |
For instance, if the deferred function is |
| 7327 |
a <a href="#Function_literals">function literal</a> and the surrounding |
| 7328 |
function has <a href="#Function_types">named result parameters</a> that |
| 7329 |
are in scope within the literal, the deferred function may access and modify |
| 7330 |
the result parameters before they are returned. |
| 7331 |
If the deferred function has any return values, they are discarded when |
| 7332 |
the function completes. |
| 7333 |
(See also the section on <a href="#Handling_panics">handling panics</a>.) |
| 7334 |
</p> |
| 7335 |
|
| 7336 |
<pre> |
| 7337 |
lock(l) |
| 7338 |
defer unlock(l) // unlocking happens before surrounding function returns |
| 7339 |
|
| 7340 |
// prints 3 2 1 0 before surrounding function returns |
| 7341 |
for i := 0; i <= 3; i++ { |
| 7342 |
defer fmt.Print(i) |
| 7343 |
} |
| 7344 |
|
| 7345 |
// f returns 42 |
| 7346 |
func f() (result int) { |
| 7347 |
defer func() { |
| 7348 |
// result is accessed after it was set to 6 by the return statement |
| 7349 |
result *= 7 |
| 7350 |
}() |
| 7351 |
return 6 |
| 7352 |
} |
| 7353 |
</pre> |
| 7354 |
|
| 7355 |
<h2 id="Built-in_functions">Built-in functions</h2> |
| 7356 |
|
| 7357 |
<p> |
| 7358 |
Built-in functions are |
| 7359 |
<a href="#Predeclared_identifiers">predeclared</a>. |
| 7360 |
They are called like any other function but some of them |
| 7361 |
accept a type instead of an expression as the first argument. |
| 7362 |
</p> |
| 7363 |
|
| 7364 |
<p> |
| 7365 |
The built-in functions do not have standard Go types, |
| 7366 |
so they can only appear in <a href="#Calls">call expressions</a>; |
| 7367 |
they cannot be used as function values. |
| 7368 |
</p> |
| 7369 |
|
| 7370 |
|
| 7371 |
<h3 id="Appending_and_copying_slices">Appending to and copying slices</h3> |
| 7372 |
|
| 7373 |
<p> |
| 7374 |
The built-in functions <code>append</code> and <code>copy</code> assist in |
| 7375 |
common slice operations. |
| 7376 |
For both functions, the result is independent of whether the memory referenced |
| 7377 |
by the arguments overlaps. |
| 7378 |
</p> |
| 7379 |
|
| 7380 |
<p> |
| 7381 |
The <a href="#Function_types">variadic</a> function <code>append</code> |
| 7382 |
appends zero or more values <code>x</code> to a slice <code>s</code> of |
| 7383 |
type <code>S</code> and returns the resulting slice, also of type |
| 7384 |
<code>S</code>. |
| 7385 |
The values <code>x</code> are passed to a parameter of type <code>...E</code> |
| 7386 |
where <code>E</code> is the element type of <code>S</code> |
| 7387 |
and the respective <a href="#Passing_arguments_to_..._parameters">parameter |
| 7388 |
passing rules</a> apply. |
| 7389 |
As a special case, <code>append</code> also accepts a slice whose type is assignable to |
| 7390 |
type <code>[]byte</code> with a second argument of <code>string</code> type followed by |
| 7391 |
<code>...</code>. |
| 7392 |
This form appends the bytes of the string. |
| 7393 |
</p> |
| 7394 |
|
| 7395 |
<pre class="grammar"> |
| 7396 |
append(s S, x ...E) S // E is the element type of S |
| 7397 |
</pre> |
| 7398 |
|
| 7399 |
<p> |
| 7400 |
If <code>S</code> is a <a href="#Type_parameter_declarations">type parameter</a>, |
| 7401 |
all types in its type set must have the same underlying slice type <code>[]E</code>. |
| 7402 |
</p> |
| 7403 |
|
| 7404 |
<p> |
| 7405 |
If the capacity of <code>s</code> is not large enough to fit the additional |
| 7406 |
values, <code>append</code> <a href="#Allocation">allocates</a> a new, sufficiently large underlying |
| 7407 |
array that fits both the existing slice elements and the additional values. |
| 7408 |
Otherwise, <code>append</code> re-uses the underlying array. |
| 7409 |
</p> |
| 7410 |
|
| 7411 |
<pre> |
| 7412 |
s0 := []int{0, 0} |
| 7413 |
s1 := append(s0, 2) // append a single element s1 is []int{0, 0, 2} |
| 7414 |
s2 := append(s1, 3, 5, 7) // append multiple elements s2 is []int{0, 0, 2, 3, 5, 7} |
| 7415 |
s3 := append(s2, s0...) // append a slice s3 is []int{0, 0, 2, 3, 5, 7, 0, 0} |
| 7416 |
s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 is []int{3, 5, 7, 2, 3, 5, 7, 0, 0} |
| 7417 |
|
| 7418 |
var t []interface{} |
| 7419 |
t = append(t, 42, 3.1415, "foo") // t is []interface{}{42, 3.1415, "foo"} |
| 7420 |
|
| 7421 |
var b []byte |
| 7422 |
b = append(b, "bar"...) // append string contents b is []byte{'b', 'a', 'r' } |
| 7423 |
</pre> |
| 7424 |
|
| 7425 |
<p> |
| 7426 |
The function <code>copy</code> copies slice elements from |
| 7427 |
a source <code>src</code> to a destination <code>dst</code> and returns the |
| 7428 |
number of elements copied. |
| 7429 |
Both arguments must have <a href="#Type_identity">identical</a> element type |
| 7430 |
<code>E</code> and must be assignable to a slice of type <code>[]E</code>. |
| 7431 |
The number of elements copied is the minimum of |
| 7432 |
<code>len(src)</code> and <code>len(dst)</code>. |
| 7433 |
As a special case, <code>copy</code> also accepts a destination argument |
| 7434 |
assignable to type <code>[]byte</code> with a source argument of a |
| 7435 |
<code>string</code> type. |
| 7436 |
This form copies the bytes from the string into the byte slice. |
| 7437 |
</p> |
| 7438 |
|
| 7439 |
<pre class="grammar"> |
| 7440 |
copy(dst, src []T) int |
| 7441 |
copy(dst []byte, src string) int |
| 7442 |
</pre> |
| 7443 |
|
| 7444 |
<p> |
| 7445 |
If the type of one or both arguments is a <a href="#Type_parameter_declarations">type parameter</a>, |
| 7446 |
all types in their respective type sets must have the same underlying slice type <code>[]E</code>. |
| 7447 |
</p> |
| 7448 |
|
| 7449 |
<p> |
| 7450 |
Examples: |
| 7451 |
</p> |
| 7452 |
|
| 7453 |
<pre> |
| 7454 |
var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7} |
| 7455 |
var s = make([]int, 6) |
| 7456 |
var b = make([]byte, 5) |
| 7457 |
n1 := copy(s, a[0:]) // n1 == 6, s is []int{0, 1, 2, 3, 4, 5} |
| 7458 |
n2 := copy(s, s[2:]) // n2 == 4, s is []int{2, 3, 4, 5, 4, 5} |
| 7459 |
n3 := copy(b, "Hello, World!") // n3 == 5, b is []byte("Hello") |
| 7460 |
</pre> |
| 7461 |
|
| 7462 |
|
| 7463 |
<h3 id="Clear">Clear</h3> |
| 7464 |
|
| 7465 |
<p> |
| 7466 |
The built-in function <code>clear</code> takes an argument of <a href="#Map_types">map</a>, |
| 7467 |
<a href="#Slice_types">slice</a>, or <a href="#Type_parameter_declarations">type parameter</a> type, |
| 7468 |
and deletes or zeroes out all elements |
| 7469 |
[<a href="#Go_1.21">Go 1.21</a>]. |
| 7470 |
</p> |
| 7471 |
|
| 7472 |
<pre class="grammar"> |
| 7473 |
Call Argument type Result |
| 7474 |
|
| 7475 |
clear(m) map[K]T deletes all entries, resulting in an |
| 7476 |
empty map (len(m) == 0) |
| 7477 |
|
| 7478 |
clear(s) []T sets all elements up to the length of |
| 7479 |
<code>s</code> to the zero value of T |
| 7480 |
|
| 7481 |
clear(t) type parameter see below |
| 7482 |
</pre> |
| 7483 |
|
| 7484 |
<p> |
| 7485 |
If the type of the argument to <code>clear</code> is a |
| 7486 |
<a href="#Type_parameter_declarations">type parameter</a>, |
| 7487 |
all types in its type set must be maps or slices, and <code>clear</code> |
| 7488 |
performs the operation corresponding to the actual type argument. |
| 7489 |
</p> |
| 7490 |
|
| 7491 |
<p> |
| 7492 |
If the map or slice is <code>nil</code>, <code>clear</code> is a no-op. |
| 7493 |
</p> |
| 7494 |
|
| 7495 |
|
| 7496 |
<h3 id="Close">Close</h3> |
| 7497 |
|
| 7498 |
<p> |
| 7499 |
For a channel <code>ch</code>, the built-in function <code>close(ch)</code> |
| 7500 |
records that no more values will be sent on the channel. |
| 7501 |
It is an error if <code>ch</code> is a receive-only channel. |
| 7502 |
Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>. |
| 7503 |
Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>. |
| 7504 |
After calling <code>close</code>, and after any previously |
| 7505 |
sent values have been received, receive operations will return |
| 7506 |
the zero value for the channel's type without blocking. |
| 7507 |
The multi-valued <a href="#Receive_operator">receive operation</a> |
| 7508 |
returns a received value along with an indication of whether the channel is closed. |
| 7509 |
</p> |
| 7510 |
|
| 7511 |
<p> |
| 7512 |
If the type of the argument to <code>close</code> is a |
| 7513 |
<a href="#Type_parameter_declarations">type parameter</a>, |
| 7514 |
all types in its type set must be channels. |
| 7515 |
It is an error if any of those channels is a receive-only channel. |
| 7516 |
</p> |
| 7517 |
|
| 7518 |
<h3 id="Complex_numbers">Manipulating complex numbers</h3> |
| 7519 |
|
| 7520 |
<p> |
| 7521 |
Three functions assemble and disassemble complex numbers. |
| 7522 |
The built-in function <code>complex</code> constructs a complex |
| 7523 |
value from a floating-point real and imaginary part, while |
| 7524 |
<code>real</code> and <code>imag</code> |
| 7525 |
extract the real and imaginary parts of a complex value. |
| 7526 |
</p> |
| 7527 |
|
| 7528 |
<pre class="grammar"> |
| 7529 |
complex(realPart, imaginaryPart floatT) complexT |
| 7530 |
real(complexT) floatT |
| 7531 |
imag(complexT) floatT |
| 7532 |
</pre> |
| 7533 |
|
| 7534 |
<p> |
| 7535 |
The type of the arguments and return value correspond. |
| 7536 |
For <code>complex</code>, the two arguments must be of the same |
| 7537 |
<a href="#Numeric_types">floating-point type</a> and the return type is the |
| 7538 |
<a href="#Numeric_types">complex type</a> |
| 7539 |
with the corresponding floating-point constituents: |
| 7540 |
<code>complex64</code> for <code>float32</code> arguments, and |
| 7541 |
<code>complex128</code> for <code>float64</code> arguments. |
| 7542 |
If one of the arguments evaluates to an untyped constant, it is first implicitly |
| 7543 |
<a href="#Conversions">converted</a> to the type of the other argument. |
| 7544 |
If both arguments evaluate to untyped constants, they must be non-complex |
| 7545 |
numbers or their imaginary parts must be zero, and the return value of |
| 7546 |
the function is an untyped complex constant. |
| 7547 |
</p> |
| 7548 |
|
| 7549 |
<p> |
| 7550 |
For <code>real</code> and <code>imag</code>, the argument must be |
| 7551 |
of complex type, and the return type is the corresponding floating-point |
| 7552 |
type: <code>float32</code> for a <code>complex64</code> argument, and |
| 7553 |
<code>float64</code> for a <code>complex128</code> argument. |
| 7554 |
If the argument evaluates to an untyped constant, it must be a number, |
| 7555 |
and the return value of the function is an untyped floating-point constant. |
| 7556 |
</p> |
| 7557 |
|
| 7558 |
<p> |
| 7559 |
The <code>real</code> and <code>imag</code> functions together form the inverse of |
| 7560 |
<code>complex</code>, so for a value <code>z</code> of a complex type <code>Z</code>, |
| 7561 |
<code>z == Z(complex(real(z), imag(z)))</code>. |
| 7562 |
</p> |
| 7563 |
|
| 7564 |
<p> |
| 7565 |
If the operands of these functions are all constants, the return |
| 7566 |
value is a constant. |
| 7567 |
</p> |
| 7568 |
|
| 7569 |
<pre> |
| 7570 |
var a = complex(2, -2) // complex128 |
| 7571 |
const b = complex(1.0, -1.4) // untyped complex constant 1 - 1.4i |
| 7572 |
x := float32(math.Cos(math.Pi/2)) // float32 |
| 7573 |
var c64 = complex(5, -x) // complex64 |
| 7574 |
var s int = complex(1, 0) // untyped complex constant 1 + 0i can be converted to int |
| 7575 |
_ = complex(1, 2<<s) // illegal: 2 assumes floating-point type, cannot shift |
| 7576 |
var rl = real(c64) // float32 |
| 7577 |
var im = imag(a) // float64 |
| 7578 |
const c = imag(b) // untyped constant -1.4 |
| 7579 |
_ = imag(3 << s) // illegal: 3 assumes complex type, cannot shift |
| 7580 |
</pre> |
| 7581 |
|
| 7582 |
<p> |
| 7583 |
Arguments of type parameter type are not permitted. |
| 7584 |
</p> |
| 7585 |
|
| 7586 |
|
| 7587 |
<h3 id="Deletion_of_map_elements">Deletion of map elements</h3> |
| 7588 |
|
| 7589 |
<p> |
| 7590 |
The built-in function <code>delete</code> removes the element with key |
| 7591 |
<code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The |
| 7592 |
value <code>k</code> must be <a href="#Assignability">assignable</a> |
| 7593 |
to the key type of <code>m</code>. |
| 7594 |
</p> |
| 7595 |
|
| 7596 |
<pre class="grammar"> |
| 7597 |
delete(m, k) // remove element m[k] from map m |
| 7598 |
</pre> |
| 7599 |
|
| 7600 |
<p> |
| 7601 |
If the type of <code>m</code> is a <a href="#Type_parameter_declarations">type parameter</a>, |
| 7602 |
all types in that type set must be maps, and they must all have identical key types. |
| 7603 |
</p> |
| 7604 |
|
| 7605 |
<p> |
| 7606 |
If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code> |
| 7607 |
does not exist, <code>delete</code> is a no-op. |
| 7608 |
</p> |
| 7609 |
|
| 7610 |
|
| 7611 |
<h3 id="Length_and_capacity">Length and capacity</h3> |
| 7612 |
|
| 7613 |
<p> |
| 7614 |
The built-in functions <code>len</code> and <code>cap</code> take arguments |
| 7615 |
of various types and return a result of type <code>int</code>. |
| 7616 |
The implementation guarantees that the result always fits into an <code>int</code>. |
| 7617 |
</p> |
| 7618 |
|
| 7619 |
<pre class="grammar"> |
| 7620 |
Call Argument type Result |
| 7621 |
|
| 7622 |
len(s) string type string length in bytes |
| 7623 |
[n]T, *[n]T array length (== n) |
| 7624 |
[]T slice length |
| 7625 |
map[K]T map length (number of defined keys) |
| 7626 |
chan T number of elements queued in channel buffer |
| 7627 |
type parameter see below |
| 7628 |
|
| 7629 |
cap(s) [n]T, *[n]T array length (== n) |
| 7630 |
[]T slice capacity |
| 7631 |
chan T channel buffer capacity |
| 7632 |
type parameter see below |
| 7633 |
</pre> |
| 7634 |
|
| 7635 |
<p> |
| 7636 |
If the argument type is a <a href="#Type_parameter_declarations">type parameter</a> <code>P</code>, |
| 7637 |
the call <code>len(e)</code> (or <code>cap(e)</code> respectively) must be valid for |
| 7638 |
each type in <code>P</code>'s type set. |
| 7639 |
The result is the length (or capacity, respectively) of the argument whose type |
| 7640 |
corresponds to the type argument with which <code>P</code> was |
| 7641 |
<a href="#Instantiations">instantiated</a>. |
| 7642 |
</p> |
| 7643 |
|
| 7644 |
<p> |
| 7645 |
The capacity of a slice is the number of elements for which there is |
| 7646 |
space allocated in the underlying array. |
| 7647 |
At any time the following relationship holds: |
| 7648 |
</p> |
| 7649 |
|
| 7650 |
<pre> |
| 7651 |
0 <= len(s) <= cap(s) |
| 7652 |
</pre> |
| 7653 |
|
| 7654 |
<p> |
| 7655 |
The length of a <code>nil</code> slice, map or channel is 0. |
| 7656 |
The capacity of a <code>nil</code> slice or channel is 0. |
| 7657 |
</p> |
| 7658 |
|
| 7659 |
<p> |
| 7660 |
The expression <code>len(s)</code> is <a href="#Constants">constant</a> if |
| 7661 |
<code>s</code> is a string constant. The expressions <code>len(s)</code> and |
| 7662 |
<code>cap(s)</code> are constants if the type of <code>s</code> is an array |
| 7663 |
or pointer to an array and the expression <code>s</code> does not contain |
| 7664 |
<a href="#Receive_operator">channel receives</a> or (non-constant) |
| 7665 |
<a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated. |
| 7666 |
Otherwise, invocations of <code>len</code> and <code>cap</code> are not |
| 7667 |
constant and <code>s</code> is evaluated. |
| 7668 |
</p> |
| 7669 |
|
| 7670 |
<pre> |
| 7671 |
const ( |
| 7672 |
c1 = imag(2i) // imag(2i) = 2.0 is a constant |
| 7673 |
c2 = len([10]float64{2}) // [10]float64{2} contains no function calls |
| 7674 |
c3 = len([10]float64{c1}) // [10]float64{c1} contains no function calls |
| 7675 |
c4 = len([10]float64{imag(2i)}) // imag(2i) is a constant and no function call is issued |
| 7676 |
c5 = len([10]float64{imag(z)}) // invalid: imag(z) is a (non-constant) function call |
| 7677 |
) |
| 7678 |
var z complex128 |
| 7679 |
</pre> |
| 7680 |
|
| 7681 |
|
| 7682 |
<h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3> |
| 7683 |
|
| 7684 |
<p> |
| 7685 |
The built-in function <code>make</code> takes a type <code>T</code>, |
| 7686 |
which must be a slice, map or channel type, or a type parameter, |
| 7687 |
optionally followed by a type-specific list of expressions. |
| 7688 |
It returns a value of type <code>T</code> (not <code>*T</code>). |
| 7689 |
The memory is initialized as described in the section on |
| 7690 |
<a href="#The_zero_value">initial values</a>. |
| 7691 |
</p> |
| 7692 |
|
| 7693 |
<pre class="grammar"> |
| 7694 |
Call Type T Result |
| 7695 |
|
| 7696 |
make(T, n) slice slice of type T with length n and capacity n |
| 7697 |
make(T, n, m) slice slice of type T with length n and capacity m |
| 7698 |
|
| 7699 |
make(T) map map of type T |
| 7700 |
make(T, n) map map of type T with initial space for approximately n elements |
| 7701 |
|
| 7702 |
make(T) channel unbuffered channel of type T |
| 7703 |
make(T, n) channel buffered channel of type T, buffer size n |
| 7704 |
|
| 7705 |
make(T, n) type parameter see below |
| 7706 |
make(T, n, m) type parameter see below |
| 7707 |
</pre> |
| 7708 |
|
| 7709 |
<p> |
| 7710 |
If the first argument is a <a href="#Type_parameter_declarations">type parameter</a>, |
| 7711 |
all types in its type set must have the same underlying type, which must be a slice |
| 7712 |
or map type, or, if there are channel types, there must only be channel types, they |
| 7713 |
must all have the same element type, and the channel directions must not conflict. |
| 7714 |
</p> |
| 7715 |
|
| 7716 |
<p> |
| 7717 |
Each of the size arguments <code>n</code> and <code>m</code> must be of <a href="#Numeric_types">integer type</a>, |
| 7718 |
have a <a href="#Interface_types">type set</a> containing only integer types, |
| 7719 |
or be an untyped <a href="#Constants">constant</a>. |
| 7720 |
A constant size argument must be non-negative and <a href="#Representability">representable</a> |
| 7721 |
by a value of type <code>int</code>; if it is an untyped constant it is given type <code>int</code>. |
| 7722 |
If both <code>n</code> and <code>m</code> are provided and are constant, then |
| 7723 |
<code>n</code> must be no larger than <code>m</code>. |
| 7724 |
For slices and channels, if <code>n</code> is negative or larger than <code>m</code> at run time, |
| 7725 |
a <a href="#Run_time_panics">run-time panic</a> occurs. |
| 7726 |
</p> |
| 7727 |
|
| 7728 |
<pre> |
| 7729 |
s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100 |
| 7730 |
s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000 |
| 7731 |
s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type int |
| 7732 |
s := make([]int, 10, 0) // illegal: len(s) > cap(s) |
| 7733 |
c := make(chan int, 10) // channel with a buffer size of 10 |
| 7734 |
m := make(map[string]int, 100) // map with initial space for approximately 100 elements |
| 7735 |
</pre> |
| 7736 |
|
| 7737 |
<p> |
| 7738 |
Calling <code>make</code> with a map type and size hint <code>n</code> will |
| 7739 |
create a map with initial space to hold <code>n</code> map elements. |
| 7740 |
The precise behavior is implementation-dependent. |
| 7741 |
</p> |
| 7742 |
|
| 7743 |
|
| 7744 |
<h3 id="Min_and_max">Min and max</h3> |
| 7745 |
|
| 7746 |
<p> |
| 7747 |
The built-in functions <code>min</code> and <code>max</code> compute the |
| 7748 |
smallest—or largest, respectively—value of a fixed number of |
| 7749 |
arguments of <a href="#Comparison_operators">ordered types</a>. |
| 7750 |
There must be at least one argument |
| 7751 |
[<a href="#Go_1.21">Go 1.21</a>]. |
| 7752 |
</p> |
| 7753 |
|
| 7754 |
<p> |
| 7755 |
The same type rules as for <a href="#Operators">operators</a> apply: |
| 7756 |
for <a href="#Comparison_operators">ordered</a> arguments <code>x</code> and |
| 7757 |
<code>y</code>, <code>min(x, y)</code> is valid if <code>x + y</code> is valid, |
| 7758 |
and the type of <code>min(x, y)</code> is the type of <code>x + y</code> |
| 7759 |
(and similarly for <code>max</code>). |
| 7760 |
If all arguments are constant, the result is constant. |
| 7761 |
</p> |
| 7762 |
|
| 7763 |
<pre> |
| 7764 |
var x, y int |
| 7765 |
m := min(x) // m == x |
| 7766 |
m := min(x, y) // m is the smaller of x and y |
| 7767 |
m := max(x, y, 10) // m is the larger of x and y but at least 10 |
| 7768 |
c := max(1, 2.0, 10) // c == 10.0 (floating-point kind) |
| 7769 |
f := max(0, float32(x)) // type of f is float32 |
| 7770 |
var s []string |
| 7771 |
_ = min(s...) // invalid: slice arguments are not permitted |
| 7772 |
t := max("", "foo", "bar") // t == "foo" (string kind) |
| 7773 |
</pre> |
| 7774 |
|
| 7775 |
<p> |
| 7776 |
For numeric arguments, assuming all NaNs are equal, <code>min</code> and <code>max</code> are |
| 7777 |
commutative and associative: |
| 7778 |
</p> |
| 7779 |
|
| 7780 |
<pre> |
| 7781 |
min(x, y) == min(y, x) |
| 7782 |
min(x, y, z) == min(min(x, y), z) == min(x, min(y, z)) |
| 7783 |
</pre> |
| 7784 |
|
| 7785 |
<p> |
| 7786 |
For floating-point arguments negative zero, NaN, and infinity the following rules apply: |
| 7787 |
</p> |
| 7788 |
|
| 7789 |
<pre> |
| 7790 |
x y min(x, y) max(x, y) |
| 7791 |
|
| 7792 |
-0.0 0.0 -0.0 0.0 // negative zero is smaller than (non-negative) zero |
| 7793 |
-Inf y -Inf y // negative infinity is smaller than any other number |
| 7794 |
+Inf y y +Inf // positive infinity is larger than any other number |
| 7795 |
NaN y NaN NaN // if any argument is a NaN, the result is a NaN |
| 7796 |
</pre> |
| 7797 |
|
| 7798 |
<p> |
| 7799 |
For string arguments the result for <code>min</code> is the first argument |
| 7800 |
with the smallest (or for <code>max</code>, largest) value, |
| 7801 |
compared lexically byte-wise: |
| 7802 |
</p> |
| 7803 |
|
| 7804 |
<pre> |
| 7805 |
min(x, y) == if x <= y then x else y |
| 7806 |
min(x, y, z) == min(min(x, y), z) |
| 7807 |
</pre> |
| 7808 |
|
| 7809 |
<h3 id="Allocation">Allocation</h3> |
| 7810 |
|
| 7811 |
<p> |
| 7812 |
The built-in function <code>new</code> creates a new, initialized |
| 7813 |
<a href="#Variables">variable</a> and returns |
| 7814 |
a <a href="#Pointer_types">pointer</a> to it. |
| 7815 |
It accepts a single argument, which may be either a type or an expression. |
| 7816 |
</p> |
| 7817 |
|
| 7818 |
<p> |
| 7819 |
If the argument is a type <code>T</code>, then <code>new(T)</code> |
| 7820 |
allocates a variable of type <code>T</code> initialized to its |
| 7821 |
<a href="#The_zero_value">zero value</a>. |
| 7822 |
</p> |
| 7823 |
|
| 7824 |
<p> |
| 7825 |
If the argument is an expression <code>x</code>, then <code>new(x)</code> |
| 7826 |
allocates a variable of the type of <code>x</code> initialized to the value of <code>x</code>. |
| 7827 |
If that value is an untyped constant, it is first implicitly <a href="#Conversions">converted</a> |
| 7828 |
to its <a href="#Constants">default type</a>; |
| 7829 |
if it is an untyped boolean value, it is first implicitly converted to type bool. |
| 7830 |
The predeclared identifier <code>nil</code> cannot be used as an argument to <code>new</code>. |
| 7831 |
</p> |
| 7832 |
|
| 7833 |
<p> |
| 7834 |
For example, <code>new(int)</code> and <code>new(123)</code> each |
| 7835 |
return a pointer to a new variable of type <code>int</code>. |
| 7836 |
The value of the first variable is <code>0</code>, and the value |
| 7837 |
of the second is <code>123</code>. Similarly |
| 7838 |
</p> |
| 7839 |
|
| 7840 |
<pre> |
| 7841 |
type S struct { a int; b float64 } |
| 7842 |
new(S) |
| 7843 |
</pre> |
| 7844 |
|
| 7845 |
<p> |
| 7846 |
allocates a variable of type <code>S</code>, |
| 7847 |
initializes it (<code>a=0</code>, <code>b=0.0</code>), |
| 7848 |
and returns a value of type <code>*S</code> containing the address |
| 7849 |
of the variable. |
| 7850 |
</p> |
| 7851 |
|
| 7852 |
<h3 id="Handling_panics">Handling panics</h3> |
| 7853 |
|
| 7854 |
<p> Two built-in functions, <code>panic</code> and <code>recover</code>, |
| 7855 |
assist in reporting and handling <a href="#Run_time_panics">run-time panics</a> |
| 7856 |
and program-defined error conditions. |
| 7857 |
</p> |
| 7858 |
|
| 7859 |
<pre class="grammar"> |
| 7860 |
func panic(interface{}) |
| 7861 |
func recover() interface{} |
| 7862 |
</pre> |
| 7863 |
|
| 7864 |
<p> |
| 7865 |
While executing a function <code>F</code>, |
| 7866 |
an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a> |
| 7867 |
terminates the execution of <code>F</code>. |
| 7868 |
Any functions <a href="#Defer_statements">deferred</a> by <code>F</code> |
| 7869 |
are then executed as usual. |
| 7870 |
Next, any deferred functions run by <code>F</code>'s caller are run, |
| 7871 |
and so on up to any deferred by the top-level function in the executing goroutine. |
| 7872 |
At that point, the program is terminated and the error |
| 7873 |
condition is reported, including the value of the argument to <code>panic</code>. |
| 7874 |
This termination sequence is called <i>panicking</i>. |
| 7875 |
</p> |
| 7876 |
|
| 7877 |
<pre> |
| 7878 |
panic(42) |
| 7879 |
panic("unreachable") |
| 7880 |
panic(Error("cannot parse")) |
| 7881 |
</pre> |
| 7882 |
|
| 7883 |
<p> |
| 7884 |
The <code>recover</code> function allows a program to manage behavior |
| 7885 |
of a panicking goroutine. |
| 7886 |
Suppose a function <code>G</code> defers a function <code>D</code> that calls |
| 7887 |
<code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code> |
| 7888 |
is executing. |
| 7889 |
When the running of deferred functions reaches <code>D</code>, |
| 7890 |
the return value of <code>D</code>'s call to <code>recover</code> will be the value passed to the call of <code>panic</code>. |
| 7891 |
If <code>D</code> returns normally, without starting a new |
| 7892 |
<code>panic</code>, the panicking sequence stops. In that case, |
| 7893 |
the state of functions called between <code>G</code> and the call to <code>panic</code> |
| 7894 |
is discarded, and normal execution resumes. |
| 7895 |
Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s |
| 7896 |
execution terminates by returning to its caller. |
| 7897 |
</p> |
| 7898 |
|
| 7899 |
<p> |
| 7900 |
The return value of <code>recover</code> is <code>nil</code> when the |
| 7901 |
goroutine is not panicking or <code>recover</code> was not called directly by a deferred function. |
| 7902 |
Conversely, if a goroutine is panicking and <code>recover</code> was called directly by a deferred function, |
| 7903 |
the return value of <code>recover</code> is guaranteed not to be <code>nil</code>. |
| 7904 |
To ensure this, calling <code>panic</code> with a <code>nil</code> interface value (or an untyped <code>nil</code>) |
| 7905 |
causes a <a href="#Run_time_panics">run-time panic</a>. |
| 7906 |
</p> |
| 7907 |
|
| 7908 |
<p> |
| 7909 |
The <code>protect</code> function in the example below invokes |
| 7910 |
the function argument <code>g</code> and protects callers from |
| 7911 |
run-time panics caused by <code>g</code>. |
| 7912 |
</p> |
| 7913 |
|
| 7914 |
<pre> |
| 7915 |
func protect(g func()) { |
| 7916 |
defer func() { |
| 7917 |
log.Println("done") // Println executes normally even if there is a panic |
| 7918 |
if x := recover(); x != nil { |
| 7919 |
log.Printf("run time panic: %v", x) |
| 7920 |
} |
| 7921 |
}() |
| 7922 |
log.Println("start") |
| 7923 |
g() |
| 7924 |
} |
| 7925 |
</pre> |
| 7926 |
|
| 7927 |
|
| 7928 |
<h3 id="Bootstrapping">Bootstrapping</h3> |
| 7929 |
|
| 7930 |
<p> |
| 7931 |
Current implementations provide several built-in functions useful during |
| 7932 |
bootstrapping. These functions are documented for completeness but are not |
| 7933 |
guaranteed to stay in the language. They do not return a result. |
| 7934 |
</p> |
| 7935 |
|
| 7936 |
<pre class="grammar"> |
| 7937 |
Function Behavior |
| 7938 |
|
| 7939 |
print prints all arguments; formatting of arguments is implementation-specific |
| 7940 |
println like print but prints spaces between arguments and a newline at the end |
| 7941 |
</pre> |
| 7942 |
|
| 7943 |
<p> |
| 7944 |
Implementation restriction: <code>print</code> and <code>println</code> need not |
| 7945 |
accept arbitrary argument types, but printing of boolean, numeric, and string |
| 7946 |
<a href="#Types">types</a> must be supported. |
| 7947 |
</p> |
| 7948 |
|
| 7949 |
|
| 7950 |
<h2 id="Packages">Packages</h2> |
| 7951 |
|
| 7952 |
<p> |
| 7953 |
Go programs are constructed by linking together <i>packages</i>. |
| 7954 |
A package in turn is constructed from one or more source files |
| 7955 |
that together declare constants, types, variables and functions |
| 7956 |
belonging to the package and which are accessible in all files |
| 7957 |
of the same package. Those elements may be |
| 7958 |
<a href="#Exported_identifiers">exported</a> and used in another package. |
| 7959 |
</p> |
| 7960 |
|
| 7961 |
<h3 id="Source_file_organization">Source file organization</h3> |
| 7962 |
|
| 7963 |
<p> |
| 7964 |
Each source file consists of a package clause defining the package |
| 7965 |
to which it belongs, followed by a possibly empty set of import |
| 7966 |
declarations that declare packages whose contents it wishes to use, |
| 7967 |
followed by a possibly empty set of declarations of functions, |
| 7968 |
types, variables, and constants. |
| 7969 |
</p> |
| 7970 |
|
| 7971 |
<pre class="ebnf"> |
| 7972 |
SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } . |
| 7973 |
</pre> |
| 7974 |
|
| 7975 |
<h3 id="Package_clause">Package clause</h3> |
| 7976 |
|
| 7977 |
<p> |
| 7978 |
A package clause begins each source file and defines the package |
| 7979 |
to which the file belongs. |
| 7980 |
</p> |
| 7981 |
|
| 7982 |
<pre class="ebnf"> |
| 7983 |
PackageClause = "package" PackageName . |
| 7984 |
PackageName = identifier . |
| 7985 |
</pre> |
| 7986 |
|
| 7987 |
<p> |
| 7988 |
The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>. |
| 7989 |
</p> |
| 7990 |
|
| 7991 |
<pre> |
| 7992 |
package math |
| 7993 |
</pre> |
| 7994 |
|
| 7995 |
<p> |
| 7996 |
A set of files sharing the same PackageName form the implementation of a package. |
| 7997 |
An implementation may require that all source files for a package inhabit the same directory. |
| 7998 |
</p> |
| 7999 |
|
| 8000 |
<h3 id="Import_declarations">Import declarations</h3> |
| 8001 |
|
| 8002 |
<p> |
| 8003 |
An import declaration states that the source file containing the declaration |
| 8004 |
depends on functionality of the <i>imported</i> package |
| 8005 |
(<a href="#Program_initialization_and_execution">§Program initialization and execution</a>) |
| 8006 |
and enables access to <a href="#Exported_identifiers">exported</a> identifiers |
| 8007 |
of that package. |
| 8008 |
The import names an identifier (PackageName) to be used for access and an ImportPath |
| 8009 |
that specifies the package to be imported. |
| 8010 |
</p> |
| 8011 |
|
| 8012 |
<pre class="ebnf"> |
| 8013 |
ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) . |
| 8014 |
ImportSpec = [ "." | PackageName ] ImportPath . |
| 8015 |
ImportPath = string_lit . |
| 8016 |
</pre> |
| 8017 |
|
| 8018 |
<p> |
| 8019 |
The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a> |
| 8020 |
to access exported identifiers of the package within the importing source file. |
| 8021 |
It is declared in the <a href="#Blocks">file block</a>. |
| 8022 |
If the PackageName is omitted, it defaults to the identifier specified in the |
| 8023 |
<a href="#Package_clause">package clause</a> of the imported package. |
| 8024 |
If an explicit period (<code>.</code>) appears instead of a name, all the |
| 8025 |
package's exported identifiers declared in that package's |
| 8026 |
<a href="#Blocks">package block</a> will be declared in the importing source |
| 8027 |
file's file block and must be accessed without a qualifier. |
| 8028 |
</p> |
| 8029 |
|
| 8030 |
<p> |
| 8031 |
The interpretation of the ImportPath is implementation-dependent but |
| 8032 |
it is typically a substring of the full file name of the compiled |
| 8033 |
package and may be relative to a repository of installed packages. |
| 8034 |
</p> |
| 8035 |
|
| 8036 |
<p> |
| 8037 |
Implementation restriction: A compiler may restrict ImportPaths to |
| 8038 |
non-empty strings using only characters belonging to |
| 8039 |
<a href="https://www.unicode.org/versions/Unicode6.3.0/">Unicode's</a> |
| 8040 |
L, M, N, P, and S general categories (the Graphic characters without |
| 8041 |
spaces) and may also exclude the characters |
| 8042 |
<code>!"#$%&'()*,:;<=>?[\]^`{|}</code> |
| 8043 |
and the Unicode replacement character U+FFFD. |
| 8044 |
</p> |
| 8045 |
|
| 8046 |
<p> |
| 8047 |
Consider a compiled a package containing the package clause |
| 8048 |
<code>package math</code>, which exports function <code>Sin</code>, and |
| 8049 |
installed the compiled package in the file identified by |
| 8050 |
<code>"lib/math"</code>. |
| 8051 |
This table illustrates how <code>Sin</code> is accessed in files |
| 8052 |
that import the package after the |
| 8053 |
various types of import declaration. |
| 8054 |
</p> |
| 8055 |
|
| 8056 |
<pre class="grammar"> |
| 8057 |
Import declaration Local name of Sin |
| 8058 |
|
| 8059 |
import "lib/math" math.Sin |
| 8060 |
import m "lib/math" m.Sin |
| 8061 |
import . "lib/math" Sin |
| 8062 |
</pre> |
| 8063 |
|
| 8064 |
<p> |
| 8065 |
An import declaration declares a dependency relation between |
| 8066 |
the importing and imported package. |
| 8067 |
It is illegal for a package to import itself, directly or indirectly, |
| 8068 |
or to directly import a package without |
| 8069 |
referring to any of its exported identifiers. To import a package solely for |
| 8070 |
its side-effects (initialization), use the <a href="#Blank_identifier">blank</a> |
| 8071 |
identifier as explicit package name: |
| 8072 |
</p> |
| 8073 |
|
| 8074 |
<pre> |
| 8075 |
import _ "lib/math" |
| 8076 |
</pre> |
| 8077 |
|
| 8078 |
|
| 8079 |
<h3 id="An_example_package">An example package</h3> |
| 8080 |
|
| 8081 |
<p> |
| 8082 |
Here is a complete Go package that implements a concurrent prime sieve. |
| 8083 |
</p> |
| 8084 |
|
| 8085 |
<pre> |
| 8086 |
package main |
| 8087 |
|
| 8088 |
import "fmt" |
| 8089 |
|
| 8090 |
// Send the sequence 2, 3, 4, … to channel 'ch'. |
| 8091 |
func generate(ch chan<- int) { |
| 8092 |
for i := 2; ; i++ { |
| 8093 |
ch <- i // Send 'i' to channel 'ch'. |
| 8094 |
} |
| 8095 |
} |
| 8096 |
|
| 8097 |
// Copy the values from channel 'src' to channel 'dst', |
| 8098 |
// removing those divisible by 'prime'. |
| 8099 |
func filter(src <-chan int, dst chan<- int, prime int) { |
| 8100 |
for i := range src { // Loop over values received from 'src'. |
| 8101 |
if i%prime != 0 { |
| 8102 |
dst <- i // Send 'i' to channel 'dst'. |
| 8103 |
} |
| 8104 |
} |
| 8105 |
} |
| 8106 |
|
| 8107 |
// The prime sieve: Daisy-chain filter processes together. |
| 8108 |
func sieve() { |
| 8109 |
ch := make(chan int) // Create a new channel. |
| 8110 |
go generate(ch) // Start generate() as a subprocess. |
| 8111 |
for { |
| 8112 |
prime := <-ch |
| 8113 |
fmt.Print(prime, "\n") |
| 8114 |
ch1 := make(chan int) |
| 8115 |
go filter(ch, ch1, prime) |
| 8116 |
ch = ch1 |
| 8117 |
} |
| 8118 |
} |
| 8119 |
|
| 8120 |
func main() { |
| 8121 |
sieve() |
| 8122 |
} |
| 8123 |
</pre> |
| 8124 |
|
| 8125 |
<h2 id="Program_initialization_and_execution">Program initialization and execution</h2> |
| 8126 |
|
| 8127 |
<h3 id="The_zero_value">The zero value</h3> |
| 8128 |
<p> |
| 8129 |
When storage is allocated for a <a href="#Variables">variable</a>, |
| 8130 |
either through a declaration or a call of <code>new</code>, or when |
| 8131 |
a new value is created, either through a composite literal or a call |
| 8132 |
of <code>make</code>, |
| 8133 |
and no explicit initialization is provided, the variable or value is |
| 8134 |
given a default value. Each element of such a variable or value is |
| 8135 |
set to the <i>zero value</i> for its type: <code>false</code> for booleans, |
| 8136 |
<code>0</code> for numeric types, <code>""</code> |
| 8137 |
for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps. |
| 8138 |
This initialization is done recursively, so for instance each element of an |
| 8139 |
array of structs will have its fields zeroed if no value is specified. |
| 8140 |
</p> |
| 8141 |
<p> |
| 8142 |
These two simple declarations are equivalent: |
| 8143 |
</p> |
| 8144 |
|
| 8145 |
<pre> |
| 8146 |
var i int |
| 8147 |
var i int = 0 |
| 8148 |
</pre> |
| 8149 |
|
| 8150 |
<p> |
| 8151 |
After |
| 8152 |
</p> |
| 8153 |
|
| 8154 |
<pre> |
| 8155 |
type T struct { i int; f float64; next *T } |
| 8156 |
t := new(T) |
| 8157 |
</pre> |
| 8158 |
|
| 8159 |
<p> |
| 8160 |
the following holds: |
| 8161 |
</p> |
| 8162 |
|
| 8163 |
<pre> |
| 8164 |
t.i == 0 |
| 8165 |
t.f == 0.0 |
| 8166 |
t.next == nil |
| 8167 |
</pre> |
| 8168 |
|
| 8169 |
<p> |
| 8170 |
The same would also be true after |
| 8171 |
</p> |
| 8172 |
|
| 8173 |
<pre> |
| 8174 |
var t T |
| 8175 |
</pre> |
| 8176 |
|
| 8177 |
<h3 id="Package_initialization">Package initialization</h3> |
| 8178 |
|
| 8179 |
<p> |
| 8180 |
Within a package, package-level variable initialization proceeds stepwise, |
| 8181 |
with each step selecting the variable earliest in <i>declaration order</i> |
| 8182 |
which has no dependencies on uninitialized variables. |
| 8183 |
</p> |
| 8184 |
|
| 8185 |
<p> |
| 8186 |
More precisely, a package-level variable is considered <i>ready for |
| 8187 |
initialization</i> if it is not yet initialized and either has |
| 8188 |
no <a href="#Variable_declarations">initialization expression</a> or |
| 8189 |
its initialization expression has no <i>dependencies</i> on uninitialized variables. |
| 8190 |
Initialization proceeds by repeatedly initializing the next package-level |
| 8191 |
variable that is earliest in declaration order and ready for initialization, |
| 8192 |
until there are no variables ready for initialization. |
| 8193 |
</p> |
| 8194 |
|
| 8195 |
<p> |
| 8196 |
If any variables are still uninitialized when this |
| 8197 |
process ends, those variables are part of one or more initialization cycles, |
| 8198 |
and the program is not valid. |
| 8199 |
</p> |
| 8200 |
|
| 8201 |
<p> |
| 8202 |
Multiple variables on the left-hand side of a variable declaration initialized |
| 8203 |
by single (multi-valued) expression on the right-hand side are initialized |
| 8204 |
together: If any of the variables on the left-hand side is initialized, all |
| 8205 |
those variables are initialized in the same step. |
| 8206 |
</p> |
| 8207 |
|
| 8208 |
<pre> |
| 8209 |
var x = a |
| 8210 |
var a, b = f() // a and b are initialized together, before x is initialized |
| 8211 |
</pre> |
| 8212 |
|
| 8213 |
<p> |
| 8214 |
For the purpose of package initialization, <a href="#Blank_identifier">blank</a> |
| 8215 |
variables are treated like any other variables in declarations. |
| 8216 |
</p> |
| 8217 |
|
| 8218 |
<p> |
| 8219 |
The declaration order of variables declared in multiple files is determined |
| 8220 |
by the order in which the files are presented to the compiler: Variables |
| 8221 |
declared in the first file are declared before any of the variables declared |
| 8222 |
in the second file, and so on. |
| 8223 |
To ensure reproducible initialization behavior, build systems are encouraged |
| 8224 |
to present multiple files belonging to the same package in lexical file name |
| 8225 |
order to a compiler. |
| 8226 |
</p> |
| 8227 |
|
| 8228 |
<p> |
| 8229 |
Dependency analysis does not rely on the actual values of the |
| 8230 |
variables, only on lexical <i>references</i> to them in the source, |
| 8231 |
analyzed transitively. For instance, if a variable <code>x</code>'s |
| 8232 |
initialization expression refers to a function whose body refers to |
| 8233 |
variable <code>y</code> then <code>x</code> depends on <code>y</code>. |
| 8234 |
Specifically: |
| 8235 |
</p> |
| 8236 |
|
| 8237 |
<ul> |
| 8238 |
<li> |
| 8239 |
A reference to a variable or function is an identifier denoting that |
| 8240 |
variable or function. |
| 8241 |
</li> |
| 8242 |
|
| 8243 |
<li> |
| 8244 |
A reference to a method <code>m</code> is a |
| 8245 |
<a href="#Method_values">method value</a> or |
| 8246 |
<a href="#Method_expressions">method expression</a> of the form |
| 8247 |
<code>t.m</code>, where the (static) type of <code>t</code> is |
| 8248 |
not an interface type, and the method <code>m</code> is in the |
| 8249 |
<a href="#Method_sets">method set</a> of <code>t</code>. |
| 8250 |
It is immaterial whether the resulting function value |
| 8251 |
<code>t.m</code> is invoked. |
| 8252 |
</li> |
| 8253 |
|
| 8254 |
<li> |
| 8255 |
A variable, function, or method <code>x</code> depends on a variable |
| 8256 |
<code>y</code> if <code>x</code>'s initialization expression or body |
| 8257 |
(for functions and methods) contains a reference to <code>y</code> |
| 8258 |
or to a function or method that depends on <code>y</code>. |
| 8259 |
</li> |
| 8260 |
</ul> |
| 8261 |
|
| 8262 |
<p> |
| 8263 |
For example, given the declarations |
| 8264 |
</p> |
| 8265 |
|
| 8266 |
<pre> |
| 8267 |
var ( |
| 8268 |
a = c + b // == 9 |
| 8269 |
b = f() // == 4 |
| 8270 |
c = f() // == 5 |
| 8271 |
d = 3 // == 5 after initialization has finished |
| 8272 |
) |
| 8273 |
|
| 8274 |
func f() int { |
| 8275 |
d++ |
| 8276 |
return d |
| 8277 |
} |
| 8278 |
</pre> |
| 8279 |
|
| 8280 |
<p> |
| 8281 |
the initialization order is <code>d</code>, <code>b</code>, <code>c</code>, <code>a</code>. |
| 8282 |
Note that the order of subexpressions in initialization expressions is irrelevant: |
| 8283 |
<code>a = c + b</code> and <code>a = b + c</code> result in the same initialization |
| 8284 |
order in this example. |
| 8285 |
</p> |
| 8286 |
|
| 8287 |
<p> |
| 8288 |
Dependency analysis is performed per package; only references referring |
| 8289 |
to variables, functions, and (non-interface) methods declared in the current |
| 8290 |
package are considered. If other, hidden, data dependencies exists between |
| 8291 |
variables, the initialization order between those variables is unspecified. |
| 8292 |
</p> |
| 8293 |
|
| 8294 |
<p> |
| 8295 |
For instance, given the declarations |
| 8296 |
</p> |
| 8297 |
|
| 8298 |
<pre> |
| 8299 |
var x = I(T{}).ab() // x has an undetected, hidden dependency on a and b |
| 8300 |
var _ = sideEffect() // unrelated to x, a, or b |
| 8301 |
var a = b |
| 8302 |
var b = 42 |
| 8303 |
|
| 8304 |
type I interface { ab() []int } |
| 8305 |
type T struct{} |
| 8306 |
func (T) ab() []int { return []int{a, b} } |
| 8307 |
</pre> |
| 8308 |
|
| 8309 |
<p> |
| 8310 |
the variable <code>a</code> will be initialized after <code>b</code> but |
| 8311 |
whether <code>x</code> is initialized before <code>b</code>, between |
| 8312 |
<code>b</code> and <code>a</code>, or after <code>a</code>, and |
| 8313 |
thus also the moment at which <code>sideEffect()</code> is called (before |
| 8314 |
or after <code>x</code> is initialized) is not specified. |
| 8315 |
</p> |
| 8316 |
|
| 8317 |
<p> |
| 8318 |
Variables may also be initialized using functions named <code>init</code> |
| 8319 |
declared in the package block, with no arguments and no result parameters. |
| 8320 |
</p> |
| 8321 |
|
| 8322 |
<pre> |
| 8323 |
func init() { … } |
| 8324 |
</pre> |
| 8325 |
|
| 8326 |
<p> |
| 8327 |
Multiple such functions may be defined per package, even within a single |
| 8328 |
source file. In the package block, the <code>init</code> identifier can |
| 8329 |
be used only to declare <code>init</code> functions, yet the identifier |
| 8330 |
itself is not <a href="#Declarations_and_scope">declared</a>. Thus |
| 8331 |
<code>init</code> functions cannot be referred to from anywhere |
| 8332 |
in a program. |
| 8333 |
</p> |
| 8334 |
|
| 8335 |
<p> |
| 8336 |
The entire package is initialized by assigning initial values |
| 8337 |
to all its package-level variables followed by calling |
| 8338 |
all <code>init</code> functions in the order they appear |
| 8339 |
in the source, possibly in multiple files, as presented |
| 8340 |
to the compiler. |
| 8341 |
</p> |
| 8342 |
|
| 8343 |
<h3 id="Program_initialization">Program initialization</h3> |
| 8344 |
|
| 8345 |
<p> |
| 8346 |
The packages of a complete program are initialized stepwise, one package at a time. |
| 8347 |
If a package has imports, the imported packages are initialized |
| 8348 |
before initializing the package itself. If multiple packages import |
| 8349 |
a package, the imported package will be initialized only once. |
| 8350 |
The importing of packages, by construction, guarantees that there |
| 8351 |
can be no cyclic initialization dependencies. |
| 8352 |
More precisely: |
| 8353 |
</p> |
| 8354 |
|
| 8355 |
<p> |
| 8356 |
Given the list of all packages, sorted by import path, in each step the first |
| 8357 |
uninitialized package in the list for which all imported packages (if any) are |
| 8358 |
already initialized is <a href="#Package_initialization">initialized</a>. |
| 8359 |
This step is repeated until all packages are initialized. |
| 8360 |
</p> |
| 8361 |
|
| 8362 |
<p> |
| 8363 |
Package initialization—variable initialization and the invocation of |
| 8364 |
<code>init</code> functions—happens in a single goroutine, |
| 8365 |
sequentially, one package at a time. |
| 8366 |
An <code>init</code> function may launch other goroutines, which can run |
| 8367 |
concurrently with the initialization code. However, initialization |
| 8368 |
always sequences |
| 8369 |
the <code>init</code> functions: it will not invoke the next one |
| 8370 |
until the previous one has returned. |
| 8371 |
</p> |
| 8372 |
|
| 8373 |
<h3 id="Program_execution">Program execution</h3> |
| 8374 |
<p> |
| 8375 |
A complete program is created by linking a single, unimported package |
| 8376 |
called the <i>main package</i> with all the packages it imports, transitively. |
| 8377 |
The main package must |
| 8378 |
have package name <code>main</code> and |
| 8379 |
declare a function <code>main</code> that takes no |
| 8380 |
arguments and returns no value. |
| 8381 |
</p> |
| 8382 |
|
| 8383 |
<pre> |
| 8384 |
func main() { … } |
| 8385 |
</pre> |
| 8386 |
|
| 8387 |
<p> |
| 8388 |
Program execution begins by <a href="#Program_initialization">initializing the program</a> |
| 8389 |
and then invoking the function <code>main</code> in package <code>main</code>. |
| 8390 |
When that function invocation returns, the program exits. |
| 8391 |
It does not wait for other (non-<code>main</code>) goroutines to complete. |
| 8392 |
</p> |
| 8393 |
|
| 8394 |
<h2 id="Errors">Errors</h2> |
| 8395 |
|
| 8396 |
<p> |
| 8397 |
The predeclared type <code>error</code> is defined as |
| 8398 |
</p> |
| 8399 |
|
| 8400 |
<pre> |
| 8401 |
type error interface { |
| 8402 |
Error() string |
| 8403 |
} |
| 8404 |
</pre> |
| 8405 |
|
| 8406 |
<p> |
| 8407 |
It is the conventional interface for representing an error condition, |
| 8408 |
with the nil value representing no error. |
| 8409 |
For instance, a function to read data from a file might be defined: |
| 8410 |
</p> |
| 8411 |
|
| 8412 |
<pre> |
| 8413 |
func Read(f *File, b []byte) (n int, err error) |
| 8414 |
</pre> |
| 8415 |
|
| 8416 |
<h2 id="Run_time_panics">Run-time panics</h2> |
| 8417 |
|
| 8418 |
<p> |
| 8419 |
Execution errors such as attempting to index an array out |
| 8420 |
of bounds trigger a <i>run-time panic</i> equivalent to a call of |
| 8421 |
the built-in function <a href="#Handling_panics"><code>panic</code></a> |
| 8422 |
with a value of the implementation-defined interface type <code>runtime.Error</code>. |
| 8423 |
That type satisfies the predeclared interface type |
| 8424 |
<a href="#Errors"><code>error</code></a>. |
| 8425 |
The exact error values that |
| 8426 |
represent distinct run-time error conditions are unspecified. |
| 8427 |
</p> |
| 8428 |
|
| 8429 |
<pre> |
| 8430 |
package runtime |
| 8431 |
|
| 8432 |
type Error interface { |
| 8433 |
error |
| 8434 |
// and perhaps other methods |
| 8435 |
} |
| 8436 |
</pre> |
| 8437 |
|
| 8438 |
<h2 id="System_considerations">System considerations</h2> |
| 8439 |
|
| 8440 |
<h3 id="Package_unsafe">Package <code>unsafe</code></h3> |
| 8441 |
|
| 8442 |
<p> |
| 8443 |
The built-in package <code>unsafe</code>, known to the compiler |
| 8444 |
and accessible through the <a href="#Import_declarations">import path</a> <code>"unsafe"</code>, |
| 8445 |
provides facilities for low-level programming including operations |
| 8446 |
that violate the type system. A package using <code>unsafe</code> |
| 8447 |
must be vetted manually for type safety and may not be portable. |
| 8448 |
The package provides the following interface: |
| 8449 |
</p> |
| 8450 |
|
| 8451 |
<pre class="grammar"> |
| 8452 |
package unsafe |
| 8453 |
|
| 8454 |
type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type |
| 8455 |
type Pointer *ArbitraryType |
| 8456 |
|
| 8457 |
func Alignof(variable ArbitraryType) uintptr |
| 8458 |
func Offsetof(selector ArbitraryType) uintptr |
| 8459 |
func Sizeof(variable ArbitraryType) uintptr |
| 8460 |
|
| 8461 |
type IntegerType int // shorthand for an integer type; it is not a real type |
| 8462 |
func Add(ptr Pointer, len IntegerType) Pointer |
| 8463 |
func Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryType |
| 8464 |
func SliceData(slice []ArbitraryType) *ArbitraryType |
| 8465 |
func String(ptr *byte, len IntegerType) string |
| 8466 |
func StringData(str string) *byte |
| 8467 |
</pre> |
| 8468 |
|
| 8469 |
<p> |
| 8470 |
A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code> |
| 8471 |
value may not be <a href="#Address_operators">dereferenced</a>. |
| 8472 |
Any pointer or value of <a href="#Underlying_types">underlying type</a> <code>uintptr</code> can be |
| 8473 |
<a href="#Conversions">converted</a> to a type of underlying type <code>Pointer</code> and vice versa. |
| 8474 |
If the respective types are <a href="#Type_parameter_declarations">type parameters</a>, all types in |
| 8475 |
their respective type sets must have the same underlying type, which must be <code>uintptr</code> and |
| 8476 |
<code>Pointer</code>, respectively. |
| 8477 |
The effect of converting between <code>Pointer</code> and <code>uintptr</code> is implementation-defined. |
| 8478 |
</p> |
| 8479 |
|
| 8480 |
<pre> |
| 8481 |
var f float64 |
| 8482 |
bits = *(*uint64)(unsafe.Pointer(&f)) |
| 8483 |
|
| 8484 |
type ptr unsafe.Pointer |
| 8485 |
bits = *(*uint64)(ptr(&f)) |
| 8486 |
|
| 8487 |
func f[P ~*B, B any](p P) uintptr { |
| 8488 |
return uintptr(unsafe.Pointer(p)) |
| 8489 |
} |
| 8490 |
|
| 8491 |
var p ptr = nil |
| 8492 |
</pre> |
| 8493 |
|
| 8494 |
<p> |
| 8495 |
The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code> |
| 8496 |
of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code> |
| 8497 |
as if <code>v</code> were declared via <code>var v = x</code>. |
| 8498 |
</p> |
| 8499 |
<p> |
| 8500 |
The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a> |
| 8501 |
<code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code> |
| 8502 |
or <code>*s</code>, and returns the field offset in bytes relative to the struct's address. |
| 8503 |
If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable |
| 8504 |
without pointer indirections through fields of the struct. |
| 8505 |
For a struct <code>s</code> with field <code>f</code>: |
| 8506 |
</p> |
| 8507 |
|
| 8508 |
<pre> |
| 8509 |
uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&s.f)) |
| 8510 |
</pre> |
| 8511 |
|
| 8512 |
<p> |
| 8513 |
Computer architectures may require memory addresses to be <i>aligned</i>; |
| 8514 |
that is, for addresses of a variable to be a multiple of a factor, |
| 8515 |
the variable's type's <i>alignment</i>. The function <code>Alignof</code> |
| 8516 |
takes an expression denoting a variable of any type and returns the |
| 8517 |
alignment of the (type of the) variable in bytes. For a variable |
| 8518 |
<code>x</code>: |
| 8519 |
</p> |
| 8520 |
|
| 8521 |
<pre> |
| 8522 |
uintptr(unsafe.Pointer(&x)) % unsafe.Alignof(x) == 0 |
| 8523 |
</pre> |
| 8524 |
|
| 8525 |
<p> |
| 8526 |
A (variable of) type <code>T</code> has <i>variable size</i> if <code>T</code> |
| 8527 |
is a <a href="#Type_parameter_declarations">type parameter</a>, or if it is an |
| 8528 |
array or struct type containing elements |
| 8529 |
or fields of variable size. Otherwise the size is <i>constant</i>. |
| 8530 |
Calls to <code>Alignof</code>, <code>Offsetof</code>, and <code>Sizeof</code> |
| 8531 |
are compile-time <a href="#Constant_expressions">constant expressions</a> of |
| 8532 |
type <code>uintptr</code> if their arguments (or the struct <code>s</code> in |
| 8533 |
the selector expression <code>s.f</code> for <code>Offsetof</code>) are types |
| 8534 |
of constant size. |
| 8535 |
</p> |
| 8536 |
|
| 8537 |
<p> |
| 8538 |
The function <code>Add</code> adds <code>len</code> to <code>ptr</code> |
| 8539 |
and returns the updated pointer <code>unsafe.Pointer(uintptr(ptr) + uintptr(len))</code> |
| 8540 |
[<a href="#Go_1.17">Go 1.17</a>]. |
| 8541 |
The <code>len</code> argument must be of <a href="#Numeric_types">integer type</a> or an untyped <a href="#Constants">constant</a>. |
| 8542 |
A constant <code>len</code> argument must be <a href="#Representability">representable</a> by a value of type <code>int</code>; |
| 8543 |
if it is an untyped constant it is given type <code>int</code>. |
| 8544 |
The rules for <a href="/pkg/unsafe#Pointer">valid uses</a> of <code>Pointer</code> still apply. |
| 8545 |
</p> |
| 8546 |
|
| 8547 |
<p> |
| 8548 |
The function <code>Slice</code> returns a slice whose underlying array starts at <code>ptr</code> |
| 8549 |
and whose length and capacity are <code>len</code>. |
| 8550 |
<code>Slice(ptr, len)</code> is equivalent to |
| 8551 |
</p> |
| 8552 |
|
| 8553 |
<pre> |
| 8554 |
(*[len]ArbitraryType)(unsafe.Pointer(ptr))[:] |
| 8555 |
</pre> |
| 8556 |
|
| 8557 |
<p> |
| 8558 |
except that, as a special case, if <code>ptr</code> |
| 8559 |
is <code>nil</code> and <code>len</code> is zero, |
| 8560 |
<code>Slice</code> returns <code>nil</code> |
| 8561 |
[<a href="#Go_1.17">Go 1.17</a>]. |
| 8562 |
</p> |
| 8563 |
|
| 8564 |
<p> |
| 8565 |
The <code>len</code> argument must be of <a href="#Numeric_types">integer type</a> or an untyped <a href="#Constants">constant</a>. |
| 8566 |
A constant <code>len</code> argument must be non-negative and <a href="#Representability">representable</a> by a value of type <code>int</code>; |
| 8567 |
if it is an untyped constant it is given type <code>int</code>. |
| 8568 |
At run time, if <code>len</code> is negative, |
| 8569 |
or if <code>ptr</code> is <code>nil</code> and <code>len</code> is not zero, |
| 8570 |
a <a href="#Run_time_panics">run-time panic</a> occurs |
| 8571 |
[<a href="#Go_1.17">Go 1.17</a>]. |
| 8572 |
</p> |
| 8573 |
|
| 8574 |
<p> |
| 8575 |
The function <code>SliceData</code> returns a pointer to the underlying array of the <code>slice</code> argument. |
| 8576 |
If the slice's capacity <code>cap(slice)</code> is not zero, that pointer is <code>&slice[:1][0]</code>. |
| 8577 |
If <code>slice</code> is <code>nil</code>, the result is <code>nil</code>. |
| 8578 |
Otherwise it is a non-<code>nil</code> pointer to an unspecified memory address |
| 8579 |
[<a href="#Go_1.20">Go 1.20</a>]. |
| 8580 |
</p> |
| 8581 |
|
| 8582 |
<p> |
| 8583 |
The function <code>String</code> returns a <code>string</code> value whose underlying bytes start at |
| 8584 |
<code>ptr</code> and whose length is <code>len</code>. |
| 8585 |
The same requirements apply to the <code>ptr</code> and <code>len</code> argument as in the function |
| 8586 |
<code>Slice</code>. If <code>len</code> is zero, the result is the empty string <code>""</code>. |
| 8587 |
Since Go strings are immutable, the bytes passed to <code>String</code> must not be modified afterwards. |
| 8588 |
[<a href="#Go_1.20">Go 1.20</a>] |
| 8589 |
</p> |
| 8590 |
|
| 8591 |
<p> |
| 8592 |
The function <code>StringData</code> returns a pointer to the underlying bytes of the <code>str</code> argument. |
| 8593 |
For an empty string the return value is unspecified, and may be <code>nil</code>. |
| 8594 |
Since Go strings are immutable, the bytes returned by <code>StringData</code> must not be modified |
| 8595 |
[<a href="#Go_1.20">Go 1.20</a>]. |
| 8596 |
</p> |
| 8597 |
|
| 8598 |
<h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3> |
| 8599 |
|
| 8600 |
<p> |
| 8601 |
For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed: |
| 8602 |
</p> |
| 8603 |
|
| 8604 |
<pre class="grammar"> |
| 8605 |
type size in bytes |
| 8606 |
|
| 8607 |
byte, uint8, int8 1 |
| 8608 |
uint16, int16 2 |
| 8609 |
uint32, int32, float32 4 |
| 8610 |
uint64, int64, float64, complex64 8 |
| 8611 |
complex128 16 |
| 8612 |
</pre> |
| 8613 |
|
| 8614 |
<p> |
| 8615 |
The following minimal alignment properties are guaranteed: |
| 8616 |
</p> |
| 8617 |
<ol> |
| 8618 |
<li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1. |
| 8619 |
</li> |
| 8620 |
|
| 8621 |
<li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of |
| 8622 |
all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1. |
| 8623 |
</li> |
| 8624 |
|
| 8625 |
<li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as |
| 8626 |
the alignment of a variable of the array's element type. |
| 8627 |
</li> |
| 8628 |
</ol> |
| 8629 |
|
| 8630 |
<p> |
| 8631 |
A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero. Two distinct zero-size variables may have the same address in memory. |
| 8632 |
</p> |
| 8633 |
|
| 8634 |
<h2 id="Appendix">Appendix</h2> |
| 8635 |
|
| 8636 |
<h3 id="Language_versions">Language versions</h3> |
| 8637 |
|
| 8638 |
<p> |
| 8639 |
The <a href="/doc/go1compat">Go 1 compatibility guarantee</a> ensures that |
| 8640 |
programs written to the Go 1 specification will continue to compile and run |
| 8641 |
correctly, unchanged, over the lifetime of that specification. |
| 8642 |
More generally, as adjustments are made and features added to the language, |
| 8643 |
the compatibility guarantee ensures that a Go program that works with a |
| 8644 |
specific Go language version will continue to work with any subsequent version. |
| 8645 |
</p> |
| 8646 |
|
| 8647 |
<p> |
| 8648 |
For instance, the ability to use the prefix <code>0b</code> for binary |
| 8649 |
integer literals was introduced with Go 1.13, indicated |
| 8650 |
by [<a href="#Go_1.13">Go 1.13</a>] in the section on |
| 8651 |
<a href="#Integer_literals">integer literals</a>. |
| 8652 |
Source code containing an integer literal such as <code>0b1011</code> |
| 8653 |
will be rejected if the implied or required language version used by |
| 8654 |
the compiler is older than Go 1.13. |
| 8655 |
</p> |
| 8656 |
|
| 8657 |
<p> |
| 8658 |
The following table describes the minimum language version required for |
| 8659 |
features introduced after Go 1. |
| 8660 |
</p> |
| 8661 |
|
| 8662 |
<h4 id="Go_1.9">Go 1.9</h4> |
| 8663 |
<ul> |
| 8664 |
<li> |
| 8665 |
An <a href="#Alias_declarations">alias declaration</a> may be used to declare an alias name for a type. |
| 8666 |
</li> |
| 8667 |
</ul> |
| 8668 |
|
| 8669 |
<h4 id="Go_1.13">Go 1.13</h4> |
| 8670 |
<ul> |
| 8671 |
<li> |
| 8672 |
<a href="#Integer_literals">Integer literals</a> may use the prefixes <code>0b</code>, <code>0B</code>, <code>0o</code>, |
| 8673 |
and <code>0O</code> for binary, and octal literals, respectively. |
| 8674 |
</li> |
| 8675 |
<li> |
| 8676 |
Hexadecimal <a href="#Floating-point_literals">floating-point literals</a> may be written using the prefixes |
| 8677 |
<code>0x</code> and <code>0X</code>. |
| 8678 |
</li> |
| 8679 |
<li> |
| 8680 |
The <a href="#Imaginary_literals">imaginary suffix</a> <code>i</code> may be used with any (binary, decimal, hexadecimal) |
| 8681 |
integer or floating-point literal, not just decimal literals. |
| 8682 |
</li> |
| 8683 |
<li> |
| 8684 |
The digits of any number literal may be <a href="#Integer_literals">separated</a> (grouped) |
| 8685 |
using underscores <code>_</code>. |
| 8686 |
</li> |
| 8687 |
<li> |
| 8688 |
The shift count in a <a href="#Operators">shift operation</a> may be a signed integer type. |
| 8689 |
</li> |
| 8690 |
</ul> |
| 8691 |
|
| 8692 |
<h4 id="Go_1.14">Go 1.14</h4> |
| 8693 |
<ul> |
| 8694 |
<li> |
| 8695 |
Emdedding a method more than once through different <a href="#Embedded_interfaces">embedded interfaces</a> |
| 8696 |
is not an error. |
| 8697 |
</li> |
| 8698 |
</ul> |
| 8699 |
|
| 8700 |
<h4 id="Go_1.17">Go 1.17</h4> |
| 8701 |
<ul> |
| 8702 |
<li> |
| 8703 |
A slice may be <a href="#Conversions">converted</a> to an array pointer if the slice and array element |
| 8704 |
types match, and the array is not longer than the slice. |
| 8705 |
</li> |
| 8706 |
<li> |
| 8707 |
The built-in <a href="#Package_unsafe">package <code>unsafe</code></a> includes the new functions |
| 8708 |
<code>Add</code> and <code>Slice</code>. |
| 8709 |
</li> |
| 8710 |
</ul> |
| 8711 |
|
| 8712 |
<h4 id="Go_1.18">Go 1.18</h4> |
| 8713 |
<p> |
| 8714 |
The 1.18 release adds polymorphic functions and types ("generics") to the language. |
| 8715 |
Specifically: |
| 8716 |
</p> |
| 8717 |
<ul> |
| 8718 |
<li> |
| 8719 |
The set of <a href="#Operators_and_punctuation">operators and punctuation</a> includes the new token <code>~</code>. |
| 8720 |
</li> |
| 8721 |
<li> |
| 8722 |
Function and type declarations may declare <a href="#Type_parameter_declarations">type parameters</a>. |
| 8723 |
</li> |
| 8724 |
<li> |
| 8725 |
Interface types may <a href="#General_interfaces">embed arbitrary types</a> (not just type names of interfaces) |
| 8726 |
as well as union and <code>~T</code> type elements. |
| 8727 |
</li> |
| 8728 |
<li> |
| 8729 |
The set of <a href="#Predeclared_identifiers">predeclared</a> types includes the new types |
| 8730 |
<code>any</code> and <code>comparable</code>. |
| 8731 |
</li> |
| 8732 |
</ul> |
| 8733 |
|
| 8734 |
<h4 id="Go_1.20">Go 1.20</h4> |
| 8735 |
<ul> |
| 8736 |
<li> |
| 8737 |
A slice may be <a href="#Conversions">converted</a> to an array if the slice and array element |
| 8738 |
types match and the array is not longer than the slice. |
| 8739 |
</li> |
| 8740 |
<li> |
| 8741 |
The built-in <a href="#Package_unsafe">package <code>unsafe</code></a> includes the new functions |
| 8742 |
<code>SliceData</code>, <code>String</code>, and <code>StringData</code>. |
| 8743 |
</li> |
| 8744 |
<li> |
| 8745 |
<a href="#Comparison_operators">Comparable types</a> (such as ordinary interfaces) may satisfy |
| 8746 |
<code>comparable</code> constraints, even if the type arguments are not strictly comparable. |
| 8747 |
</li> |
| 8748 |
</ul> |
| 8749 |
|
| 8750 |
<h4 id="Go_1.21">Go 1.21</h4> |
| 8751 |
<ul> |
| 8752 |
<li> |
| 8753 |
The set of <a href="#Predeclared_identifiers">predeclared</a> functions includes the new functions |
| 8754 |
<code>min</code>, <code>max</code>, and <code>clear</code>. |
| 8755 |
</li> |
| 8756 |
<li> |
| 8757 |
<a href="#Type_inference">Type inference</a> uses the types of interface methods for inference. |
| 8758 |
It also infers type arguments for generic functions assigned to variables or |
| 8759 |
passed as arguments to other (possibly generic) functions. |
| 8760 |
</li> |
| 8761 |
</ul> |
| 8762 |
|
| 8763 |
<h4 id="Go_1.22">Go 1.22</h4> |
| 8764 |
<ul> |
| 8765 |
<li> |
| 8766 |
In a <a href="#For_statements">"for" statement</a>, each iteration has its own set of iteration |
| 8767 |
variables rather than sharing the same variables in each iteration. |
| 8768 |
</li> |
| 8769 |
<li> |
| 8770 |
A "for" statement with <a href="#For_range">"range" clause</a> may iterate over |
| 8771 |
integer values from zero to an upper limit. |
| 8772 |
</li> |
| 8773 |
</ul> |
| 8774 |
|
| 8775 |
<h4 id="Go_1.23">Go 1.23</h4> |
| 8776 |
<ul> |
| 8777 |
<li>A "for" statement with <a href="#For_range">"range" clause</a> accepts an iterator |
| 8778 |
function as range expression. |
| 8779 |
</li> |
| 8780 |
</ul> |
| 8781 |
|
| 8782 |
<h4 id="Go_1.24">Go 1.24</h4> |
| 8783 |
<ul> |
| 8784 |
<li> |
| 8785 |
An <a href="#Alias_declarations">alias declaration</a> may declare |
| 8786 |
<a href="#Type_parameter_declarations">type parameters</a>. |
| 8787 |
</li> |
| 8788 |
</ul> |
| 8789 |
|
| 8790 |
<h3 id="Type_unification_rules">Type unification rules</h3> |
| 8791 |
|
| 8792 |
<p> |
| 8793 |
The type unification rules describe if and how two types unify. |
| 8794 |
The precise details are relevant for Go implementations, |
| 8795 |
affect the specifics of error messages (such as whether |
| 8796 |
a compiler reports a type inference or other error), |
| 8797 |
and may explain why type inference fails in unusual code situations. |
| 8798 |
But by and large these rules can be ignored when writing Go code: |
| 8799 |
type inference is designed to mostly "work as expected", |
| 8800 |
and the unification rules are fine-tuned accordingly. |
| 8801 |
</p> |
| 8802 |
|
| 8803 |
<p> |
| 8804 |
Type unification is controlled by a <i>matching mode</i>, which may |
| 8805 |
be <i>exact</i> or <i>loose</i>. |
| 8806 |
As unification recursively descends a composite type structure, |
| 8807 |
the matching mode used for elements of the type, the <i>element matching mode</i>, |
| 8808 |
remains the same as the matching mode except when two types are unified for |
| 8809 |
<a href="#Assignability">assignability</a> (<code>≡<sub>A</sub></code>): |
| 8810 |
in this case, the matching mode is <i>loose</i> at the top level but |
| 8811 |
then changes to <i>exact</i> for element types, reflecting the fact |
| 8812 |
that types don't have to be identical to be assignable. |
| 8813 |
</p> |
| 8814 |
|
| 8815 |
<p> |
| 8816 |
Two types that are not bound type parameters unify exactly if any of |
| 8817 |
following conditions is true: |
| 8818 |
</p> |
| 8819 |
|
| 8820 |
<ul> |
| 8821 |
<li> |
| 8822 |
Both types are <a href="#Type_identity">identical</a>. |
| 8823 |
</li> |
| 8824 |
<li> |
| 8825 |
Both types have identical structure and their element types |
| 8826 |
unify exactly. |
| 8827 |
</li> |
| 8828 |
<li> |
| 8829 |
Exactly one type is an <a href="#Type_inference">unbound</a> |
| 8830 |
type parameter, and all the types in its type set unify with |
| 8831 |
the other type |
| 8832 |
per the unification rules for <code>≡<sub>A</sub></code> |
| 8833 |
(loose unification at the top level and exact unification |
| 8834 |
for element types). |
| 8835 |
</li> |
| 8836 |
</ul> |
| 8837 |
|
| 8838 |
<p> |
| 8839 |
If both types are bound type parameters, they unify per the given |
| 8840 |
matching modes if: |
| 8841 |
</p> |
| 8842 |
|
| 8843 |
<ul> |
| 8844 |
<li> |
| 8845 |
Both type parameters are identical. |
| 8846 |
</li> |
| 8847 |
<li> |
| 8848 |
At most one of the type parameters has a known type argument. |
| 8849 |
In this case, the type parameters are <i>joined</i>: |
| 8850 |
they both stand for the same type argument. |
| 8851 |
If neither type parameter has a known type argument yet, |
| 8852 |
a future type argument inferred for one the type parameters |
| 8853 |
is simultaneously inferred for both of them. |
| 8854 |
</li> |
| 8855 |
<li> |
| 8856 |
Both type parameters have a known type argument |
| 8857 |
and the type arguments unify per the given matching modes. |
| 8858 |
</li> |
| 8859 |
</ul> |
| 8860 |
|
| 8861 |
<p> |
| 8862 |
A single bound type parameter <code>P</code> and another type <code>T</code> unify |
| 8863 |
per the given matching modes if: |
| 8864 |
</p> |
| 8865 |
|
| 8866 |
<ul> |
| 8867 |
<li> |
| 8868 |
<code>P</code> doesn't have a known type argument. |
| 8869 |
In this case, <code>T</code> is inferred as the type argument for <code>P</code>. |
| 8870 |
</li> |
| 8871 |
<li> |
| 8872 |
<code>P</code> does have a known type argument <code>A</code>, |
| 8873 |
<code>A</code> and <code>T</code> unify per the given matching modes, |
| 8874 |
and one of the following conditions is true: |
| 8875 |
<ul> |
| 8876 |
<li> |
| 8877 |
Both <code>A</code> and <code>T</code> are interface types: |
| 8878 |
In this case, if both <code>A</code> and <code>T</code> are |
| 8879 |
also <a href="#Type_definitions">defined</a> types, |
| 8880 |
they must be <a href="#Type_identity">identical</a>. |
| 8881 |
Otherwise, if neither of them is a defined type, they must |
| 8882 |
have the same number of methods |
| 8883 |
(unification of <code>A</code> and <code>T</code> already |
| 8884 |
established that the methods match). |
| 8885 |
</li> |
| 8886 |
<li> |
| 8887 |
Neither <code>A</code> nor <code>T</code> are interface types: |
| 8888 |
In this case, if <code>T</code> is a defined type, <code>T</code> |
| 8889 |
replaces <code>A</code> as the inferred type argument for <code>P</code>. |
| 8890 |
</li> |
| 8891 |
</ul> |
| 8892 |
</li> |
| 8893 |
</ul> |
| 8894 |
|
| 8895 |
<p> |
| 8896 |
Finally, two types that are not bound type parameters unify loosely |
| 8897 |
(and per the element matching mode) if: |
| 8898 |
</p> |
| 8899 |
|
| 8900 |
<ul> |
| 8901 |
<li> |
| 8902 |
Both types unify exactly. |
| 8903 |
</li> |
| 8904 |
<li> |
| 8905 |
One type is a <a href="#Type_definitions">defined type</a>, |
| 8906 |
the other type is a type literal, but not an interface, |
| 8907 |
and their underlying types unify per the element matching mode. |
| 8908 |
</li> |
| 8909 |
<li> |
| 8910 |
Both types are interfaces (but not type parameters) with |
| 8911 |
identical <a href="#Interface_types">type terms</a>, |
| 8912 |
both or neither embed the predeclared type |
| 8913 |
<a href="#Predeclared_identifiers">comparable</a>, |
| 8914 |
corresponding method types unify exactly, |
| 8915 |
and the method set of one of the interfaces is a subset of |
| 8916 |
the method set of the other interface. |
| 8917 |
</li> |
| 8918 |
<li> |
| 8919 |
Only one type is an interface (but not a type parameter), |
| 8920 |
corresponding methods of the two types unify per the element matching mode, |
| 8921 |
and the method set of the interface is a subset of |
| 8922 |
the method set of the other type. |
| 8923 |
</li> |
| 8924 |
<li> |
| 8925 |
Both types have the same structure and their element types |
| 8926 |
unify per the element matching mode. |
| 8927 |
</li> |
| 8928 |
</ul> |