github.com/stingnevermore/go@v0.0.0-20180120041312-3810f5bfed72/doc/go_spec.html (about) 1 <!--{ 2 "Title": "The Go Programming Language Specification", 3 "Subtitle": "Version of January 17, 2018", 4 "Path": "/ref/spec" 5 }--> 6 7 <h2 id="Introduction">Introduction</h2> 8 9 <p> 10 This is a reference manual for the Go programming language. For 11 more information and other documents, see <a href="/">golang.org</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 grammar is compact and regular, allowing for easy analysis by 24 automatic tools such as integrated development environments. 25 </p> 26 27 <h2 id="Notation">Notation</h2> 28 <p> 29 The syntax is specified using Extended Backus-Naur Form (EBNF): 30 </p> 31 32 <pre class="grammar"> 33 Production = production_name "=" [ Expression ] "." . 34 Expression = Alternative { "|" Alternative } . 35 Alternative = Term { Term } . 36 Term = production_name | token [ "…" token ] | Group | Option | Repetition . 37 Group = "(" Expression ")" . 38 Option = "[" Expression "]" . 39 Repetition = "{" Expression "}" . 40 </pre> 41 42 <p> 43 Productions are expressions constructed from terms and the following 44 operators, in increasing precedence: 45 </p> 46 <pre class="grammar"> 47 | alternation 48 () grouping 49 [] option (0 or 1 times) 50 {} repetition (0 to n times) 51 </pre> 52 53 <p> 54 Lower-case production names are used to identify lexical tokens. 55 Non-terminals are in CamelCase. Lexical tokens are enclosed in 56 double quotes <code>""</code> or back quotes <code>``</code>. 57 </p> 58 59 <p> 60 The form <code>a … b</code> represents the set of characters from 61 <code>a</code> through <code>b</code> as alternatives. The horizontal 62 ellipsis <code>…</code> is also used elsewhere in the spec to informally denote various 63 enumerations or code snippets that are not further specified. The character <code>…</code> 64 (as opposed to the three characters <code>...</code>) is not a token of the Go 65 language. 66 </p> 67 68 <h2 id="Source_code_representation">Source code representation</h2> 69 70 <p> 71 Source code is Unicode text encoded in 72 <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. The text is not 73 canonicalized, so a single accented code point is distinct from the 74 same character constructed from combining an accent and a letter; 75 those are treated as two code points. For simplicity, this document 76 will use the unqualified term <i>character</i> to refer to a Unicode code point 77 in the source text. 78 </p> 79 <p> 80 Each code point is distinct; for instance, upper and lower case letters 81 are different characters. 82 </p> 83 <p> 84 Implementation restriction: For compatibility with other tools, a 85 compiler may disallow the NUL character (U+0000) in the source text. 86 </p> 87 <p> 88 Implementation restriction: For compatibility with other tools, a 89 compiler may ignore a UTF-8-encoded byte order mark 90 (U+FEFF) if it is the first Unicode code point in the source text. 91 A byte order mark may be disallowed anywhere else in the source. 92 </p> 93 94 <h3 id="Characters">Characters</h3> 95 96 <p> 97 The following terms are used to denote specific Unicode character classes: 98 </p> 99 <pre class="ebnf"> 100 newline = /* the Unicode code point U+000A */ . 101 unicode_char = /* an arbitrary Unicode code point except newline */ . 102 unicode_letter = /* a Unicode code point classified as "Letter" */ . 103 unicode_digit = /* a Unicode code point classified as "Number, decimal digit" */ . 104 </pre> 105 106 <p> 107 In <a href="http://www.unicode.org/versions/Unicode8.0.0/">The Unicode Standard 8.0</a>, 108 Section 4.5 "General Category" defines a set of character categories. 109 Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo 110 as Unicode letters, and those in the Number category Nd as Unicode digits. 111 </p> 112 113 <h3 id="Letters_and_digits">Letters and digits</h3> 114 115 <p> 116 The underscore character <code>_</code> (U+005F) is considered a letter. 117 </p> 118 <pre class="ebnf"> 119 letter = unicode_letter | "_" . 120 decimal_digit = "0" … "9" . 121 octal_digit = "0" … "7" . 122 hex_digit = "0" … "9" | "A" … "F" | "a" … "f" . 123 </pre> 124 125 <h2 id="Lexical_elements">Lexical elements</h2> 126 127 <h3 id="Comments">Comments</h3> 128 129 <p> 130 Comments serve as program documentation. There are two forms: 131 </p> 132 133 <ol> 134 <li> 135 <i>Line comments</i> start with the character sequence <code>//</code> 136 and stop at the end of the line. 137 </li> 138 <li> 139 <i>General comments</i> start with the character sequence <code>/*</code> 140 and stop with the first subsequent character sequence <code>*/</code>. 141 </li> 142 </ol> 143 144 <p> 145 A comment cannot start inside a <a href="#Rune_literals">rune</a> or 146 <a href="#String_literals">string literal</a>, or inside a comment. 147 A general comment containing no newlines acts like a space. 148 Any other comment acts like a newline. 149 </p> 150 151 <h3 id="Tokens">Tokens</h3> 152 153 <p> 154 Tokens form the vocabulary of the Go language. 155 There are four classes: <i>identifiers</i>, <i>keywords</i>, <i>operators 156 and punctuation</i>, and <i>literals</i>. <i>White space</i>, formed from 157 spaces (U+0020), horizontal tabs (U+0009), 158 carriage returns (U+000D), and newlines (U+000A), 159 is ignored except as it separates tokens 160 that would otherwise combine into a single token. Also, a newline or end of file 161 may trigger the insertion of a <a href="#Semicolons">semicolon</a>. 162 While breaking the input into tokens, 163 the next token is the longest sequence of characters that form a 164 valid token. 165 </p> 166 167 <h3 id="Semicolons">Semicolons</h3> 168 169 <p> 170 The formal grammar uses semicolons <code>";"</code> as terminators in 171 a number of productions. Go programs may omit most of these semicolons 172 using the following two rules: 173 </p> 174 175 <ol> 176 <li> 177 When the input is broken into tokens, a semicolon is automatically inserted 178 into the token stream immediately after a line's final token if that token is 179 <ul> 180 <li>an 181 <a href="#Identifiers">identifier</a> 182 </li> 183 184 <li>an 185 <a href="#Integer_literals">integer</a>, 186 <a href="#Floating-point_literals">floating-point</a>, 187 <a href="#Imaginary_literals">imaginary</a>, 188 <a href="#Rune_literals">rune</a>, or 189 <a href="#String_literals">string</a> literal 190 </li> 191 192 <li>one of the <a href="#Keywords">keywords</a> 193 <code>break</code>, 194 <code>continue</code>, 195 <code>fallthrough</code>, or 196 <code>return</code> 197 </li> 198 199 <li>one of the <a href="#Operators_and_punctuation">operators and punctuation</a> 200 <code>++</code>, 201 <code>--</code>, 202 <code>)</code>, 203 <code>]</code>, or 204 <code>}</code> 205 </li> 206 </ul> 207 </li> 208 209 <li> 210 To allow complex statements to occupy a single line, a semicolon 211 may be omitted before a closing <code>")"</code> or <code>"}"</code>. 212 </li> 213 </ol> 214 215 <p> 216 To reflect idiomatic use, code examples in this document elide semicolons 217 using these rules. 218 </p> 219 220 221 <h3 id="Identifiers">Identifiers</h3> 222 223 <p> 224 Identifiers name program entities such as variables and types. 225 An identifier is a sequence of one or more letters and digits. 226 The first character in an identifier must be a letter. 227 </p> 228 <pre class="ebnf"> 229 identifier = letter { letter | unicode_digit } . 230 </pre> 231 <pre> 232 a 233 _x9 234 ThisVariableIsExported 235 αβ 236 </pre> 237 238 <p> 239 Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>. 240 </p> 241 242 243 <h3 id="Keywords">Keywords</h3> 244 245 <p> 246 The following keywords are reserved and may not be used as identifiers. 247 </p> 248 <pre class="grammar"> 249 break default func interface select 250 case defer go map struct 251 chan else goto package switch 252 const fallthrough if range type 253 continue for import return var 254 </pre> 255 256 <h3 id="Operators_and_punctuation">Operators and punctuation</h3> 257 258 <p> 259 The following character sequences represent <a href="#Operators">operators</a> 260 (including <a href="#assign_op">assignment operators</a>) and punctuation: 261 </p> 262 <pre class="grammar"> 263 + & += &= && == != ( ) 264 - | -= |= || < <= [ ] 265 * ^ *= ^= <- > >= { } 266 / << /= <<= ++ = := , ; 267 % >> %= >>= -- ! ... . : 268 &^ &^= 269 </pre> 270 271 <h3 id="Integer_literals">Integer literals</h3> 272 273 <p> 274 An integer literal is a sequence of digits representing an 275 <a href="#Constants">integer constant</a>. 276 An optional prefix sets a non-decimal base: <code>0</code> for octal, <code>0x</code> or 277 <code>0X</code> for hexadecimal. In hexadecimal literals, letters 278 <code>a-f</code> and <code>A-F</code> represent values 10 through 15. 279 </p> 280 <pre class="ebnf"> 281 int_lit = decimal_lit | octal_lit | hex_lit . 282 decimal_lit = ( "1" … "9" ) { decimal_digit } . 283 octal_lit = "0" { octal_digit } . 284 hex_lit = "0" ( "x" | "X" ) hex_digit { hex_digit } . 285 </pre> 286 287 <pre> 288 42 289 0600 290 0xBadFace 291 170141183460469231731687303715884105727 292 </pre> 293 294 <h3 id="Floating-point_literals">Floating-point literals</h3> 295 <p> 296 A floating-point literal is a decimal representation of a 297 <a href="#Constants">floating-point constant</a>. 298 It has an integer part, a decimal point, a fractional part, 299 and an exponent part. The integer and fractional part comprise 300 decimal digits; the exponent part is an <code>e</code> or <code>E</code> 301 followed by an optionally signed decimal exponent. One of the 302 integer part or the fractional part may be elided; one of the decimal 303 point or the exponent may be elided. 304 </p> 305 <pre class="ebnf"> 306 float_lit = decimals "." [ decimals ] [ exponent ] | 307 decimals exponent | 308 "." decimals [ exponent ] . 309 decimals = decimal_digit { decimal_digit } . 310 exponent = ( "e" | "E" ) [ "+" | "-" ] decimals . 311 </pre> 312 313 <pre> 314 0. 315 72.40 316 072.40 // == 72.40 317 2.71828 318 1.e+0 319 6.67428e-11 320 1E6 321 .25 322 .12345E+5 323 </pre> 324 325 <h3 id="Imaginary_literals">Imaginary literals</h3> 326 <p> 327 An imaginary literal is a decimal representation of the imaginary part of a 328 <a href="#Constants">complex constant</a>. 329 It consists of a 330 <a href="#Floating-point_literals">floating-point literal</a> 331 or decimal integer followed 332 by the lower-case letter <code>i</code>. 333 </p> 334 <pre class="ebnf"> 335 imaginary_lit = (decimals | float_lit) "i" . 336 </pre> 337 338 <pre> 339 0i 340 011i // == 11i 341 0.i 342 2.71828i 343 1.e+0i 344 6.67428e-11i 345 1E6i 346 .25i 347 .12345E+5i 348 </pre> 349 350 351 <h3 id="Rune_literals">Rune literals</h3> 352 353 <p> 354 A rune literal represents a <a href="#Constants">rune constant</a>, 355 an integer value identifying a Unicode code point. 356 A rune literal is expressed as one or more characters enclosed in single quotes, 357 as in <code>'x'</code> or <code>'\n'</code>. 358 Within the quotes, any character may appear except newline and unescaped single 359 quote. A single quoted character represents the Unicode value 360 of the character itself, 361 while multi-character sequences beginning with a backslash encode 362 values in various formats. 363 </p> 364 <p> 365 The simplest form represents the single character within the quotes; 366 since Go source text is Unicode characters encoded in UTF-8, multiple 367 UTF-8-encoded bytes may represent a single integer value. For 368 instance, the literal <code>'a'</code> holds a single byte representing 369 a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while 370 <code>'ä'</code> holds two bytes (<code>0xc3</code> <code>0xa4</code>) representing 371 a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>. 372 </p> 373 <p> 374 Several backslash escapes allow arbitrary values to be encoded as 375 ASCII text. There are four ways to represent the integer value 376 as a numeric constant: <code>\x</code> followed by exactly two hexadecimal 377 digits; <code>\u</code> followed by exactly four hexadecimal digits; 378 <code>\U</code> followed by exactly eight hexadecimal digits, and a 379 plain backslash <code>\</code> followed by exactly three octal digits. 380 In each case the value of the literal is the value represented by 381 the digits in the corresponding base. 382 </p> 383 <p> 384 Although these representations all result in an integer, they have 385 different valid ranges. Octal escapes must represent a value between 386 0 and 255 inclusive. Hexadecimal escapes satisfy this condition 387 by construction. The escapes <code>\u</code> and <code>\U</code> 388 represent Unicode code points so within them some values are illegal, 389 in particular those above <code>0x10FFFF</code> and surrogate halves. 390 </p> 391 <p> 392 After a backslash, certain single-character escapes represent special values: 393 </p> 394 <pre class="grammar"> 395 \a U+0007 alert or bell 396 \b U+0008 backspace 397 \f U+000C form feed 398 \n U+000A line feed or newline 399 \r U+000D carriage return 400 \t U+0009 horizontal tab 401 \v U+000b vertical tab 402 \\ U+005c backslash 403 \' U+0027 single quote (valid escape only within rune literals) 404 \" U+0022 double quote (valid escape only within string literals) 405 </pre> 406 <p> 407 All other sequences starting with a backslash are illegal inside rune literals. 408 </p> 409 <pre class="ebnf"> 410 rune_lit = "'" ( unicode_value | byte_value ) "'" . 411 unicode_value = unicode_char | little_u_value | big_u_value | escaped_char . 412 byte_value = octal_byte_value | hex_byte_value . 413 octal_byte_value = `\` octal_digit octal_digit octal_digit . 414 hex_byte_value = `\` "x" hex_digit hex_digit . 415 little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit . 416 big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit 417 hex_digit hex_digit hex_digit hex_digit . 418 escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) . 419 </pre> 420 421 <pre> 422 'a' 423 'ä' 424 '本' 425 '\t' 426 '\000' 427 '\007' 428 '\377' 429 '\x07' 430 '\xff' 431 '\u12e4' 432 '\U00101234' 433 '\'' // rune literal containing single quote character 434 'aa' // illegal: too many characters 435 '\xa' // illegal: too few hexadecimal digits 436 '\0' // illegal: too few octal digits 437 '\uDFFF' // illegal: surrogate half 438 '\U00110000' // illegal: invalid Unicode code point 439 </pre> 440 441 442 <h3 id="String_literals">String literals</h3> 443 444 <p> 445 A string literal represents a <a href="#Constants">string constant</a> 446 obtained from concatenating a sequence of characters. There are two forms: 447 raw string literals and interpreted string literals. 448 </p> 449 <p> 450 Raw string literals are character sequences between back quotes, as in 451 <code>`foo`</code>. Within the quotes, any character may appear except 452 back quote. The value of a raw string literal is the 453 string composed of the uninterpreted (implicitly UTF-8-encoded) characters 454 between the quotes; 455 in particular, backslashes have no special meaning and the string may 456 contain newlines. 457 Carriage return characters ('\r') inside raw string literals 458 are discarded from the raw string value. 459 </p> 460 <p> 461 Interpreted string literals are character sequences between double 462 quotes, as in <code>"bar"</code>. 463 Within the quotes, any character may appear except newline and unescaped double quote. 464 The text between the quotes forms the 465 value of the literal, with backslash escapes interpreted as they 466 are in <a href="#Rune_literals">rune literals</a> (except that <code>\'</code> is illegal and 467 <code>\"</code> is legal), with the same restrictions. 468 The three-digit octal (<code>\</code><i>nnn</i>) 469 and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual 470 <i>bytes</i> of the resulting string; all other escapes represent 471 the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>. 472 Thus inside a string literal <code>\377</code> and <code>\xFF</code> represent 473 a single byte of value <code>0xFF</code>=255, while <code>ÿ</code>, 474 <code>\u00FF</code>, <code>\U000000FF</code> and <code>\xc3\xbf</code> represent 475 the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character 476 U+00FF. 477 </p> 478 479 <pre class="ebnf"> 480 string_lit = raw_string_lit | interpreted_string_lit . 481 raw_string_lit = "`" { unicode_char | newline } "`" . 482 interpreted_string_lit = `"` { unicode_value | byte_value } `"` . 483 </pre> 484 485 <pre> 486 `abc` // same as "abc" 487 `\n 488 \n` // same as "\\n\n\\n" 489 "\n" 490 "\"" // same as `"` 491 "Hello, world!\n" 492 "日本語" 493 "\u65e5本\U00008a9e" 494 "\xff\u00FF" 495 "\uD800" // illegal: surrogate half 496 "\U00110000" // illegal: invalid Unicode code point 497 </pre> 498 499 <p> 500 These examples all represent the same string: 501 </p> 502 503 <pre> 504 "日本語" // UTF-8 input text 505 `日本語` // UTF-8 input text as a raw literal 506 "\u65e5\u672c\u8a9e" // the explicit Unicode code points 507 "\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points 508 "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes 509 </pre> 510 511 <p> 512 If the source code represents a character as two code points, such as 513 a combining form involving an accent and a letter, the result will be 514 an error if placed in a rune literal (it is not a single code 515 point), and will appear as two code points if placed in a string 516 literal. 517 </p> 518 519 520 <h2 id="Constants">Constants</h2> 521 522 <p>There are <i>boolean constants</i>, 523 <i>rune constants</i>, 524 <i>integer constants</i>, 525 <i>floating-point constants</i>, <i>complex constants</i>, 526 and <i>string constants</i>. Rune, integer, floating-point, 527 and complex constants are 528 collectively called <i>numeric constants</i>. 529 </p> 530 531 <p> 532 A constant value is represented by a 533 <a href="#Rune_literals">rune</a>, 534 <a href="#Integer_literals">integer</a>, 535 <a href="#Floating-point_literals">floating-point</a>, 536 <a href="#Imaginary_literals">imaginary</a>, 537 or 538 <a href="#String_literals">string</a> literal, 539 an identifier denoting a constant, 540 a <a href="#Constant_expressions">constant expression</a>, 541 a <a href="#Conversions">conversion</a> with a result that is a constant, or 542 the result value of some built-in functions such as 543 <code>unsafe.Sizeof</code> applied to any value, 544 <code>cap</code> or <code>len</code> applied to 545 <a href="#Length_and_capacity">some expressions</a>, 546 <code>real</code> and <code>imag</code> applied to a complex constant 547 and <code>complex</code> applied to numeric constants. 548 The boolean truth values are represented by the predeclared constants 549 <code>true</code> and <code>false</code>. The predeclared identifier 550 <a href="#Iota">iota</a> denotes an integer constant. 551 </p> 552 553 <p> 554 In general, complex constants are a form of 555 <a href="#Constant_expressions">constant expression</a> 556 and are discussed in that section. 557 </p> 558 559 <p> 560 Numeric constants represent exact values of arbitrary precision and do not overflow. 561 Consequently, there are no constants denoting the IEEE-754 negative zero, infinity, 562 and not-a-number values. 563 </p> 564 565 <p> 566 Constants may be <a href="#Types">typed</a> or <i>untyped</i>. 567 Literal constants, <code>true</code>, <code>false</code>, <code>iota</code>, 568 and certain <a href="#Constant_expressions">constant expressions</a> 569 containing only untyped constant operands are untyped. 570 </p> 571 572 <p> 573 A constant may be given a type explicitly by a <a href="#Constant_declarations">constant declaration</a> 574 or <a href="#Conversions">conversion</a>, or implicitly when used in a 575 <a href="#Variable_declarations">variable declaration</a> or an 576 <a href="#Assignments">assignment</a> or as an 577 operand in an <a href="#Expressions">expression</a>. 578 It is an error if the constant value 579 cannot be <a href="#Representability">represented</a> as a value of the respective type. 580 </p> 581 582 <p> 583 An untyped constant has a <i>default type</i> which is the type to which the 584 constant is implicitly converted in contexts where a typed value is required, 585 for instance, in a <a href="#Short_variable_declarations">short variable declaration</a> 586 such as <code>i := 0</code> where there is no explicit type. 587 The default type of an untyped constant is <code>bool</code>, <code>rune</code>, 588 <code>int</code>, <code>float64</code>, <code>complex128</code> or <code>string</code> 589 respectively, depending on whether it is a boolean, rune, integer, floating-point, 590 complex, or string constant. 591 </p> 592 593 <p> 594 Implementation restriction: Although numeric constants have arbitrary 595 precision in the language, a compiler may implement them using an 596 internal representation with limited precision. That said, every 597 implementation must: 598 </p> 599 <ul> 600 <li>Represent integer constants with at least 256 bits.</li> 601 602 <li>Represent floating-point constants, including the parts of 603 a complex constant, with a mantissa of at least 256 bits 604 and a signed binary exponent of at least 16 bits.</li> 605 606 <li>Give an error if unable to represent an integer constant 607 precisely.</li> 608 609 <li>Give an error if unable to represent a floating-point or 610 complex constant due to overflow.</li> 611 612 <li>Round to the nearest representable constant if unable to 613 represent a floating-point or complex constant due to limits 614 on precision.</li> 615 </ul> 616 <p> 617 These requirements apply both to literal constants and to the result 618 of evaluating <a href="#Constant_expressions">constant 619 expressions</a>. 620 </p> 621 622 <h2 id="Variables">Variables</h2> 623 624 <p> 625 A variable is a storage location for holding a <i>value</i>. 626 The set of permissible values is determined by the 627 variable's <i><a href="#Types">type</a></i>. 628 </p> 629 630 <p> 631 A <a href="#Variable_declarations">variable declaration</a> 632 or, for function parameters and results, the signature 633 of a <a href="#Function_declarations">function declaration</a> 634 or <a href="#Function_literals">function literal</a> reserves 635 storage for a named variable. 636 637 Calling the built-in function <a href="#Allocation"><code>new</code></a> 638 or taking the address of a <a href="#Composite_literals">composite literal</a> 639 allocates storage for a variable at run time. 640 Such an anonymous variable is referred to via a (possibly implicit) 641 <a href="#Address_operators">pointer indirection</a>. 642 </p> 643 644 <p> 645 <i>Structured</i> variables of <a href="#Array_types">array</a>, <a href="#Slice_types">slice</a>, 646 and <a href="#Struct_types">struct</a> types have elements and fields that may 647 be <a href="#Address_operators">addressed</a> individually. Each such element 648 acts like a variable. 649 </p> 650 651 <p> 652 The <i>static type</i> (or just <i>type</i>) of a variable is the 653 type given in its declaration, the type provided in the 654 <code>new</code> call or composite literal, or the type of 655 an element of a structured variable. 656 Variables of interface type also have a distinct <i>dynamic type</i>, 657 which is the concrete type of the value assigned to the variable at run time 658 (unless the value is the predeclared identifier <code>nil</code>, 659 which has no type). 660 The dynamic type may vary during execution but values stored in interface 661 variables are always <a href="#Assignability">assignable</a> 662 to the static type of the variable. 663 </p> 664 665 <pre> 666 var x interface{} // x is nil and has static type interface{} 667 var v *T // v has value nil, static type *T 668 x = 42 // x has value 42 and dynamic type int 669 x = v // x has value (*T)(nil) and dynamic type *T 670 </pre> 671 672 <p> 673 A variable's value is retrieved by referring to the variable in an 674 <a href="#Expressions">expression</a>; it is the most recent value 675 <a href="#Assignments">assigned</a> to the variable. 676 If a variable has not yet been assigned a value, its value is the 677 <a href="#The_zero_value">zero value</a> for its type. 678 </p> 679 680 681 <h2 id="Types">Types</h2> 682 683 <p> 684 A type determines a set of values together with operations and methods specific 685 to those values. A type may be denoted by a <i>type name</i>, if it has one, 686 or specified using a <i>type literal</i>, which composes a type from existing types. 687 </p> 688 689 <pre class="ebnf"> 690 Type = TypeName | TypeLit | "(" Type ")" . 691 TypeName = identifier | QualifiedIdent . 692 TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType | 693 SliceType | MapType | ChannelType . 694 </pre> 695 696 <p> 697 Named instances of the boolean, numeric, and string types are 698 <a href="#Predeclared_identifiers">predeclared</a>. 699 Other named types are introduced with <a href="#Type_declarations">type declarations</a>. 700 <i>Composite types</i>—array, struct, pointer, function, 701 interface, slice, map, and channel types—may be constructed using 702 type literals. 703 </p> 704 705 <p> 706 Each type <code>T</code> has an <i>underlying type</i>: If <code>T</code> 707 is one of the predeclared boolean, numeric, or string types, or a type literal, 708 the corresponding underlying 709 type is <code>T</code> itself. Otherwise, <code>T</code>'s underlying type 710 is the underlying type of the type to which <code>T</code> refers in its 711 <a href="#Type_declarations">type declaration</a>. 712 </p> 713 714 <pre> 715 type ( 716 A1 = string 717 A2 = A1 718 ) 719 720 type ( 721 B1 string 722 B2 B1 723 B3 []B1 724 B4 B3 725 ) 726 </pre> 727 728 <p> 729 The underlying type of <code>string</code>, <code>A1</code>, <code>A2</code>, <code>B1</code>, 730 and <code>B2</code> is <code>string</code>. 731 The underlying type of <code>[]B1</code>, <code>B3</code>, and <code>B4</code> is <code>[]B1</code>. 732 </p> 733 734 <h3 id="Method_sets">Method sets</h3> 735 <p> 736 A type may have a <i>method set</i> associated with it. 737 The method set of an <a href="#Interface_types">interface type</a> is its interface. 738 The method set of any other type <code>T</code> consists of all 739 <a href="#Method_declarations">methods</a> declared with receiver type <code>T</code>. 740 The method set of the corresponding <a href="#Pointer_types">pointer type</a> <code>*T</code> 741 is the set of all methods declared with receiver <code>*T</code> or <code>T</code> 742 (that is, it also contains the method set of <code>T</code>). 743 Further rules apply to structs containing embedded fields, as described 744 in the section on <a href="#Struct_types">struct types</a>. 745 Any other type has an empty method set. 746 In a method set, each method must have a 747 <a href="#Uniqueness_of_identifiers">unique</a> 748 non-<a href="#Blank_identifier">blank</a> <a href="#MethodName">method name</a>. 749 </p> 750 751 <p> 752 The method set of a type determines the interfaces that the 753 type <a href="#Interface_types">implements</a> 754 and the methods that can be <a href="#Calls">called</a> 755 using a receiver of that type. 756 </p> 757 758 <h3 id="Boolean_types">Boolean types</h3> 759 760 <p> 761 A <i>boolean type</i> represents the set of Boolean truth values 762 denoted by the predeclared constants <code>true</code> 763 and <code>false</code>. The predeclared boolean type is <code>bool</code>; 764 it is a <a href="#Type_definitions">defined type</a>. 765 </p> 766 767 <h3 id="Numeric_types">Numeric types</h3> 768 769 <p> 770 A <i>numeric type</i> represents sets of integer or floating-point values. 771 The predeclared architecture-independent numeric types are: 772 </p> 773 774 <pre class="grammar"> 775 uint8 the set of all unsigned 8-bit integers (0 to 255) 776 uint16 the set of all unsigned 16-bit integers (0 to 65535) 777 uint32 the set of all unsigned 32-bit integers (0 to 4294967295) 778 uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615) 779 780 int8 the set of all signed 8-bit integers (-128 to 127) 781 int16 the set of all signed 16-bit integers (-32768 to 32767) 782 int32 the set of all signed 32-bit integers (-2147483648 to 2147483647) 783 int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807) 784 785 float32 the set of all IEEE-754 32-bit floating-point numbers 786 float64 the set of all IEEE-754 64-bit floating-point numbers 787 788 complex64 the set of all complex numbers with float32 real and imaginary parts 789 complex128 the set of all complex numbers with float64 real and imaginary parts 790 791 byte alias for uint8 792 rune alias for int32 793 </pre> 794 795 <p> 796 The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using 797 <a href="http://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>. 798 </p> 799 800 <p> 801 There is also a set of predeclared numeric types with implementation-specific sizes: 802 </p> 803 804 <pre class="grammar"> 805 uint either 32 or 64 bits 806 int same size as uint 807 uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value 808 </pre> 809 810 <p> 811 To avoid portability issues all numeric types are <a href="#Type_definitions">defined 812 types</a> and thus distinct except 813 <code>byte</code>, which is an <a href="#Alias_declarations">alias</a> for <code>uint8</code>, and 814 <code>rune</code>, which is an alias for <code>int32</code>. 815 Conversions 816 are required when different numeric types are mixed in an expression 817 or assignment. For instance, <code>int32</code> and <code>int</code> 818 are not the same type even though they may have the same size on a 819 particular architecture. 820 821 822 <h3 id="String_types">String types</h3> 823 824 <p> 825 A <i>string type</i> represents the set of string values. 826 A string value is a (possibly empty) sequence of bytes. 827 Strings are immutable: once created, 828 it is impossible to change the contents of a string. 829 The predeclared string type is <code>string</code>; 830 it is a <a href="#Type_definitions">defined type</a>. 831 </p> 832 833 <p> 834 The length of a string <code>s</code> (its size in bytes) can be discovered using 835 the built-in function <a href="#Length_and_capacity"><code>len</code></a>. 836 The length is a compile-time constant if the string is a constant. 837 A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a> 838 0 through <code>len(s)-1</code>. 839 It is illegal to take the address of such an element; if 840 <code>s[i]</code> is the <code>i</code>'th byte of a 841 string, <code>&s[i]</code> is invalid. 842 </p> 843 844 845 <h3 id="Array_types">Array types</h3> 846 847 <p> 848 An array is a numbered sequence of elements of a single 849 type, called the element type. 850 The number of elements is called the length and is never 851 negative. 852 </p> 853 854 <pre class="ebnf"> 855 ArrayType = "[" ArrayLength "]" ElementType . 856 ArrayLength = Expression . 857 ElementType = Type . 858 </pre> 859 860 <p> 861 The length is part of the array's type; it must evaluate to a 862 non-negative <a href="#Constants">constant</a> 863 <a href="#Representability">representable</a> by a value 864 of type <code>int</code>. 865 The length of array <code>a</code> can be discovered 866 using the built-in function <a href="#Length_and_capacity"><code>len</code></a>. 867 The elements can be addressed by integer <a href="#Index_expressions">indices</a> 868 0 through <code>len(a)-1</code>. 869 Array types are always one-dimensional but may be composed to form 870 multi-dimensional types. 871 </p> 872 873 <pre> 874 [32]byte 875 [2*N] struct { x, y int32 } 876 [1000]*float64 877 [3][5]int 878 [2][2][2]float64 // same as [2]([2]([2]float64)) 879 </pre> 880 881 <h3 id="Slice_types">Slice types</h3> 882 883 <p> 884 A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and 885 provides access to a numbered sequence of elements from that array. 886 A slice type denotes the set of all slices of arrays of its element type. 887 The value of an uninitialized slice is <code>nil</code>. 888 </p> 889 890 <pre class="ebnf"> 891 SliceType = "[" "]" ElementType . 892 </pre> 893 894 <p> 895 Like arrays, slices are indexable and have a length. The length of a 896 slice <code>s</code> can be discovered by the built-in function 897 <a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during 898 execution. The elements can be addressed by integer <a href="#Index_expressions">indices</a> 899 0 through <code>len(s)-1</code>. The slice index of a 900 given element may be less than the index of the same element in the 901 underlying array. 902 </p> 903 <p> 904 A slice, once initialized, is always associated with an underlying 905 array that holds its elements. A slice therefore shares storage 906 with its array and with other slices of the same array; by contrast, 907 distinct arrays always represent distinct storage. 908 </p> 909 <p> 910 The array underlying a slice may extend past the end of the slice. 911 The <i>capacity</i> is a measure of that extent: it is the sum of 912 the length of the slice and the length of the array beyond the slice; 913 a slice of length up to that capacity can be created by 914 <a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice. 915 The capacity of a slice <code>a</code> can be discovered using the 916 built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>. 917 </p> 918 919 <p> 920 A new, initialized slice value for a given element type <code>T</code> is 921 made using the built-in function 922 <a href="#Making_slices_maps_and_channels"><code>make</code></a>, 923 which takes a slice type 924 and parameters specifying the length and optionally the capacity. 925 A slice created with <code>make</code> always allocates a new, hidden array 926 to which the returned slice value refers. That is, executing 927 </p> 928 929 <pre> 930 make([]T, length, capacity) 931 </pre> 932 933 <p> 934 produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a> 935 it, so these two expressions are equivalent: 936 </p> 937 938 <pre> 939 make([]int, 50, 100) 940 new([100]int)[0:50] 941 </pre> 942 943 <p> 944 Like arrays, slices are always one-dimensional but may be composed to construct 945 higher-dimensional objects. 946 With arrays of arrays, the inner arrays are, by construction, always the same length; 947 however with slices of slices (or arrays of slices), the inner lengths may vary dynamically. 948 Moreover, the inner slices must be initialized individually. 949 </p> 950 951 <h3 id="Struct_types">Struct types</h3> 952 953 <p> 954 A struct is a sequence of named elements, called fields, each of which has a 955 name and a type. Field names may be specified explicitly (IdentifierList) or 956 implicitly (EmbeddedField). 957 Within a struct, non-<a href="#Blank_identifier">blank</a> field names must 958 be <a href="#Uniqueness_of_identifiers">unique</a>. 959 </p> 960 961 <pre class="ebnf"> 962 StructType = "struct" "{" { FieldDecl ";" } "}" . 963 FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] . 964 EmbeddedField = [ "*" ] TypeName . 965 Tag = string_lit . 966 </pre> 967 968 <pre> 969 // An empty struct. 970 struct {} 971 972 // A struct with 6 fields. 973 struct { 974 x, y int 975 u float32 976 _ float32 // padding 977 A *[]int 978 F func() 979 } 980 </pre> 981 982 <p> 983 A field declared with a type but no explicit field name is called an <i>embedded field</i>. 984 An embedded field must be specified as 985 a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>, 986 and <code>T</code> itself may not be 987 a pointer type. The unqualified type name acts as the field name. 988 </p> 989 990 <pre> 991 // A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4 992 struct { 993 T1 // field name is T1 994 *T2 // field name is T2 995 P.T3 // field name is T3 996 *P.T4 // field name is T4 997 x, y int // field names are x and y 998 } 999 </pre> 1000 1001 <p> 1002 The following declaration is illegal because field names must be unique 1003 in a struct type: 1004 </p> 1005 1006 <pre> 1007 struct { 1008 T // conflicts with embedded field *T and *P.T 1009 *T // conflicts with embedded field T and *P.T 1010 *P.T // conflicts with embedded field T and *T 1011 } 1012 </pre> 1013 1014 <p> 1015 A field or <a href="#Method_declarations">method</a> <code>f</code> of an 1016 embedded field in a struct <code>x</code> is called <i>promoted</i> if 1017 <code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes 1018 that field or method <code>f</code>. 1019 </p> 1020 1021 <p> 1022 Promoted fields act like ordinary fields 1023 of a struct except that they cannot be used as field names in 1024 <a href="#Composite_literals">composite literals</a> of the struct. 1025 </p> 1026 1027 <p> 1028 Given a struct type <code>S</code> and a type named <code>T</code>, 1029 promoted methods are included in the method set of the struct as follows: 1030 </p> 1031 <ul> 1032 <li> 1033 If <code>S</code> contains an embedded field <code>T</code>, 1034 the <a href="#Method_sets">method sets</a> of <code>S</code> 1035 and <code>*S</code> both include promoted methods with receiver 1036 <code>T</code>. The method set of <code>*S</code> also 1037 includes promoted methods with receiver <code>*T</code>. 1038 </li> 1039 1040 <li> 1041 If <code>S</code> contains an embedded field <code>*T</code>, 1042 the method sets of <code>S</code> and <code>*S</code> both 1043 include promoted methods with receiver <code>T</code> or 1044 <code>*T</code>. 1045 </li> 1046 </ul> 1047 1048 <p> 1049 A field declaration may be followed by an optional string literal <i>tag</i>, 1050 which becomes an attribute for all the fields in the corresponding 1051 field declaration. An empty tag string is equivalent to an absent tag. 1052 The tags are made visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a> 1053 and take part in <a href="#Type_identity">type identity</a> for structs 1054 but are otherwise ignored. 1055 </p> 1056 1057 <pre> 1058 struct { 1059 x, y float64 "" // an empty tag string is like an absent tag 1060 name string "any string is permitted as a tag" 1061 _ [4]byte "ceci n'est pas un champ de structure" 1062 } 1063 1064 // A struct corresponding to a TimeStamp protocol buffer. 1065 // The tag strings define the protocol buffer field numbers; 1066 // they follow the convention outlined by the reflect package. 1067 struct { 1068 microsec uint64 `protobuf:"1"` 1069 serverIP6 uint64 `protobuf:"2"` 1070 } 1071 </pre> 1072 1073 <h3 id="Pointer_types">Pointer types</h3> 1074 1075 <p> 1076 A pointer type denotes the set of all pointers to <a href="#Variables">variables</a> of a given 1077 type, called the <i>base type</i> of the pointer. 1078 The value of an uninitialized pointer is <code>nil</code>. 1079 </p> 1080 1081 <pre class="ebnf"> 1082 PointerType = "*" BaseType . 1083 BaseType = Type . 1084 </pre> 1085 1086 <pre> 1087 *Point 1088 *[4]int 1089 </pre> 1090 1091 <h3 id="Function_types">Function types</h3> 1092 1093 <p> 1094 A function type denotes the set of all functions with the same parameter 1095 and result types. The value of an uninitialized variable of function type 1096 is <code>nil</code>. 1097 </p> 1098 1099 <pre class="ebnf"> 1100 FunctionType = "func" Signature . 1101 Signature = Parameters [ Result ] . 1102 Result = Parameters | Type . 1103 Parameters = "(" [ ParameterList [ "," ] ] ")" . 1104 ParameterList = ParameterDecl { "," ParameterDecl } . 1105 ParameterDecl = [ IdentifierList ] [ "..." ] Type . 1106 </pre> 1107 1108 <p> 1109 Within a list of parameters or results, the names (IdentifierList) 1110 must either all be present or all be absent. If present, each name 1111 stands for one item (parameter or result) of the specified type and 1112 all non-<a href="#Blank_identifier">blank</a> names in the signature 1113 must be <a href="#Uniqueness_of_identifiers">unique</a>. 1114 If absent, each type stands for one item of that type. 1115 Parameter and result 1116 lists are always parenthesized except that if there is exactly 1117 one unnamed result it may be written as an unparenthesized type. 1118 </p> 1119 1120 <p> 1121 The final incoming parameter in a function signature may have 1122 a type prefixed with <code>...</code>. 1123 A function with such a parameter is called <i>variadic</i> and 1124 may be invoked with zero or more arguments for that parameter. 1125 </p> 1126 1127 <pre> 1128 func() 1129 func(x int) int 1130 func(a, _ int, z float32) bool 1131 func(a, b int, z float32) (bool) 1132 func(prefix string, values ...int) 1133 func(a, b int, z float64, opt ...interface{}) (success bool) 1134 func(int, int, float64) (float64, *[]int) 1135 func(n int) func(p *T) 1136 </pre> 1137 1138 1139 <h3 id="Interface_types">Interface types</h3> 1140 1141 <p> 1142 An interface type specifies a <a href="#Method_sets">method set</a> called its <i>interface</i>. 1143 A variable of interface type can store a value of any type with a method set 1144 that is any superset of the interface. Such a type is said to 1145 <i>implement the interface</i>. 1146 The value of an uninitialized variable of interface type is <code>nil</code>. 1147 </p> 1148 1149 <pre class="ebnf"> 1150 InterfaceType = "interface" "{" { MethodSpec ";" } "}" . 1151 MethodSpec = MethodName Signature | InterfaceTypeName . 1152 MethodName = identifier . 1153 InterfaceTypeName = TypeName . 1154 </pre> 1155 1156 <p> 1157 As with all method sets, in an interface type, each method must have a 1158 <a href="#Uniqueness_of_identifiers">unique</a> 1159 non-<a href="#Blank_identifier">blank</a> name. 1160 </p> 1161 1162 <pre> 1163 // A simple File interface 1164 interface { 1165 Read(b Buffer) bool 1166 Write(b Buffer) bool 1167 Close() 1168 } 1169 </pre> 1170 1171 <p> 1172 More than one type may implement an interface. 1173 For instance, if two types <code>S1</code> and <code>S2</code> 1174 have the method set 1175 </p> 1176 1177 <pre> 1178 func (p T) Read(b Buffer) bool { return … } 1179 func (p T) Write(b Buffer) bool { return … } 1180 func (p T) Close() { … } 1181 </pre> 1182 1183 <p> 1184 (where <code>T</code> stands for either <code>S1</code> or <code>S2</code>) 1185 then the <code>File</code> interface is implemented by both <code>S1</code> and 1186 <code>S2</code>, regardless of what other methods 1187 <code>S1</code> and <code>S2</code> may have or share. 1188 </p> 1189 1190 <p> 1191 A type implements any interface comprising any subset of its methods 1192 and may therefore implement several distinct interfaces. For 1193 instance, all types implement the <i>empty interface</i>: 1194 </p> 1195 1196 <pre> 1197 interface{} 1198 </pre> 1199 1200 <p> 1201 Similarly, consider this interface specification, 1202 which appears within a <a href="#Type_declarations">type declaration</a> 1203 to define an interface called <code>Locker</code>: 1204 </p> 1205 1206 <pre> 1207 type Locker interface { 1208 Lock() 1209 Unlock() 1210 } 1211 </pre> 1212 1213 <p> 1214 If <code>S1</code> and <code>S2</code> also implement 1215 </p> 1216 1217 <pre> 1218 func (p T) Lock() { … } 1219 func (p T) Unlock() { … } 1220 </pre> 1221 1222 <p> 1223 they implement the <code>Locker</code> interface as well 1224 as the <code>File</code> interface. 1225 </p> 1226 1227 <p> 1228 An interface <code>T</code> may use a (possibly qualified) interface type 1229 name <code>E</code> in place of a method specification. This is called 1230 <i>embedding</i> interface <code>E</code> in <code>T</code>; it adds 1231 all (exported and non-exported) methods of <code>E</code> to the interface 1232 <code>T</code>. 1233 </p> 1234 1235 <pre> 1236 type ReadWriter interface { 1237 Read(b Buffer) bool 1238 Write(b Buffer) bool 1239 } 1240 1241 type File interface { 1242 ReadWriter // same as adding the methods of ReadWriter 1243 Locker // same as adding the methods of Locker 1244 Close() 1245 } 1246 1247 type LockedFile interface { 1248 Locker 1249 File // illegal: Lock, Unlock not unique 1250 Lock() // illegal: Lock not unique 1251 } 1252 </pre> 1253 1254 <p> 1255 An interface type <code>T</code> may not embed itself 1256 or any interface type that embeds <code>T</code>, recursively. 1257 </p> 1258 1259 <pre> 1260 // illegal: Bad cannot embed itself 1261 type Bad interface { 1262 Bad 1263 } 1264 1265 // illegal: Bad1 cannot embed itself using Bad2 1266 type Bad1 interface { 1267 Bad2 1268 } 1269 type Bad2 interface { 1270 Bad1 1271 } 1272 </pre> 1273 1274 <h3 id="Map_types">Map types</h3> 1275 1276 <p> 1277 A map is an unordered group of elements of one type, called the 1278 element type, indexed by a set of unique <i>keys</i> of another type, 1279 called the key type. 1280 The value of an uninitialized map is <code>nil</code>. 1281 </p> 1282 1283 <pre class="ebnf"> 1284 MapType = "map" "[" KeyType "]" ElementType . 1285 KeyType = Type . 1286 </pre> 1287 1288 <p> 1289 The <a href="#Comparison_operators">comparison operators</a> 1290 <code>==</code> and <code>!=</code> must be fully defined 1291 for operands of the key type; thus the key type must not be a function, map, or 1292 slice. 1293 If the key type is an interface type, these 1294 comparison operators must be defined for the dynamic key values; 1295 failure will cause a <a href="#Run_time_panics">run-time panic</a>. 1296 1297 </p> 1298 1299 <pre> 1300 map[string]int 1301 map[*T]struct{ x, y float64 } 1302 map[string]interface{} 1303 </pre> 1304 1305 <p> 1306 The number of map elements is called its length. 1307 For a map <code>m</code>, it can be discovered using the 1308 built-in function <a href="#Length_and_capacity"><code>len</code></a> 1309 and may change during execution. Elements may be added during execution 1310 using <a href="#Assignments">assignments</a> and retrieved with 1311 <a href="#Index_expressions">index expressions</a>; they may be removed with the 1312 <a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function. 1313 </p> 1314 <p> 1315 A new, empty map value is made using the built-in 1316 function <a href="#Making_slices_maps_and_channels"><code>make</code></a>, 1317 which takes the map type and an optional capacity hint as arguments: 1318 </p> 1319 1320 <pre> 1321 make(map[string]int) 1322 make(map[string]int, 100) 1323 </pre> 1324 1325 <p> 1326 The initial capacity does not bound its size: 1327 maps grow to accommodate the number of items 1328 stored in them, with the exception of <code>nil</code> maps. 1329 A <code>nil</code> map is equivalent to an empty map except that no elements 1330 may be added. 1331 1332 <h3 id="Channel_types">Channel types</h3> 1333 1334 <p> 1335 A channel provides a mechanism for 1336 <a href="#Go_statements">concurrently executing functions</a> 1337 to communicate by 1338 <a href="#Send_statements">sending</a> and 1339 <a href="#Receive_operator">receiving</a> 1340 values of a specified element type. 1341 The value of an uninitialized channel is <code>nil</code>. 1342 </p> 1343 1344 <pre class="ebnf"> 1345 ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" ) ElementType . 1346 </pre> 1347 1348 <p> 1349 The optional <code><-</code> operator specifies the channel <i>direction</i>, 1350 <i>send</i> or <i>receive</i>. If no direction is given, the channel is 1351 <i>bidirectional</i>. 1352 A channel may be constrained only to send or only to receive by 1353 <a href="#Conversions">conversion</a> or <a href="#Assignments">assignment</a>. 1354 </p> 1355 1356 <pre> 1357 chan T // can be used to send and receive values of type T 1358 chan<- float64 // can only be used to send float64s 1359 <-chan int // can only be used to receive ints 1360 </pre> 1361 1362 <p> 1363 The <code><-</code> operator associates with the leftmost <code>chan</code> 1364 possible: 1365 </p> 1366 1367 <pre> 1368 chan<- chan int // same as chan<- (chan int) 1369 chan<- <-chan int // same as chan<- (<-chan int) 1370 <-chan <-chan int // same as <-chan (<-chan int) 1371 chan (<-chan int) 1372 </pre> 1373 1374 <p> 1375 A new, initialized channel 1376 value can be made using the built-in function 1377 <a href="#Making_slices_maps_and_channels"><code>make</code></a>, 1378 which takes the channel type and an optional <i>capacity</i> as arguments: 1379 </p> 1380 1381 <pre> 1382 make(chan int, 100) 1383 </pre> 1384 1385 <p> 1386 The capacity, in number of elements, sets the size of the buffer in the channel. 1387 If the capacity is zero or absent, the channel is unbuffered and communication 1388 succeeds only when both a sender and receiver are ready. Otherwise, the channel 1389 is buffered and communication succeeds without blocking if the buffer 1390 is not full (sends) or not empty (receives). 1391 A <code>nil</code> channel is never ready for communication. 1392 </p> 1393 1394 <p> 1395 A channel may be closed with the built-in function 1396 <a href="#Close"><code>close</code></a>. 1397 The multi-valued assignment form of the 1398 <a href="#Receive_operator">receive operator</a> 1399 reports whether a received value was sent before 1400 the channel was closed. 1401 </p> 1402 1403 <p> 1404 A single channel may be used in 1405 <a href="#Send_statements">send statements</a>, 1406 <a href="#Receive_operator">receive operations</a>, 1407 and calls to the built-in functions 1408 <a href="#Length_and_capacity"><code>cap</code></a> and 1409 <a href="#Length_and_capacity"><code>len</code></a> 1410 by any number of goroutines without further synchronization. 1411 Channels act as first-in-first-out queues. 1412 For example, if one goroutine sends values on a channel 1413 and a second goroutine receives them, the values are 1414 received in the order sent. 1415 </p> 1416 1417 <h2 id="Properties_of_types_and_values">Properties of types and values</h2> 1418 1419 <h3 id="Type_identity">Type identity</h3> 1420 1421 <p> 1422 Two types are either <i>identical</i> or <i>different</i>. 1423 </p> 1424 1425 <p> 1426 A <a href="#Type_definitions">defined type</a> is always different from any other type. 1427 Otherwise, two types are identical if their <a href="#Types">underlying</a> type literals are 1428 structurally equivalent; that is, they have the same literal structure and corresponding 1429 components have identical types. In detail: 1430 </p> 1431 1432 <ul> 1433 <li>Two array types are identical if they have identical element types and 1434 the same array length.</li> 1435 1436 <li>Two slice types are identical if they have identical element types.</li> 1437 1438 <li>Two struct types are identical if they have the same sequence of fields, 1439 and if corresponding fields have the same names, and identical types, 1440 and identical tags. 1441 <a href="#Exported_identifiers">Non-exported</a> field names from different 1442 packages are always different.</li> 1443 1444 <li>Two pointer types are identical if they have identical base types.</li> 1445 1446 <li>Two function types are identical if they have the same number of parameters 1447 and result values, corresponding parameter and result types are 1448 identical, and either both functions are variadic or neither is. 1449 Parameter and result names are not required to match.</li> 1450 1451 <li>Two interface types are identical if they have the same set of methods 1452 with the same names and identical function types. 1453 <a href="#Exported_identifiers">Non-exported</a> method names from different 1454 packages are always different. The order of the methods is irrelevant.</li> 1455 1456 <li>Two map types are identical if they have identical key and element types.</li> 1457 1458 <li>Two channel types are identical if they have identical element types and 1459 the same direction.</li> 1460 </ul> 1461 1462 <p> 1463 Given the declarations 1464 </p> 1465 1466 <pre> 1467 type ( 1468 A0 = []string 1469 A1 = A0 1470 A2 = struct{ a, b int } 1471 A3 = int 1472 A4 = func(A3, float64) *A0 1473 A5 = func(x int, _ float64) *[]string 1474 ) 1475 1476 type ( 1477 B0 A0 1478 B1 []string 1479 B2 struct{ a, b int } 1480 B3 struct{ a, c int } 1481 B4 func(int, float64) *B0 1482 B5 func(x int, y float64) *A1 1483 ) 1484 1485 type C0 = B0 1486 </pre> 1487 1488 <p> 1489 these types are identical: 1490 </p> 1491 1492 <pre> 1493 A0, A1, and []string 1494 A2 and struct{ a, b int } 1495 A3 and int 1496 A4, func(int, float64) *[]string, and A5 1497 1498 B0 and C0 1499 []int and []int 1500 struct{ a, b *T5 } and struct{ a, b *T5 } 1501 func(x int, y float64) *[]string, func(int, float64) (result *[]string), and A5 1502 </pre> 1503 1504 <p> 1505 <code>B0</code> and <code>B1</code> are different because they are new types 1506 created by distinct <a href="#Type_definitions">type definitions</a>; 1507 <code>func(int, float64) *B0</code> and <code>func(x int, y float64) *[]string</code> 1508 are different because <code>B0</code> is different from <code>[]string</code>. 1509 </p> 1510 1511 1512 <h3 id="Assignability">Assignability</h3> 1513 1514 <p> 1515 A value <code>x</code> is <i>assignable</i> to a <a href="#Variables">variable</a> of type <code>T</code> 1516 ("<code>x</code> is assignable to <code>T</code>") if one of the following conditions applies: 1517 </p> 1518 1519 <ul> 1520 <li> 1521 <code>x</code>'s type is identical to <code>T</code>. 1522 </li> 1523 <li> 1524 <code>x</code>'s type <code>V</code> and <code>T</code> have identical 1525 <a href="#Types">underlying types</a> and at least one of <code>V</code> 1526 or <code>T</code> is not a <a href="#Type_definitions">defined</a> type. 1527 </li> 1528 <li> 1529 <code>T</code> is an interface type and 1530 <code>x</code> <a href="#Interface_types">implements</a> <code>T</code>. 1531 </li> 1532 <li> 1533 <code>x</code> is a bidirectional channel value, <code>T</code> is a channel type, 1534 <code>x</code>'s type <code>V</code> and <code>T</code> have identical element types, 1535 and at least one of <code>V</code> or <code>T</code> is not a defined type. 1536 </li> 1537 <li> 1538 <code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code> 1539 is a pointer, function, slice, map, channel, or interface type. 1540 </li> 1541 <li> 1542 <code>x</code> is an untyped <a href="#Constants">constant</a> 1543 <a href="#Representability">representable</a> 1544 by a value of type <code>T</code>. 1545 </li> 1546 </ul> 1547 1548 1549 <h3 id="Representability">Representability</h3> 1550 1551 <p> 1552 A <a href="#Constants">constant</a> <code>x</code> is <i>representable</i> 1553 by a value of type <code>T</code> if one of the following conditions applies: 1554 </p> 1555 1556 <ul> 1557 <li> 1558 <code>x</code> is in the set of values <a href="#Types">determined</a> by <code>T</code>. 1559 </li> 1560 1561 <li> 1562 <code>T</code> is a floating-point type and <code>x</code> can be rounded to <code>T</code>'s 1563 precision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEE 1564 negative zero further simplified to an unsigned zero. Note that constant values never result 1565 in an IEEE negative zero, NaN, or infinity. 1566 </li> 1567 1568 <li> 1569 <code>T</code> is a complex type, and <code>x</code>'s 1570 <a href="#Complex_numbers">components</a> <code>real(x)</code> and <code>imag(x)</code> 1571 are representable by values of <code>T</code>'s component type (<code>float32</code> or 1572 <code>float64</code>). 1573 </li> 1574 </ul> 1575 1576 <pre> 1577 x T x is representable by a value of T because 1578 1579 'a' byte 97 is in the set of byte values 1580 97 rune rune is an alias for int32, and 97 is in the set of 32-bit integers 1581 "foo" string "foo" is in the set of string values 1582 1024 int16 1024 is in the set of 16-bit integers 1583 42.0 byte 42 is in the set of unsigned 8-bit integers 1584 1e10 uint64 10000000000 is in the set of unsigned 64-bit integers 1585 2.718281828459045 float32 2.718281828459045 rounds to 2.7182817 which is in the set of float32 values 1586 -1e-1000 float64 -1e-1000 rounds to IEEE -0.0 which is further simplified to 0.0 1587 0i int 0 is an integer value 1588 (42 + 0i) float32 42.0 (with zero imaginary part) is in the set of float32 values 1589 </pre> 1590 1591 <pre> 1592 x T x is not representable by a value of T because 1593 1594 0 bool 0 is not in the set of boolean values 1595 'a' string 'a' is a rune, it is not in the set of string values 1596 1024 byte 1024 is not in the set of unsigned 8-bit integers 1597 -1 uint16 -1 is not in the set of unsigned 16-bit integers 1598 1.1 int 1.1 is not an integer value 1599 42i float32 (0 + 42i) is not in the set of float32 values 1600 1e1000 float64 1e1000 overflows to IEEE +Inf after rounding 1601 </pre> 1602 1603 1604 <h2 id="Blocks">Blocks</h2> 1605 1606 <p> 1607 A <i>block</i> is a possibly empty sequence of declarations and statements 1608 within matching brace brackets. 1609 </p> 1610 1611 <pre class="ebnf"> 1612 Block = "{" StatementList "}" . 1613 StatementList = { Statement ";" } . 1614 </pre> 1615 1616 <p> 1617 In addition to explicit blocks in the source code, there are implicit blocks: 1618 </p> 1619 1620 <ol> 1621 <li>The <i>universe block</i> encompasses all Go source text.</li> 1622 1623 <li>Each <a href="#Packages">package</a> has a <i>package block</i> containing all 1624 Go source text for that package.</li> 1625 1626 <li>Each file has a <i>file block</i> containing all Go source text 1627 in that file.</li> 1628 1629 <li>Each <a href="#If_statements">"if"</a>, 1630 <a href="#For_statements">"for"</a>, and 1631 <a href="#Switch_statements">"switch"</a> 1632 statement is considered to be in its own implicit block.</li> 1633 1634 <li>Each clause in a <a href="#Switch_statements">"switch"</a> 1635 or <a href="#Select_statements">"select"</a> statement 1636 acts as an implicit block.</li> 1637 </ol> 1638 1639 <p> 1640 Blocks nest and influence <a href="#Declarations_and_scope">scoping</a>. 1641 </p> 1642 1643 1644 <h2 id="Declarations_and_scope">Declarations and scope</h2> 1645 1646 <p> 1647 A <i>declaration</i> binds a non-<a href="#Blank_identifier">blank</a> identifier to a 1648 <a href="#Constant_declarations">constant</a>, 1649 <a href="#Type_declarations">type</a>, 1650 <a href="#Variable_declarations">variable</a>, 1651 <a href="#Function_declarations">function</a>, 1652 <a href="#Labeled_statements">label</a>, or 1653 <a href="#Import_declarations">package</a>. 1654 Every identifier in a program must be declared. 1655 No identifier may be declared twice in the same block, and 1656 no identifier may be declared in both the file and package block. 1657 </p> 1658 1659 <p> 1660 The <a href="#Blank_identifier">blank identifier</a> may be used like any other identifier 1661 in a declaration, but it does not introduce a binding and thus is not declared. 1662 In the package block, the identifier <code>init</code> may only be used for 1663 <a href="#Package_initialization"><code>init</code> function</a> declarations, 1664 and like the blank identifier it does not introduce a new binding. 1665 </p> 1666 1667 <pre class="ebnf"> 1668 Declaration = ConstDecl | TypeDecl | VarDecl . 1669 TopLevelDecl = Declaration | FunctionDecl | MethodDecl . 1670 </pre> 1671 1672 <p> 1673 The <i>scope</i> of a declared identifier is the extent of source text in which 1674 the identifier denotes the specified constant, type, variable, function, label, or package. 1675 </p> 1676 1677 <p> 1678 Go is lexically scoped using <a href="#Blocks">blocks</a>: 1679 </p> 1680 1681 <ol> 1682 <li>The scope of a <a href="#Predeclared_identifiers">predeclared identifier</a> is the universe block.</li> 1683 1684 <li>The scope of an identifier denoting a constant, type, variable, 1685 or function (but not method) declared at top level (outside any 1686 function) is the package block.</li> 1687 1688 <li>The scope of the package name of an imported package is the file block 1689 of the file containing the import declaration.</li> 1690 1691 <li>The scope of an identifier denoting a method receiver, function parameter, 1692 or result variable is the function body.</li> 1693 1694 <li>The scope of a constant or variable identifier declared 1695 inside a function begins at the end of the ConstSpec or VarSpec 1696 (ShortVarDecl for short variable declarations) 1697 and ends at the end of the innermost containing block.</li> 1698 1699 <li>The scope of a type identifier declared inside a function 1700 begins at the identifier in the TypeSpec 1701 and ends at the end of the innermost containing block.</li> 1702 </ol> 1703 1704 <p> 1705 An identifier declared in a block may be redeclared in an inner block. 1706 While the identifier of the inner declaration is in scope, it denotes 1707 the entity declared by the inner declaration. 1708 </p> 1709 1710 <p> 1711 The <a href="#Package_clause">package clause</a> is not a declaration; the package name 1712 does not appear in any scope. Its purpose is to identify the files belonging 1713 to the same <a href="#Packages">package</a> and to specify the default package name for import 1714 declarations. 1715 </p> 1716 1717 1718 <h3 id="Label_scopes">Label scopes</h3> 1719 1720 <p> 1721 Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are 1722 used in the <a href="#Break_statements">"break"</a>, 1723 <a href="#Continue_statements">"continue"</a>, and 1724 <a href="#Goto_statements">"goto"</a> statements. 1725 It is illegal to define a label that is never used. 1726 In contrast to other identifiers, labels are not block scoped and do 1727 not conflict with identifiers that are not labels. The scope of a label 1728 is the body of the function in which it is declared and excludes 1729 the body of any nested function. 1730 </p> 1731 1732 1733 <h3 id="Blank_identifier">Blank identifier</h3> 1734 1735 <p> 1736 The <i>blank identifier</i> is represented by the underscore character <code>_</code>. 1737 It serves as an anonymous placeholder instead of a regular (non-blank) 1738 identifier and has special meaning in <a href="#Declarations_and_scope">declarations</a>, 1739 as an <a href="#Operands">operand</a>, and in <a href="#Assignments">assignments</a>. 1740 </p> 1741 1742 1743 <h3 id="Predeclared_identifiers">Predeclared identifiers</h3> 1744 1745 <p> 1746 The following identifiers are implicitly declared in the 1747 <a href="#Blocks">universe block</a>: 1748 </p> 1749 <pre class="grammar"> 1750 Types: 1751 bool byte complex64 complex128 error float32 float64 1752 int int8 int16 int32 int64 rune string 1753 uint uint8 uint16 uint32 uint64 uintptr 1754 1755 Constants: 1756 true false iota 1757 1758 Zero value: 1759 nil 1760 1761 Functions: 1762 append cap close complex copy delete imag len 1763 make new panic print println real recover 1764 </pre> 1765 1766 1767 <h3 id="Exported_identifiers">Exported identifiers</h3> 1768 1769 <p> 1770 An identifier may be <i>exported</i> to permit access to it from another package. 1771 An identifier is exported if both: 1772 </p> 1773 <ol> 1774 <li>the first character of the identifier's name is a Unicode upper case 1775 letter (Unicode class "Lu"); and</li> 1776 <li>the identifier is declared in the <a href="#Blocks">package block</a> 1777 or it is a <a href="#Struct_types">field name</a> or 1778 <a href="#MethodName">method name</a>.</li> 1779 </ol> 1780 <p> 1781 All other identifiers are not exported. 1782 </p> 1783 1784 1785 <h3 id="Uniqueness_of_identifiers">Uniqueness of identifiers</h3> 1786 1787 <p> 1788 Given a set of identifiers, an identifier is called <i>unique</i> if it is 1789 <i>different</i> from every other in the set. 1790 Two identifiers are different if they are spelled differently, or if they 1791 appear in different <a href="#Packages">packages</a> and are not 1792 <a href="#Exported_identifiers">exported</a>. Otherwise, they are the same. 1793 </p> 1794 1795 <h3 id="Constant_declarations">Constant declarations</h3> 1796 1797 <p> 1798 A constant declaration binds a list of identifiers (the names of 1799 the constants) to the values of a list of <a href="#Constant_expressions">constant expressions</a>. 1800 The number of identifiers must be equal 1801 to the number of expressions, and the <i>n</i>th identifier on 1802 the left is bound to the value of the <i>n</i>th expression on the 1803 right. 1804 </p> 1805 1806 <pre class="ebnf"> 1807 ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) . 1808 ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] . 1809 1810 IdentifierList = identifier { "," identifier } . 1811 ExpressionList = Expression { "," Expression } . 1812 </pre> 1813 1814 <p> 1815 If the type is present, all constants take the type specified, and 1816 the expressions must be <a href="#Assignability">assignable</a> to that type. 1817 If the type is omitted, the constants take the 1818 individual types of the corresponding expressions. 1819 If the expression values are untyped <a href="#Constants">constants</a>, 1820 the declared constants remain untyped and the constant identifiers 1821 denote the constant values. For instance, if the expression is a 1822 floating-point literal, the constant identifier denotes a floating-point 1823 constant, even if the literal's fractional part is zero. 1824 </p> 1825 1826 <pre> 1827 const Pi float64 = 3.14159265358979323846 1828 const zero = 0.0 // untyped floating-point constant 1829 const ( 1830 size int64 = 1024 1831 eof = -1 // untyped integer constant 1832 ) 1833 const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants 1834 const u, v float32 = 0, 3 // u = 0.0, v = 3.0 1835 </pre> 1836 1837 <p> 1838 Within a parenthesized <code>const</code> declaration list the 1839 expression list may be omitted from any but the first ConstSpec. 1840 Such an empty list is equivalent to the textual substitution of the 1841 first preceding non-empty expression list and its type if any. 1842 Omitting the list of expressions is therefore equivalent to 1843 repeating the previous list. The number of identifiers must be equal 1844 to the number of expressions in the previous list. 1845 Together with the <a href="#Iota"><code>iota</code> constant generator</a> 1846 this mechanism permits light-weight declaration of sequential values: 1847 </p> 1848 1849 <pre> 1850 const ( 1851 Sunday = iota 1852 Monday 1853 Tuesday 1854 Wednesday 1855 Thursday 1856 Friday 1857 Partyday 1858 numberOfDays // this constant is not exported 1859 ) 1860 </pre> 1861 1862 1863 <h3 id="Iota">Iota</h3> 1864 1865 <p> 1866 Within a <a href="#Constant_declarations">constant declaration</a>, the predeclared identifier 1867 <code>iota</code> represents successive untyped integer <a href="#Constants"> 1868 constants</a>. Its value is the index of the respective <a href="#ConstSpec">ConstSpec</a> 1869 in that constant declaration, starting at zero. 1870 It can be used to construct a set of related constants: 1871 </p> 1872 1873 <pre> 1874 const ( 1875 c0 = iota // c0 == 0 1876 c1 = iota // c1 == 1 1877 c2 = iota // c2 == 2 1878 ) 1879 1880 const ( 1881 a = 1 << iota // a == 1 (iota == 0) 1882 b = 1 << iota // b == 2 (iota == 1) 1883 c = 3 // c == 3 (iota == 2, unused) 1884 d = 1 << iota // d == 8 (iota == 3) 1885 ) 1886 1887 const ( 1888 u = iota * 42 // u == 0 (untyped integer constant) 1889 v float64 = iota * 42 // v == 42.0 (float64 constant) 1890 w = iota * 42 // w == 84 (untyped integer constant) 1891 ) 1892 1893 const x = iota // x == 0 1894 const y = iota // y == 0 1895 </pre> 1896 1897 <p> 1898 By definition, multiple uses of <code>iota</code> in the same ConstSpec all have the same value: 1899 </p> 1900 1901 <pre> 1902 const ( 1903 bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 (iota == 0) 1904 bit1, mask1 // bit1 == 2, mask1 == 1 (iota == 1) 1905 _, _ // (iota == 2, unused) 1906 bit3, mask3 // bit3 == 8, mask3 == 7 (iota == 3) 1907 ) 1908 </pre> 1909 1910 <p> 1911 This last example exploits the <a href="#Constant_declarations">implicit repetition</a> 1912 of the last non-empty expression list. 1913 </p> 1914 1915 1916 <h3 id="Type_declarations">Type declarations</h3> 1917 1918 <p> 1919 A type declaration binds an identifier, the <i>type name</i>, to a <a href="#Types">type</a>. 1920 Type declarations come in two forms: alias declarations and type definitions. 1921 <p> 1922 1923 <pre class="ebnf"> 1924 TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) . 1925 TypeSpec = AliasDecl | TypeDef . 1926 </pre> 1927 1928 <h4 id="Alias_declarations">Alias declarations</h4> 1929 1930 <p> 1931 An alias declaration binds an identifier to the given type. 1932 </p> 1933 1934 <pre class="ebnf"> 1935 AliasDecl = identifier "=" Type . 1936 </pre> 1937 1938 <p> 1939 Within the <a href="#Declarations_and_scope">scope</a> of 1940 the identifier, it serves as an <i>alias</i> for the type. 1941 </p> 1942 1943 <pre> 1944 type ( 1945 nodeList = []*Node // nodeList and []*Node are identical types 1946 Polar = polar // Polar and polar denote identical types 1947 ) 1948 </pre> 1949 1950 1951 <h4 id="Type_definitions">Type definitions</h4> 1952 1953 <p> 1954 A type definition creates a new, distinct type with the same 1955 <a href="#Types">underlying type</a> and operations as the given type, 1956 and binds an identifier to it. 1957 </p> 1958 1959 <pre class="ebnf"> 1960 TypeDef = identifier Type . 1961 </pre> 1962 1963 <p> 1964 The new type is called a <i>defined type</i>. 1965 It is <a href="#Type_identity">different</a> from any other type, 1966 including the type it is created from. 1967 </p> 1968 1969 <pre> 1970 type ( 1971 Point struct{ x, y float64 } // Point and struct{ x, y float64 } are different types 1972 polar Point // polar and Point denote different types 1973 ) 1974 1975 type TreeNode struct { 1976 left, right *TreeNode 1977 value *Comparable 1978 } 1979 1980 type Block interface { 1981 BlockSize() int 1982 Encrypt(src, dst []byte) 1983 Decrypt(src, dst []byte) 1984 } 1985 </pre> 1986 1987 <p> 1988 A defined type may have <a href="#Method_declarations">methods</a> associated with it. 1989 It does not inherit any methods bound to the given type, 1990 but the <a href="#Method_sets">method set</a> 1991 of an interface type or of elements of a composite type remains unchanged: 1992 </p> 1993 1994 <pre> 1995 // A Mutex is a data type with two methods, Lock and Unlock. 1996 type Mutex struct { /* Mutex fields */ } 1997 func (m *Mutex) Lock() { /* Lock implementation */ } 1998 func (m *Mutex) Unlock() { /* Unlock implementation */ } 1999 2000 // NewMutex has the same composition as Mutex but its method set is empty. 2001 type NewMutex Mutex 2002 2003 // The method set of PtrMutex's underlying type *Mutex remains unchanged, 2004 // but the method set of PtrMutex is empty. 2005 type PtrMutex *Mutex 2006 2007 // The method set of *PrintableMutex contains the methods 2008 // Lock and Unlock bound to its embedded field Mutex. 2009 type PrintableMutex struct { 2010 Mutex 2011 } 2012 2013 // MyBlock is an interface type that has the same method set as Block. 2014 type MyBlock Block 2015 </pre> 2016 2017 <p> 2018 Type definitions may be used to define different boolean, numeric, 2019 or string types and associate methods with them: 2020 </p> 2021 2022 <pre> 2023 type TimeZone int 2024 2025 const ( 2026 EST TimeZone = -(5 + iota) 2027 CST 2028 MST 2029 PST 2030 ) 2031 2032 func (tz TimeZone) String() string { 2033 return fmt.Sprintf("GMT%+dh", tz) 2034 } 2035 </pre> 2036 2037 2038 <h3 id="Variable_declarations">Variable declarations</h3> 2039 2040 <p> 2041 A variable declaration creates one or more <a href="#Variables">variables</a>, 2042 binds corresponding identifiers to them, and gives each a type and an initial value. 2043 </p> 2044 2045 <pre class="ebnf"> 2046 VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) . 2047 VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) . 2048 </pre> 2049 2050 <pre> 2051 var i int 2052 var U, V, W float64 2053 var k = 0 2054 var x, y float32 = -1, -2 2055 var ( 2056 i int 2057 u, v, s = 2.0, 3.0, "bar" 2058 ) 2059 var re, im = complexSqrt(-1) 2060 var _, found = entries[name] // map lookup; only interested in "found" 2061 </pre> 2062 2063 <p> 2064 If a list of expressions is given, the variables are initialized 2065 with the expressions following the rules for <a href="#Assignments">assignments</a>. 2066 Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>. 2067 </p> 2068 2069 <p> 2070 If a type is present, each variable is given that type. 2071 Otherwise, each variable is given the type of the corresponding 2072 initialization value in the assignment. 2073 If that value is an untyped constant, it is first 2074 <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>; 2075 if it is an untyped boolean value, it is first converted to type <code>bool</code>. 2076 The predeclared value <code>nil</code> cannot be used to initialize a variable 2077 with no explicit type. 2078 </p> 2079 2080 <pre> 2081 var d = math.Sin(0.5) // d is float64 2082 var i = 42 // i is int 2083 var t, ok = x.(T) // t is T, ok is bool 2084 var n = nil // illegal 2085 </pre> 2086 2087 <p> 2088 Implementation restriction: A compiler may make it illegal to declare a variable 2089 inside a <a href="#Function_declarations">function body</a> if the variable is 2090 never used. 2091 </p> 2092 2093 <h3 id="Short_variable_declarations">Short variable declarations</h3> 2094 2095 <p> 2096 A <i>short variable declaration</i> uses the syntax: 2097 </p> 2098 2099 <pre class="ebnf"> 2100 ShortVarDecl = IdentifierList ":=" ExpressionList . 2101 </pre> 2102 2103 <p> 2104 It is shorthand for a regular <a href="#Variable_declarations">variable declaration</a> 2105 with initializer expressions but no types: 2106 </p> 2107 2108 <pre class="grammar"> 2109 "var" IdentifierList = ExpressionList . 2110 </pre> 2111 2112 <pre> 2113 i, j := 0, 10 2114 f := func() int { return 7 } 2115 ch := make(chan int) 2116 r, w := os.Pipe(fd) // os.Pipe() returns two values 2117 _, y, _ := coord(p) // coord() returns three values; only interested in y coordinate 2118 </pre> 2119 2120 <p> 2121 Unlike regular variable declarations, a short variable declaration may <i>redeclare</i> 2122 variables provided they were originally declared earlier in the same block 2123 (or the parameter lists if the block is the function body) with the same type, 2124 and at least one of the non-<a href="#Blank_identifier">blank</a> variables is new. 2125 As a consequence, redeclaration can only appear in a multi-variable short declaration. 2126 Redeclaration does not introduce a new variable; it just assigns a new value to the original. 2127 </p> 2128 2129 <pre> 2130 field1, offset := nextField(str, 0) 2131 field2, offset := nextField(str, offset) // redeclares offset 2132 a, a := 1, 2 // illegal: double declaration of a or no new variable if a was declared elsewhere 2133 </pre> 2134 2135 <p> 2136 Short variable declarations may appear only inside functions. 2137 In some contexts such as the initializers for 2138 <a href="#If_statements">"if"</a>, 2139 <a href="#For_statements">"for"</a>, or 2140 <a href="#Switch_statements">"switch"</a> statements, 2141 they can be used to declare local temporary variables. 2142 </p> 2143 2144 <h3 id="Function_declarations">Function declarations</h3> 2145 2146 <p> 2147 A function declaration binds an identifier, the <i>function name</i>, 2148 to a function. 2149 </p> 2150 2151 <pre class="ebnf"> 2152 FunctionDecl = "func" FunctionName ( Function | Signature ) . 2153 FunctionName = identifier . 2154 Function = Signature FunctionBody . 2155 FunctionBody = Block . 2156 </pre> 2157 2158 <p> 2159 If the function's <a href="#Function_types">signature</a> declares 2160 result parameters, the function body's statement list must end in 2161 a <a href="#Terminating_statements">terminating statement</a>. 2162 </p> 2163 2164 <pre> 2165 func IndexRune(s string, r rune) int { 2166 for i, c := range s { 2167 if c == r { 2168 return i 2169 } 2170 } 2171 // invalid: missing return statement 2172 } 2173 </pre> 2174 2175 <p> 2176 A function declaration may omit the body. Such a declaration provides the 2177 signature for a function implemented outside Go, such as an assembly routine. 2178 </p> 2179 2180 <pre> 2181 func min(x int, y int) int { 2182 if x < y { 2183 return x 2184 } 2185 return y 2186 } 2187 2188 func flushICache(begin, end uintptr) // implemented externally 2189 </pre> 2190 2191 <h3 id="Method_declarations">Method declarations</h3> 2192 2193 <p> 2194 A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>. 2195 A method declaration binds an identifier, the <i>method name</i>, to a method, 2196 and associates the method with the receiver's <i>base type</i>. 2197 </p> 2198 2199 <pre class="ebnf"> 2200 MethodDecl = "func" Receiver MethodName ( Function | Signature ) . 2201 Receiver = Parameters . 2202 </pre> 2203 2204 <p> 2205 The receiver is specified via an extra parameter section preceding the method 2206 name. That parameter section must declare a single non-variadic parameter, the receiver. 2207 Its type must be of the form <code>T</code> or <code>*T</code> (possibly using 2208 parentheses) where <code>T</code> is a type name. The type denoted by <code>T</code> is called 2209 the receiver <i>base type</i>; it must not be a pointer or interface type and 2210 it must be <a href="#Type_definitions">defined</a> in the same package as the method. 2211 The method is said to be <i>bound</i> to the base type and the method name 2212 is visible only within <a href="#Selectors">selectors</a> for type <code>T</code> 2213 or <code>*T</code>. 2214 </p> 2215 2216 <p> 2217 A non-<a href="#Blank_identifier">blank</a> receiver identifier must be 2218 <a href="#Uniqueness_of_identifiers">unique</a> in the method signature. 2219 If the receiver's value is not referenced inside the body of the method, 2220 its identifier may be omitted in the declaration. The same applies in 2221 general to parameters of functions and methods. 2222 </p> 2223 2224 <p> 2225 For a base type, the non-blank names of methods bound to it must be unique. 2226 If the base type is a <a href="#Struct_types">struct type</a>, 2227 the non-blank method and field names must be distinct. 2228 </p> 2229 2230 <p> 2231 Given type <code>Point</code>, the declarations 2232 </p> 2233 2234 <pre> 2235 func (p *Point) Length() float64 { 2236 return math.Sqrt(p.x * p.x + p.y * p.y) 2237 } 2238 2239 func (p *Point) Scale(factor float64) { 2240 p.x *= factor 2241 p.y *= factor 2242 } 2243 </pre> 2244 2245 <p> 2246 bind the methods <code>Length</code> and <code>Scale</code>, 2247 with receiver type <code>*Point</code>, 2248 to the base type <code>Point</code>. 2249 </p> 2250 2251 <p> 2252 The type of a method is the type of a function with the receiver as first 2253 argument. For instance, the method <code>Scale</code> has type 2254 </p> 2255 2256 <pre> 2257 func(p *Point, factor float64) 2258 </pre> 2259 2260 <p> 2261 However, a function declared this way is not a method. 2262 </p> 2263 2264 2265 <h2 id="Expressions">Expressions</h2> 2266 2267 <p> 2268 An expression specifies the computation of a value by applying 2269 operators and functions to operands. 2270 </p> 2271 2272 <h3 id="Operands">Operands</h3> 2273 2274 <p> 2275 Operands denote the elementary values in an expression. An operand may be a 2276 literal, a (possibly <a href="#Qualified_identifiers">qualified</a>) 2277 non-<a href="#Blank_identifier">blank</a> identifier denoting a 2278 <a href="#Constant_declarations">constant</a>, 2279 <a href="#Variable_declarations">variable</a>, or 2280 <a href="#Function_declarations">function</a>, 2281 or a parenthesized expression. 2282 </p> 2283 2284 <p> 2285 The <a href="#Blank_identifier">blank identifier</a> may appear as an 2286 operand only on the left-hand side of an <a href="#Assignments">assignment</a>. 2287 </p> 2288 2289 <pre class="ebnf"> 2290 Operand = Literal | OperandName | "(" Expression ")" . 2291 Literal = BasicLit | CompositeLit | FunctionLit . 2292 BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit . 2293 OperandName = identifier | QualifiedIdent. 2294 </pre> 2295 2296 <h3 id="Qualified_identifiers">Qualified identifiers</h3> 2297 2298 <p> 2299 A qualified identifier is an identifier qualified with a package name prefix. 2300 Both the package name and the identifier must not be 2301 <a href="#Blank_identifier">blank</a>. 2302 </p> 2303 2304 <pre class="ebnf"> 2305 QualifiedIdent = PackageName "." identifier . 2306 </pre> 2307 2308 <p> 2309 A qualified identifier accesses an identifier in a different package, which 2310 must be <a href="#Import_declarations">imported</a>. 2311 The identifier must be <a href="#Exported_identifiers">exported</a> and 2312 declared in the <a href="#Blocks">package block</a> of that package. 2313 </p> 2314 2315 <pre> 2316 math.Sin // denotes the Sin function in package math 2317 </pre> 2318 2319 <h3 id="Composite_literals">Composite literals</h3> 2320 2321 <p> 2322 Composite literals construct values for structs, arrays, slices, and maps 2323 and create a new value each time they are evaluated. 2324 They consist of the type of the literal followed by a brace-bound list of elements. 2325 Each element may optionally be preceded by a corresponding key. 2326 </p> 2327 2328 <pre class="ebnf"> 2329 CompositeLit = LiteralType LiteralValue . 2330 LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | 2331 SliceType | MapType | TypeName . 2332 LiteralValue = "{" [ ElementList [ "," ] ] "}" . 2333 ElementList = KeyedElement { "," KeyedElement } . 2334 KeyedElement = [ Key ":" ] Element . 2335 Key = FieldName | Expression | LiteralValue . 2336 FieldName = identifier . 2337 Element = Expression | LiteralValue . 2338 </pre> 2339 2340 <p> 2341 The LiteralType's underlying type must be a struct, array, slice, or map type 2342 (the grammar enforces this constraint except when the type is given 2343 as a TypeName). 2344 The types of the elements and keys must be <a href="#Assignability">assignable</a> 2345 to the respective field, element, and key types of the literal type; 2346 there is no additional conversion. 2347 The key is interpreted as a field name for struct literals, 2348 an index for array and slice literals, and a key for map literals. 2349 For map literals, all elements must have a key. It is an error 2350 to specify multiple elements with the same field name or 2351 constant key value. For non-constant map keys, see the section on 2352 <a href="#Order_of_evaluation">evaluation order</a>. 2353 </p> 2354 2355 <p> 2356 For struct literals the following rules apply: 2357 </p> 2358 <ul> 2359 <li>A key must be a field name declared in the struct type. 2360 </li> 2361 <li>An element list that does not contain any keys must 2362 list an element for each struct field in the 2363 order in which the fields are declared. 2364 </li> 2365 <li>If any element has a key, every element must have a key. 2366 </li> 2367 <li>An element list that contains keys does not need to 2368 have an element for each struct field. Omitted fields 2369 get the zero value for that field. 2370 </li> 2371 <li>A literal may omit the element list; such a literal evaluates 2372 to the zero value for its type. 2373 </li> 2374 <li>It is an error to specify an element for a non-exported 2375 field of a struct belonging to a different package. 2376 </li> 2377 </ul> 2378 2379 <p> 2380 Given the declarations 2381 </p> 2382 <pre> 2383 type Point3D struct { x, y, z float64 } 2384 type Line struct { p, q Point3D } 2385 </pre> 2386 2387 <p> 2388 one may write 2389 </p> 2390 2391 <pre> 2392 origin := Point3D{} // zero value for Point3D 2393 line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x 2394 </pre> 2395 2396 <p> 2397 For array and slice literals the following rules apply: 2398 </p> 2399 <ul> 2400 <li>Each element has an associated integer index marking 2401 its position in the array. 2402 </li> 2403 <li>An element with a key uses the key as its index. The 2404 key must be a non-negative constant 2405 <a href="#Representability">representable</a> by 2406 a value of type <code>int</code>; and if it is typed 2407 it must be of integer type. 2408 </li> 2409 <li>An element without a key uses the previous element's index plus one. 2410 If the first element has no key, its index is zero. 2411 </li> 2412 </ul> 2413 2414 <p> 2415 <a href="#Address_operators">Taking the address</a> of a composite literal 2416 generates a pointer to a unique <a href="#Variables">variable</a> initialized 2417 with the literal's value. 2418 </p> 2419 <pre> 2420 var pointer *Point3D = &Point3D{y: 1000} 2421 </pre> 2422 2423 <p> 2424 The length of an array literal is the length specified in the literal type. 2425 If fewer elements than the length are provided in the literal, the missing 2426 elements are set to the zero value for the array element type. 2427 It is an error to provide elements with index values outside the index range 2428 of the array. The notation <code>...</code> specifies an array length equal 2429 to the maximum element index plus one. 2430 </p> 2431 2432 <pre> 2433 buffer := [10]string{} // len(buffer) == 10 2434 intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6 2435 days := [...]string{"Sat", "Sun"} // len(days) == 2 2436 </pre> 2437 2438 <p> 2439 A slice literal describes the entire underlying array literal. 2440 Thus the length and capacity of a slice literal are the maximum 2441 element index plus one. A slice literal has the form 2442 </p> 2443 2444 <pre> 2445 []T{x1, x2, … xn} 2446 </pre> 2447 2448 <p> 2449 and is shorthand for a slice operation applied to an array: 2450 </p> 2451 2452 <pre> 2453 tmp := [n]T{x1, x2, … xn} 2454 tmp[0 : n] 2455 </pre> 2456 2457 <p> 2458 Within a composite literal of array, slice, or map type <code>T</code>, 2459 elements or map keys that are themselves composite literals may elide the respective 2460 literal type if it is identical to the element or key type of <code>T</code>. 2461 Similarly, elements or keys that are addresses of composite literals may elide 2462 the <code>&T</code> when the element or key type is <code>*T</code>. 2463 </p> 2464 2465 <pre> 2466 [...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}} 2467 [][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}} 2468 [][]Point{{{0, 1}, {1, 2}}} // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}} 2469 map[string]Point{"orig": {0, 0}} // same as map[string]Point{"orig": Point{0, 0}} 2470 map[Point]string{{0, 0}: "orig"} // same as map[Point]string{Point{0, 0}: "orig"} 2471 2472 type PPoint *Point 2473 [2]*Point{{1.5, -3.5}, {}} // same as [2]*Point{&Point{1.5, -3.5}, &Point{}} 2474 [2]PPoint{{1.5, -3.5}, {}} // same as [2]PPoint{PPoint(&Point{1.5, -3.5}), PPoint(&Point{})} 2475 </pre> 2476 2477 <p> 2478 A parsing ambiguity arises when a composite literal using the 2479 TypeName form of the LiteralType appears as an operand between the 2480 <a href="#Keywords">keyword</a> and the opening brace of the block 2481 of an "if", "for", or "switch" statement, and the composite literal 2482 is not enclosed in parentheses, square brackets, or curly braces. 2483 In this rare case, the opening brace of the literal is erroneously parsed 2484 as the one introducing the block of statements. To resolve the ambiguity, 2485 the composite literal must appear within parentheses. 2486 </p> 2487 2488 <pre> 2489 if x == (T{a,b,c}[i]) { … } 2490 if (x == T{a,b,c}[i]) { … } 2491 </pre> 2492 2493 <p> 2494 Examples of valid array, slice, and map literals: 2495 </p> 2496 2497 <pre> 2498 // list of prime numbers 2499 primes := []int{2, 3, 5, 7, 9, 2147483647} 2500 2501 // vowels[ch] is true if ch is a vowel 2502 vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true} 2503 2504 // the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1} 2505 filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1} 2506 2507 // frequencies in Hz for equal-tempered scale (A4 = 440Hz) 2508 noteFrequency := map[string]float32{ 2509 "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83, 2510 "G0": 24.50, "A0": 27.50, "B0": 30.87, 2511 } 2512 </pre> 2513 2514 2515 <h3 id="Function_literals">Function literals</h3> 2516 2517 <p> 2518 A function literal represents an anonymous <a href="#Function_declarations">function</a>. 2519 </p> 2520 2521 <pre class="ebnf"> 2522 FunctionLit = "func" Function . 2523 </pre> 2524 2525 <pre> 2526 func(a, b int, z float64) bool { return a*b < int(z) } 2527 </pre> 2528 2529 <p> 2530 A function literal can be assigned to a variable or invoked directly. 2531 </p> 2532 2533 <pre> 2534 f := func(x, y int) int { return x + y } 2535 func(ch chan int) { ch <- ACK }(replyChan) 2536 </pre> 2537 2538 <p> 2539 Function literals are <i>closures</i>: they may refer to variables 2540 defined in a surrounding function. Those variables are then shared between 2541 the surrounding function and the function literal, and they survive as long 2542 as they are accessible. 2543 </p> 2544 2545 2546 <h3 id="Primary_expressions">Primary expressions</h3> 2547 2548 <p> 2549 Primary expressions are the operands for unary and binary expressions. 2550 </p> 2551 2552 <pre class="ebnf"> 2553 PrimaryExpr = 2554 Operand | 2555 Conversion | 2556 MethodExpr | 2557 PrimaryExpr Selector | 2558 PrimaryExpr Index | 2559 PrimaryExpr Slice | 2560 PrimaryExpr TypeAssertion | 2561 PrimaryExpr Arguments . 2562 2563 Selector = "." identifier . 2564 Index = "[" Expression "]" . 2565 Slice = "[" [ Expression ] ":" [ Expression ] "]" | 2566 "[" [ Expression ] ":" Expression ":" Expression "]" . 2567 TypeAssertion = "." "(" Type ")" . 2568 Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" . 2569 </pre> 2570 2571 2572 <pre> 2573 x 2574 2 2575 (s + ".txt") 2576 f(3.1415, true) 2577 Point{1, 2} 2578 m["foo"] 2579 s[i : j + 1] 2580 obj.color 2581 f.p[i].x() 2582 </pre> 2583 2584 2585 <h3 id="Selectors">Selectors</h3> 2586 2587 <p> 2588 For a <a href="#Primary_expressions">primary expression</a> <code>x</code> 2589 that is not a <a href="#Package_clause">package name</a>, the 2590 <i>selector expression</i> 2591 </p> 2592 2593 <pre> 2594 x.f 2595 </pre> 2596 2597 <p> 2598 denotes the field or method <code>f</code> of the value <code>x</code> 2599 (or sometimes <code>*x</code>; see below). 2600 The identifier <code>f</code> is called the (field or method) <i>selector</i>; 2601 it must not be the <a href="#Blank_identifier">blank identifier</a>. 2602 The type of the selector expression is the type of <code>f</code>. 2603 If <code>x</code> is a package name, see the section on 2604 <a href="#Qualified_identifiers">qualified identifiers</a>. 2605 </p> 2606 2607 <p> 2608 A selector <code>f</code> may denote a field or method <code>f</code> of 2609 a type <code>T</code>, or it may refer 2610 to a field or method <code>f</code> of a nested 2611 <a href="#Struct_types">embedded field</a> of <code>T</code>. 2612 The number of embedded fields traversed 2613 to reach <code>f</code> is called its <i>depth</i> in <code>T</code>. 2614 The depth of a field or method <code>f</code> 2615 declared in <code>T</code> is zero. 2616 The depth of a field or method <code>f</code> declared in 2617 an embedded field <code>A</code> in <code>T</code> is the 2618 depth of <code>f</code> in <code>A</code> plus one. 2619 </p> 2620 2621 <p> 2622 The following rules apply to selectors: 2623 </p> 2624 2625 <ol> 2626 <li> 2627 For a value <code>x</code> of type <code>T</code> or <code>*T</code> 2628 where <code>T</code> is not a pointer or interface type, 2629 <code>x.f</code> denotes the field or method at the shallowest depth 2630 in <code>T</code> where there 2631 is such an <code>f</code>. 2632 If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a> 2633 with shallowest depth, the selector expression is illegal. 2634 </li> 2635 2636 <li> 2637 For a value <code>x</code> of type <code>I</code> where <code>I</code> 2638 is an interface type, <code>x.f</code> denotes the actual method with name 2639 <code>f</code> of the dynamic value of <code>x</code>. 2640 If there is no method with name <code>f</code> in the 2641 <a href="#Method_sets">method set</a> of <code>I</code>, the selector 2642 expression is illegal. 2643 </li> 2644 2645 <li> 2646 As an exception, if the type of <code>x</code> is a named pointer type 2647 and <code>(*x).f</code> is a valid selector expression denoting a field 2648 (but not a method), <code>x.f</code> is shorthand for <code>(*x).f</code>. 2649 </li> 2650 2651 <li> 2652 In all other cases, <code>x.f</code> is illegal. 2653 </li> 2654 2655 <li> 2656 If <code>x</code> is of pointer type and has the value 2657 <code>nil</code> and <code>x.f</code> denotes a struct field, 2658 assigning to or evaluating <code>x.f</code> 2659 causes a <a href="#Run_time_panics">run-time panic</a>. 2660 </li> 2661 2662 <li> 2663 If <code>x</code> is of interface type and has the value 2664 <code>nil</code>, <a href="#Calls">calling</a> or 2665 <a href="#Method_values">evaluating</a> the method <code>x.f</code> 2666 causes a <a href="#Run_time_panics">run-time panic</a>. 2667 </li> 2668 </ol> 2669 2670 <p> 2671 For example, given the declarations: 2672 </p> 2673 2674 <pre> 2675 type T0 struct { 2676 x int 2677 } 2678 2679 func (*T0) M0() 2680 2681 type T1 struct { 2682 y int 2683 } 2684 2685 func (T1) M1() 2686 2687 type T2 struct { 2688 z int 2689 T1 2690 *T0 2691 } 2692 2693 func (*T2) M2() 2694 2695 type Q *T2 2696 2697 var t T2 // with t.T0 != nil 2698 var p *T2 // with p != nil and (*p).T0 != nil 2699 var q Q = p 2700 </pre> 2701 2702 <p> 2703 one may write: 2704 </p> 2705 2706 <pre> 2707 t.z // t.z 2708 t.y // t.T1.y 2709 t.x // (*t.T0).x 2710 2711 p.z // (*p).z 2712 p.y // (*p).T1.y 2713 p.x // (*(*p).T0).x 2714 2715 q.x // (*(*q).T0).x (*q).x is a valid field selector 2716 2717 p.M0() // ((*p).T0).M0() M0 expects *T0 receiver 2718 p.M1() // ((*p).T1).M1() M1 expects T1 receiver 2719 p.M2() // p.M2() M2 expects *T2 receiver 2720 t.M2() // (&t).M2() M2 expects *T2 receiver, see section on Calls 2721 </pre> 2722 2723 <p> 2724 but the following is invalid: 2725 </p> 2726 2727 <pre> 2728 q.M0() // (*q).M0 is valid but not a field selector 2729 </pre> 2730 2731 2732 <h3 id="Method_expressions">Method expressions</h3> 2733 2734 <p> 2735 If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>, 2736 <code>T.M</code> is a function that is callable as a regular function 2737 with the same arguments as <code>M</code> prefixed by an additional 2738 argument that is the receiver of the method. 2739 </p> 2740 2741 <pre class="ebnf"> 2742 MethodExpr = ReceiverType "." MethodName . 2743 ReceiverType = Type . 2744 </pre> 2745 2746 <p> 2747 Consider a struct type <code>T</code> with two methods, 2748 <code>Mv</code>, whose receiver is of type <code>T</code>, and 2749 <code>Mp</code>, whose receiver is of type <code>*T</code>. 2750 </p> 2751 2752 <pre> 2753 type T struct { 2754 a int 2755 } 2756 func (tv T) Mv(a int) int { return 0 } // value receiver 2757 func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver 2758 2759 var t T 2760 </pre> 2761 2762 <p> 2763 The expression 2764 </p> 2765 2766 <pre> 2767 T.Mv 2768 </pre> 2769 2770 <p> 2771 yields a function equivalent to <code>Mv</code> but 2772 with an explicit receiver as its first argument; it has signature 2773 </p> 2774 2775 <pre> 2776 func(tv T, a int) int 2777 </pre> 2778 2779 <p> 2780 That function may be called normally with an explicit receiver, so 2781 these five invocations are equivalent: 2782 </p> 2783 2784 <pre> 2785 t.Mv(7) 2786 T.Mv(t, 7) 2787 (T).Mv(t, 7) 2788 f1 := T.Mv; f1(t, 7) 2789 f2 := (T).Mv; f2(t, 7) 2790 </pre> 2791 2792 <p> 2793 Similarly, the expression 2794 </p> 2795 2796 <pre> 2797 (*T).Mp 2798 </pre> 2799 2800 <p> 2801 yields a function value representing <code>Mp</code> with signature 2802 </p> 2803 2804 <pre> 2805 func(tp *T, f float32) float32 2806 </pre> 2807 2808 <p> 2809 For a method with a value receiver, one can derive a function 2810 with an explicit pointer receiver, so 2811 </p> 2812 2813 <pre> 2814 (*T).Mv 2815 </pre> 2816 2817 <p> 2818 yields a function value representing <code>Mv</code> with signature 2819 </p> 2820 2821 <pre> 2822 func(tv *T, a int) int 2823 </pre> 2824 2825 <p> 2826 Such a function indirects through the receiver to create a value 2827 to pass as the receiver to the underlying method; 2828 the method does not overwrite the value whose address is passed in 2829 the function call. 2830 </p> 2831 2832 <p> 2833 The final case, a value-receiver function for a pointer-receiver method, 2834 is illegal because pointer-receiver methods are not in the method set 2835 of the value type. 2836 </p> 2837 2838 <p> 2839 Function values derived from methods are called with function call syntax; 2840 the receiver is provided as the first argument to the call. 2841 That is, given <code>f := T.Mv</code>, <code>f</code> is invoked 2842 as <code>f(t, 7)</code> not <code>t.f(7)</code>. 2843 To construct a function that binds the receiver, use a 2844 <a href="#Function_literals">function literal</a> or 2845 <a href="#Method_values">method value</a>. 2846 </p> 2847 2848 <p> 2849 It is legal to derive a function value from a method of an interface type. 2850 The resulting function takes an explicit receiver of that interface type. 2851 </p> 2852 2853 <h3 id="Method_values">Method values</h3> 2854 2855 <p> 2856 If the expression <code>x</code> has static type <code>T</code> and 2857 <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>, 2858 <code>x.M</code> is called a <i>method value</i>. 2859 The method value <code>x.M</code> is a function value that is callable 2860 with the same arguments as a method call of <code>x.M</code>. 2861 The expression <code>x</code> is evaluated and saved during the evaluation of the 2862 method value; the saved copy is then used as the receiver in any calls, 2863 which may be executed later. 2864 </p> 2865 2866 <p> 2867 The type <code>T</code> may be an interface or non-interface type. 2868 </p> 2869 2870 <p> 2871 As in the discussion of <a href="#Method_expressions">method expressions</a> above, 2872 consider a struct type <code>T</code> with two methods, 2873 <code>Mv</code>, whose receiver is of type <code>T</code>, and 2874 <code>Mp</code>, whose receiver is of type <code>*T</code>. 2875 </p> 2876 2877 <pre> 2878 type T struct { 2879 a int 2880 } 2881 func (tv T) Mv(a int) int { return 0 } // value receiver 2882 func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver 2883 2884 var t T 2885 var pt *T 2886 func makeT() T 2887 </pre> 2888 2889 <p> 2890 The expression 2891 </p> 2892 2893 <pre> 2894 t.Mv 2895 </pre> 2896 2897 <p> 2898 yields a function value of type 2899 </p> 2900 2901 <pre> 2902 func(int) int 2903 </pre> 2904 2905 <p> 2906 These two invocations are equivalent: 2907 </p> 2908 2909 <pre> 2910 t.Mv(7) 2911 f := t.Mv; f(7) 2912 </pre> 2913 2914 <p> 2915 Similarly, the expression 2916 </p> 2917 2918 <pre> 2919 pt.Mp 2920 </pre> 2921 2922 <p> 2923 yields a function value of type 2924 </p> 2925 2926 <pre> 2927 func(float32) float32 2928 </pre> 2929 2930 <p> 2931 As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver 2932 using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>. 2933 </p> 2934 2935 <p> 2936 As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver 2937 using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&t).Mp</code>. 2938 </p> 2939 2940 <pre> 2941 f := t.Mv; f(7) // like t.Mv(7) 2942 f := pt.Mp; f(7) // like pt.Mp(7) 2943 f := pt.Mv; f(7) // like (*pt).Mv(7) 2944 f := t.Mp; f(7) // like (&t).Mp(7) 2945 f := makeT().Mp // invalid: result of makeT() is not addressable 2946 </pre> 2947 2948 <p> 2949 Although the examples above use non-interface types, it is also legal to create a method value 2950 from a value of interface type. 2951 </p> 2952 2953 <pre> 2954 var i interface { M(int) } = myVal 2955 f := i.M; f(7) // like i.M(7) 2956 </pre> 2957 2958 2959 <h3 id="Index_expressions">Index expressions</h3> 2960 2961 <p> 2962 A primary expression of the form 2963 </p> 2964 2965 <pre> 2966 a[x] 2967 </pre> 2968 2969 <p> 2970 denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>. 2971 The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively. 2972 The following rules apply: 2973 </p> 2974 2975 <p> 2976 If <code>a</code> is not a map: 2977 </p> 2978 <ul> 2979 <li>the index <code>x</code> must be of integer type or an untyped constant</li> 2980 <li>a constant index must be non-negative and 2981 <a href="#Representability">representable</a> by a value of type <code>int</code></li> 2982 <li>a constant index that is untyped is given type <code>int</code></li> 2983 <li>the index <code>x</code> is <i>in range</i> if <code>0 <= x < len(a)</code>, 2984 otherwise it is <i>out of range</i></li> 2985 </ul> 2986 2987 <p> 2988 For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>: 2989 </p> 2990 <ul> 2991 <li>a <a href="#Constants">constant</a> index must be in range</li> 2992 <li>if <code>x</code> is out of range at run time, 2993 a <a href="#Run_time_panics">run-time panic</a> occurs</li> 2994 <li><code>a[x]</code> is the array element at index <code>x</code> and the type of 2995 <code>a[x]</code> is the element type of <code>A</code></li> 2996 </ul> 2997 2998 <p> 2999 For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type: 3000 </p> 3001 <ul> 3002 <li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li> 3003 </ul> 3004 3005 <p> 3006 For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>: 3007 </p> 3008 <ul> 3009 <li>if <code>x</code> is out of range at run time, 3010 a <a href="#Run_time_panics">run-time panic</a> occurs</li> 3011 <li><code>a[x]</code> is the slice element at index <code>x</code> and the type of 3012 <code>a[x]</code> is the element type of <code>S</code></li> 3013 </ul> 3014 3015 <p> 3016 For <code>a</code> of <a href="#String_types">string type</a>: 3017 </p> 3018 <ul> 3019 <li>a <a href="#Constants">constant</a> index must be in range 3020 if the string <code>a</code> is also constant</li> 3021 <li>if <code>x</code> is out of range at run time, 3022 a <a href="#Run_time_panics">run-time panic</a> occurs</li> 3023 <li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of 3024 <code>a[x]</code> is <code>byte</code></li> 3025 <li><code>a[x]</code> may not be assigned to</li> 3026 </ul> 3027 3028 <p> 3029 For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>: 3030 </p> 3031 <ul> 3032 <li><code>x</code>'s type must be 3033 <a href="#Assignability">assignable</a> 3034 to the key type of <code>M</code></li> 3035 <li>if the map contains an entry with key <code>x</code>, 3036 <code>a[x]</code> is the map element with key <code>x</code> 3037 and the type of <code>a[x]</code> is the element type of <code>M</code></li> 3038 <li>if the map is <code>nil</code> or does not contain such an entry, 3039 <code>a[x]</code> is the <a href="#The_zero_value">zero value</a> 3040 for the element type of <code>M</code></li> 3041 </ul> 3042 3043 <p> 3044 Otherwise <code>a[x]</code> is illegal. 3045 </p> 3046 3047 <p> 3048 An index expression on a map <code>a</code> of type <code>map[K]V</code> 3049 used in an <a href="#Assignments">assignment</a> or initialization of the special form 3050 </p> 3051 3052 <pre> 3053 v, ok = a[x] 3054 v, ok := a[x] 3055 var v, ok = a[x] 3056 var v, ok T = a[x] 3057 </pre> 3058 3059 <p> 3060 yields an additional untyped boolean value. The value of <code>ok</code> is 3061 <code>true</code> if the key <code>x</code> is present in the map, and 3062 <code>false</code> otherwise. 3063 </p> 3064 3065 <p> 3066 Assigning to an element of a <code>nil</code> map causes a 3067 <a href="#Run_time_panics">run-time panic</a>. 3068 </p> 3069 3070 3071 <h3 id="Slice_expressions">Slice expressions</h3> 3072 3073 <p> 3074 Slice expressions construct a substring or slice from a string, array, pointer 3075 to array, or slice. There are two variants: a simple form that specifies a low 3076 and high bound, and a full form that also specifies a bound on the capacity. 3077 </p> 3078 3079 <h4>Simple slice expressions</h4> 3080 3081 <p> 3082 For a string, array, pointer to array, or slice <code>a</code>, the primary expression 3083 </p> 3084 3085 <pre> 3086 a[low : high] 3087 </pre> 3088 3089 <p> 3090 constructs a substring or slice. The <i>indices</i> <code>low</code> and 3091 <code>high</code> select which elements of operand <code>a</code> appear 3092 in the result. The result has indices starting at 0 and length equal to 3093 <code>high</code> - <code>low</code>. 3094 After slicing the array <code>a</code> 3095 </p> 3096 3097 <pre> 3098 a := [5]int{1, 2, 3, 4, 5} 3099 s := a[1:4] 3100 </pre> 3101 3102 <p> 3103 the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements 3104 </p> 3105 3106 <pre> 3107 s[0] == 2 3108 s[1] == 3 3109 s[2] == 4 3110 </pre> 3111 3112 <p> 3113 For convenience, any of the indices may be omitted. A missing <code>low</code> 3114 index defaults to zero; a missing <code>high</code> index defaults to the length of the 3115 sliced operand: 3116 </p> 3117 3118 <pre> 3119 a[2:] // same as a[2 : len(a)] 3120 a[:3] // same as a[0 : 3] 3121 a[:] // same as a[0 : len(a)] 3122 </pre> 3123 3124 <p> 3125 If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for 3126 <code>(*a)[low : high]</code>. 3127 </p> 3128 3129 <p> 3130 For arrays or strings, the indices are <i>in range</i> if 3131 <code>0</code> <= <code>low</code> <= <code>high</code> <= <code>len(a)</code>, 3132 otherwise they are <i>out of range</i>. 3133 For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length. 3134 A <a href="#Constants">constant</a> index must be non-negative and 3135 <a href="#Representability">representable</a> by a value of type 3136 <code>int</code>; for arrays or constant strings, constant indices must also be in range. 3137 If both indices are constant, they must satisfy <code>low <= high</code>. 3138 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. 3139 </p> 3140 3141 <p> 3142 Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice, 3143 the result of the slice operation is a non-constant value of the same type as the operand. 3144 For untyped string operands the result is a non-constant value of type <code>string</code>. 3145 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a> 3146 and the result of the slice operation is a slice with the same element type as the array. 3147 </p> 3148 3149 <p> 3150 If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result 3151 is a <code>nil</code> slice. Otherwise, if the result is a slice, it shares its underlying 3152 array with the operand. 3153 </p> 3154 3155 <h4>Full slice expressions</h4> 3156 3157 <p> 3158 For an array, pointer to array, or slice <code>a</code> (but not a string), the primary expression 3159 </p> 3160 3161 <pre> 3162 a[low : high : max] 3163 </pre> 3164 3165 <p> 3166 constructs a slice of the same type, and with the same length and elements as the simple slice 3167 expression <code>a[low : high]</code>. Additionally, it controls the resulting slice's capacity 3168 by setting it to <code>max - low</code>. Only the first index may be omitted; it defaults to 0. 3169 After slicing the array <code>a</code> 3170 </p> 3171 3172 <pre> 3173 a := [5]int{1, 2, 3, 4, 5} 3174 t := a[1:3:5] 3175 </pre> 3176 3177 <p> 3178 the slice <code>t</code> has type <code>[]int</code>, length 2, capacity 4, and elements 3179 </p> 3180 3181 <pre> 3182 t[0] == 2 3183 t[1] == 3 3184 </pre> 3185 3186 <p> 3187 As for simple slice expressions, if <code>a</code> is a pointer to an array, 3188 <code>a[low : high : max]</code> is shorthand for <code>(*a)[low : high : max]</code>. 3189 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>. 3190 </p> 3191 3192 <p> 3193 The indices are <i>in range</i> if <code>0 <= low <= high <= max <= cap(a)</code>, 3194 otherwise they are <i>out of range</i>. 3195 A <a href="#Constants">constant</a> index must be non-negative and 3196 <a href="#Representability">representable</a> by a value of type 3197 <code>int</code>; for arrays, constant indices must also be in range. 3198 If multiple indices are constant, the constants that are present must be in range relative to each 3199 other. 3200 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. 3201 </p> 3202 3203 <h3 id="Type_assertions">Type assertions</h3> 3204 3205 <p> 3206 For an expression <code>x</code> of <a href="#Interface_types">interface type</a> 3207 and a type <code>T</code>, the primary expression 3208 </p> 3209 3210 <pre> 3211 x.(T) 3212 </pre> 3213 3214 <p> 3215 asserts that <code>x</code> is not <code>nil</code> 3216 and that the value stored in <code>x</code> is of type <code>T</code>. 3217 The notation <code>x.(T)</code> is called a <i>type assertion</i>. 3218 </p> 3219 <p> 3220 More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts 3221 that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a> 3222 to the type <code>T</code>. 3223 In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>; 3224 otherwise the type assertion is invalid since it is not possible for <code>x</code> 3225 to store a value of type <code>T</code>. 3226 If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type 3227 of <code>x</code> implements the interface <code>T</code>. 3228 </p> 3229 <p> 3230 If the type assertion holds, the value of the expression is the value 3231 stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false, 3232 a <a href="#Run_time_panics">run-time panic</a> occurs. 3233 In other words, even though the dynamic type of <code>x</code> 3234 is known only at run time, the type of <code>x.(T)</code> is 3235 known to be <code>T</code> in a correct program. 3236 </p> 3237 3238 <pre> 3239 var x interface{} = 7 // x has dynamic type int and value 7 3240 i := x.(int) // i has type int and value 7 3241 3242 type I interface { m() } 3243 3244 func f(y I) { 3245 s := y.(string) // illegal: string does not implement I (missing method m) 3246 r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader 3247 … 3248 } 3249 </pre> 3250 3251 <p> 3252 A type assertion used in an <a href="#Assignments">assignment</a> or initialization of the special form 3253 </p> 3254 3255 <pre> 3256 v, ok = x.(T) 3257 v, ok := x.(T) 3258 var v, ok = x.(T) 3259 var v, ok T1 = x.(T) 3260 </pre> 3261 3262 <p> 3263 yields an additional untyped boolean value. The value of <code>ok</code> is <code>true</code> 3264 if the assertion holds. Otherwise it is <code>false</code> and the value of <code>v</code> is 3265 the <a href="#The_zero_value">zero value</a> for type <code>T</code>. 3266 No run-time panic occurs in this case. 3267 </p> 3268 3269 3270 <h3 id="Calls">Calls</h3> 3271 3272 <p> 3273 Given an expression <code>f</code> of function type 3274 <code>F</code>, 3275 </p> 3276 3277 <pre> 3278 f(a1, a2, … an) 3279 </pre> 3280 3281 <p> 3282 calls <code>f</code> with arguments <code>a1, a2, … an</code>. 3283 Except for one special case, arguments must be single-valued expressions 3284 <a href="#Assignability">assignable</a> to the parameter types of 3285 <code>F</code> and are evaluated before the function is called. 3286 The type of the expression is the result type 3287 of <code>F</code>. 3288 A method invocation is similar but the method itself 3289 is specified as a selector upon a value of the receiver type for 3290 the method. 3291 </p> 3292 3293 <pre> 3294 math.Atan2(x, y) // function call 3295 var pt *Point 3296 pt.Scale(3.5) // method call with receiver pt 3297 </pre> 3298 3299 <p> 3300 In a function call, the function value and arguments are evaluated in 3301 <a href="#Order_of_evaluation">the usual order</a>. 3302 After they are evaluated, the parameters of the call are passed by value to the function 3303 and the called function begins execution. 3304 The return parameters of the function are passed by value 3305 back to the calling function when the function returns. 3306 </p> 3307 3308 <p> 3309 Calling a <code>nil</code> function value 3310 causes a <a href="#Run_time_panics">run-time panic</a>. 3311 </p> 3312 3313 <p> 3314 As a special case, if the return values of a function or method 3315 <code>g</code> are equal in number and individually 3316 assignable to the parameters of another function or method 3317 <code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code> 3318 will invoke <code>f</code> after binding the return values of 3319 <code>g</code> to the parameters of <code>f</code> in order. The call 3320 of <code>f</code> must contain no parameters other than the call of <code>g</code>, 3321 and <code>g</code> must have at least one return value. 3322 If <code>f</code> has a final <code>...</code> parameter, it is 3323 assigned the return values of <code>g</code> that remain after 3324 assignment of regular parameters. 3325 </p> 3326 3327 <pre> 3328 func Split(s string, pos int) (string, string) { 3329 return s[0:pos], s[pos:] 3330 } 3331 3332 func Join(s, t string) string { 3333 return s + t 3334 } 3335 3336 if Join(Split(value, len(value)/2)) != value { 3337 log.Panic("test fails") 3338 } 3339 </pre> 3340 3341 <p> 3342 A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a> 3343 of (the type of) <code>x</code> contains <code>m</code> and the 3344 argument list can be assigned to the parameter list of <code>m</code>. 3345 If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&x</code>'s method 3346 set contains <code>m</code>, <code>x.m()</code> is shorthand 3347 for <code>(&x).m()</code>: 3348 </p> 3349 3350 <pre> 3351 var p Point 3352 p.Scale(3.5) 3353 </pre> 3354 3355 <p> 3356 There is no distinct method type and there are no method literals. 3357 </p> 3358 3359 <h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3> 3360 3361 <p> 3362 If <code>f</code> is <a href="#Function_types">variadic</a> with a final 3363 parameter <code>p</code> of type <code>...T</code>, then within <code>f</code> 3364 the type of <code>p</code> is equivalent to type <code>[]T</code>. 3365 If <code>f</code> is invoked with no actual arguments for <code>p</code>, 3366 the value passed to <code>p</code> is <code>nil</code>. 3367 Otherwise, the value passed is a new slice 3368 of type <code>[]T</code> with a new underlying array whose successive elements 3369 are the actual arguments, which all must be <a href="#Assignability">assignable</a> 3370 to <code>T</code>. The length and capacity of the slice is therefore 3371 the number of arguments bound to <code>p</code> and may differ for each 3372 call site. 3373 </p> 3374 3375 <p> 3376 Given the function and calls 3377 </p> 3378 <pre> 3379 func Greeting(prefix string, who ...string) 3380 Greeting("nobody") 3381 Greeting("hello:", "Joe", "Anna", "Eileen") 3382 </pre> 3383 3384 <p> 3385 within <code>Greeting</code>, <code>who</code> will have the value 3386 <code>nil</code> in the first call, and 3387 <code>[]string{"Joe", "Anna", "Eileen"}</code> in the second. 3388 </p> 3389 3390 <p> 3391 If the final argument is assignable to a slice type <code>[]T</code>, it may be 3392 passed unchanged as the value for a <code>...T</code> parameter if the argument 3393 is followed by <code>...</code>. In this case no new slice is created. 3394 </p> 3395 3396 <p> 3397 Given the slice <code>s</code> and call 3398 </p> 3399 3400 <pre> 3401 s := []string{"James", "Jasmine"} 3402 Greeting("goodbye:", s...) 3403 </pre> 3404 3405 <p> 3406 within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code> 3407 with the same underlying array. 3408 </p> 3409 3410 3411 <h3 id="Operators">Operators</h3> 3412 3413 <p> 3414 Operators combine operands into expressions. 3415 </p> 3416 3417 <pre class="ebnf"> 3418 Expression = UnaryExpr | Expression binary_op Expression . 3419 UnaryExpr = PrimaryExpr | unary_op UnaryExpr . 3420 3421 binary_op = "||" | "&&" | rel_op | add_op | mul_op . 3422 rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" . 3423 add_op = "+" | "-" | "|" | "^" . 3424 mul_op = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" . 3425 3426 unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-" . 3427 </pre> 3428 3429 <p> 3430 Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>. 3431 For other binary operators, the operand types must be <a href="#Type_identity">identical</a> 3432 unless the operation involves shifts or untyped <a href="#Constants">constants</a>. 3433 For operations involving constants only, see the section on 3434 <a href="#Constant_expressions">constant expressions</a>. 3435 </p> 3436 3437 <p> 3438 Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a> 3439 and the other operand is not, the constant is <a href="#Conversions">converted</a> 3440 to the type of the other operand. 3441 </p> 3442 3443 <p> 3444 The right operand in a shift expression must have unsigned integer type 3445 or be an untyped constant <a href="#Representability">representable</a> by a 3446 value of type <code>uint</code>. 3447 If the left operand of a non-constant shift expression is an untyped constant, 3448 it is first converted to the type it would assume if the shift expression were 3449 replaced by its left operand alone. 3450 </p> 3451 3452 <pre> 3453 var s uint = 33 3454 var i = 1<<s // 1 has type int 3455 var j int32 = 1<<s // 1 has type int32; j == 0 3456 var k = uint64(1<<s) // 1 has type uint64; k == 1<<33 3457 var m int = 1.0<<s // 1.0 has type int; m == 0 if ints are 32bits in size 3458 var n = 1.0<<s == j // 1.0 has type int32; n == true 3459 var o = 1<<s == 2<<s // 1 and 2 have type int; o == true if ints are 32bits in size 3460 var p = 1<<s == 1<<33 // illegal if ints are 32bits in size: 1 has type int, but 1<<33 overflows int 3461 var u = 1.0<<s // illegal: 1.0 has type float64, cannot shift 3462 var u1 = 1.0<<s != 0 // illegal: 1.0 has type float64, cannot shift 3463 var u2 = 1<<s != 1.0 // illegal: 1 has type float64, cannot shift 3464 var v float32 = 1<<s // illegal: 1 has type float32, cannot shift 3465 var w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression 3466 var x = a[1.0<<s] // 1.0 has type int; x == a[0] if ints are 32bits in size 3467 var a = make([]byte, 1.0<<s) // 1.0 has type int; len(a) == 0 if ints are 32bits in size 3468 </pre> 3469 3470 3471 <h4 id="Operator_precedence">Operator precedence</h4> 3472 <p> 3473 Unary operators have the highest precedence. 3474 As the <code>++</code> and <code>--</code> operators form 3475 statements, not expressions, they fall 3476 outside the operator hierarchy. 3477 As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>. 3478 <p> 3479 There are five precedence levels for binary operators. 3480 Multiplication operators bind strongest, followed by addition 3481 operators, comparison operators, <code>&&</code> (logical AND), 3482 and finally <code>||</code> (logical OR): 3483 </p> 3484 3485 <pre class="grammar"> 3486 Precedence Operator 3487 5 * / % << >> & &^ 3488 4 + - | ^ 3489 3 == != < <= > >= 3490 2 && 3491 1 || 3492 </pre> 3493 3494 <p> 3495 Binary operators of the same precedence associate from left to right. 3496 For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>. 3497 </p> 3498 3499 <pre> 3500 +x 3501 23 + 3*x[i] 3502 x <= f() 3503 ^a >> b 3504 f() || g() 3505 x == y+1 && <-chanPtr > 0 3506 </pre> 3507 3508 3509 <h3 id="Arithmetic_operators">Arithmetic operators</h3> 3510 <p> 3511 Arithmetic operators apply to numeric values and yield a result of the same 3512 type as the first operand. The four standard arithmetic operators (<code>+</code>, 3513 <code>-</code>, <code>*</code>, <code>/</code>) apply to integer, 3514 floating-point, and complex types; <code>+</code> also applies to strings. 3515 The bitwise logical and shift operators apply to integers only. 3516 </p> 3517 3518 <pre class="grammar"> 3519 + sum integers, floats, complex values, strings 3520 - difference integers, floats, complex values 3521 * product integers, floats, complex values 3522 / quotient integers, floats, complex values 3523 % remainder integers 3524 3525 & bitwise AND integers 3526 | bitwise OR integers 3527 ^ bitwise XOR integers 3528 &^ bit clear (AND NOT) integers 3529 3530 << left shift integer << unsigned integer 3531 >> right shift integer >> unsigned integer 3532 </pre> 3533 3534 3535 <h4 id="Integer_operators">Integer operators</h4> 3536 3537 <p> 3538 For two integer values <code>x</code> and <code>y</code>, the integer quotient 3539 <code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following 3540 relationships: 3541 </p> 3542 3543 <pre> 3544 x = q*y + r and |r| < |y| 3545 </pre> 3546 3547 <p> 3548 with <code>x / y</code> truncated towards zero 3549 (<a href="http://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>). 3550 </p> 3551 3552 <pre> 3553 x y x / y x % y 3554 5 3 1 2 3555 -5 3 -1 -2 3556 5 -3 -1 2 3557 -5 -3 1 -2 3558 </pre> 3559 3560 <p> 3561 The one exception to this rule is that if the dividend <code>x</code> is 3562 the most negative value for the int type of <code>x</code>, the quotient 3563 <code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>) 3564 due to two's-complement <a href="#Integer_overflow">integer overflow</a>: 3565 </p> 3566 3567 <pre> 3568 x, q 3569 int8 -128 3570 int16 -32768 3571 int32 -2147483648 3572 int64 -9223372036854775808 3573 </pre> 3574 3575 <p> 3576 If the divisor is a <a href="#Constants">constant</a>, it must not be zero. 3577 If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. 3578 If the dividend is non-negative and the divisor is a constant power of 2, 3579 the division may be replaced by a right shift, and computing the remainder may 3580 be replaced by a bitwise AND operation: 3581 </p> 3582 3583 <pre> 3584 x x / 4 x % 4 x >> 2 x & 3 3585 11 2 3 2 3 3586 -11 -2 -3 -3 1 3587 </pre> 3588 3589 <p> 3590 The shift operators shift the left operand by the shift count specified by the 3591 right operand. They implement arithmetic shifts if the left operand is a signed 3592 integer and logical shifts if it is an unsigned integer. 3593 There is no upper limit on the shift count. Shifts behave 3594 as if the left operand is shifted <code>n</code> times by 1 for a shift 3595 count of <code>n</code>. 3596 As a result, <code>x << 1</code> is the same as <code>x*2</code> 3597 and <code>x >> 1</code> is the same as 3598 <code>x/2</code> but truncated towards negative infinity. 3599 </p> 3600 3601 <p> 3602 For integer operands, the unary operators 3603 <code>+</code>, <code>-</code>, and <code>^</code> are defined as 3604 follows: 3605 </p> 3606 3607 <pre class="grammar"> 3608 +x is 0 + x 3609 -x negation is 0 - x 3610 ^x bitwise complement is m ^ x with m = "all bits set to 1" for unsigned x 3611 and m = -1 for signed x 3612 </pre> 3613 3614 3615 <h4 id="Integer_overflow">Integer overflow</h4> 3616 3617 <p> 3618 For unsigned integer values, the operations <code>+</code>, 3619 <code>-</code>, <code>*</code>, and <code><<</code> are 3620 computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of 3621 the <a href="#Numeric_types">unsigned integer</a>'s type. 3622 Loosely speaking, these unsigned integer operations 3623 discard high bits upon overflow, and programs may rely on "wrap around". 3624 </p> 3625 <p> 3626 For signed integers, the operations <code>+</code>, 3627 <code>-</code>, <code>*</code>, <code>/</code>, and <code><<</code> may legally 3628 overflow and the resulting value exists and is deterministically defined 3629 by the signed integer representation, the operation, and its operands. 3630 No exception is raised as a result of overflow. 3631 A compiler may not optimize code under the assumption that overflow does 3632 not occur. For instance, it may not assume that <code>x < x + 1</code> is always true. 3633 </p> 3634 3635 3636 <h4 id="Floating_point_operators">Floating-point operators</h4> 3637 3638 <p> 3639 For floating-point and complex numbers, 3640 <code>+x</code> is the same as <code>x</code>, 3641 while <code>-x</code> is the negation of <code>x</code>. 3642 The result of a floating-point or complex division by zero is not specified beyond the 3643 IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a> 3644 occurs is implementation-specific. 3645 </p> 3646 3647 <p> 3648 An implementation may combine multiple floating-point operations into a single 3649 fused operation, possibly across statements, and produce a result that differs 3650 from the value obtained by executing and rounding the instructions individually. 3651 A floating-point type <a href="#Conversions">conversion</a> explicitly rounds to 3652 the precision of the target type, preventing fusion that would discard that rounding. 3653 </p> 3654 3655 <p> 3656 For instance, some architectures provide a "fused multiply and add" (FMA) instruction 3657 that computes <code>x*y + z</code> without rounding the intermediate result <code>x*y</code>. 3658 These examples show when a Go implementation can use that instruction: 3659 </p> 3660 3661 <pre> 3662 // FMA allowed for computing r, because x*y is not explicitly rounded: 3663 r = x*y + z 3664 r = z; r += x*y 3665 t = x*y; r = t + z 3666 *p = x*y; r = *p + z 3667 r = x*y + float64(z) 3668 3669 // FMA disallowed for computing r, because it would omit rounding of x*y: 3670 r = float64(x*y) + z 3671 r = z; r += float64(x*y) 3672 t = float64(x*y); r = t + z 3673 </pre> 3674 3675 <h4 id="String_concatenation">String concatenation</h4> 3676 3677 <p> 3678 Strings can be concatenated using the <code>+</code> operator 3679 or the <code>+=</code> assignment operator: 3680 </p> 3681 3682 <pre> 3683 s := "hi" + string(c) 3684 s += " and good bye" 3685 </pre> 3686 3687 <p> 3688 String addition creates a new string by concatenating the operands. 3689 </p> 3690 3691 3692 <h3 id="Comparison_operators">Comparison operators</h3> 3693 3694 <p> 3695 Comparison operators compare two operands and yield an untyped boolean value. 3696 </p> 3697 3698 <pre class="grammar"> 3699 == equal 3700 != not equal 3701 < less 3702 <= less or equal 3703 > greater 3704 >= greater or equal 3705 </pre> 3706 3707 <p> 3708 In any comparison, the first operand 3709 must be <a href="#Assignability">assignable</a> 3710 to the type of the second operand, or vice versa. 3711 </p> 3712 <p> 3713 The equality operators <code>==</code> and <code>!=</code> apply 3714 to operands that are <i>comparable</i>. 3715 The ordering operators <code><</code>, <code><=</code>, <code>></code>, and <code>>=</code> 3716 apply to operands that are <i>ordered</i>. 3717 These terms and the result of the comparisons are defined as follows: 3718 </p> 3719 3720 <ul> 3721 <li> 3722 Boolean values are comparable. 3723 Two boolean values are equal if they are either both 3724 <code>true</code> or both <code>false</code>. 3725 </li> 3726 3727 <li> 3728 Integer values are comparable and ordered, in the usual way. 3729 </li> 3730 3731 <li> 3732 Floating-point values are comparable and ordered, 3733 as defined by the IEEE-754 standard. 3734 </li> 3735 3736 <li> 3737 Complex values are comparable. 3738 Two complex values <code>u</code> and <code>v</code> are 3739 equal if both <code>real(u) == real(v)</code> and 3740 <code>imag(u) == imag(v)</code>. 3741 </li> 3742 3743 <li> 3744 String values are comparable and ordered, lexically byte-wise. 3745 </li> 3746 3747 <li> 3748 Pointer values are comparable. 3749 Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>. 3750 Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal. 3751 </li> 3752 3753 <li> 3754 Channel values are comparable. 3755 Two channel values are equal if they were created by the same call to 3756 <a href="#Making_slices_maps_and_channels"><code>make</code></a> 3757 or if both have value <code>nil</code>. 3758 </li> 3759 3760 <li> 3761 Interface values are comparable. 3762 Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types 3763 and equal dynamic values or if both have value <code>nil</code>. 3764 </li> 3765 3766 <li> 3767 A value <code>x</code> of non-interface type <code>X</code> and 3768 a value <code>t</code> of interface type <code>T</code> are comparable when values 3769 of type <code>X</code> are comparable and 3770 <code>X</code> implements <code>T</code>. 3771 They are equal if <code>t</code>'s dynamic type is identical to <code>X</code> 3772 and <code>t</code>'s dynamic value is equal to <code>x</code>. 3773 </li> 3774 3775 <li> 3776 Struct values are comparable if all their fields are comparable. 3777 Two struct values are equal if their corresponding 3778 non-<a href="#Blank_identifier">blank</a> fields are equal. 3779 </li> 3780 3781 <li> 3782 Array values are comparable if values of the array element type are comparable. 3783 Two array values are equal if their corresponding elements are equal. 3784 </li> 3785 </ul> 3786 3787 <p> 3788 A comparison of two interface values with identical dynamic types 3789 causes a <a href="#Run_time_panics">run-time panic</a> if values 3790 of that type are not comparable. This behavior applies not only to direct interface 3791 value comparisons but also when comparing arrays of interface values 3792 or structs with interface-valued fields. 3793 </p> 3794 3795 <p> 3796 Slice, map, and function values are not comparable. 3797 However, as a special case, a slice, map, or function value may 3798 be compared to the predeclared identifier <code>nil</code>. 3799 Comparison of pointer, channel, and interface values to <code>nil</code> 3800 is also allowed and follows from the general rules above. 3801 </p> 3802 3803 <pre> 3804 const c = 3 < 4 // c is the untyped boolean constant true 3805 3806 type MyBool bool 3807 var x, y int 3808 var ( 3809 // The result of a comparison is an untyped boolean. 3810 // The usual assignment rules apply. 3811 b3 = x == y // b3 has type bool 3812 b4 bool = x == y // b4 has type bool 3813 b5 MyBool = x == y // b5 has type MyBool 3814 ) 3815 </pre> 3816 3817 <h3 id="Logical_operators">Logical operators</h3> 3818 3819 <p> 3820 Logical operators apply to <a href="#Boolean_types">boolean</a> values 3821 and yield a result of the same type as the operands. 3822 The right operand is evaluated conditionally. 3823 </p> 3824 3825 <pre class="grammar"> 3826 && conditional AND p && q is "if p then q else false" 3827 || conditional OR p || q is "if p then true else q" 3828 ! NOT !p is "not p" 3829 </pre> 3830 3831 3832 <h3 id="Address_operators">Address operators</h3> 3833 3834 <p> 3835 For an operand <code>x</code> of type <code>T</code>, the address operation 3836 <code>&x</code> generates a pointer of type <code>*T</code> to <code>x</code>. 3837 The operand must be <i>addressable</i>, 3838 that is, either a variable, pointer indirection, or slice indexing 3839 operation; or a field selector of an addressable struct operand; 3840 or an array indexing operation of an addressable array. 3841 As an exception to the addressability requirement, <code>x</code> may also be a 3842 (possibly parenthesized) 3843 <a href="#Composite_literals">composite literal</a>. 3844 If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>, 3845 then the evaluation of <code>&x</code> does too. 3846 </p> 3847 3848 <p> 3849 For an operand <code>x</code> of pointer type <code>*T</code>, the pointer 3850 indirection <code>*x</code> denotes the <a href="#Variables">variable</a> of type <code>T</code> pointed 3851 to by <code>x</code>. 3852 If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code> 3853 will cause a <a href="#Run_time_panics">run-time panic</a>. 3854 </p> 3855 3856 <pre> 3857 &x 3858 &a[f(2)] 3859 &Point{2, 3} 3860 *p 3861 *pf(x) 3862 3863 var x *int = nil 3864 *x // causes a run-time panic 3865 &*x // causes a run-time panic 3866 </pre> 3867 3868 3869 <h3 id="Receive_operator">Receive operator</h3> 3870 3871 <p> 3872 For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>, 3873 the value of the receive operation <code><-ch</code> is the value received 3874 from the channel <code>ch</code>. The channel direction must permit receive operations, 3875 and the type of the receive operation is the element type of the channel. 3876 The expression blocks until a value is available. 3877 Receiving from a <code>nil</code> channel blocks forever. 3878 A receive operation on a <a href="#Close">closed</a> channel can always proceed 3879 immediately, yielding the element type's <a href="#The_zero_value">zero value</a> 3880 after any previously sent values have been received. 3881 </p> 3882 3883 <pre> 3884 v1 := <-ch 3885 v2 = <-ch 3886 f(<-ch) 3887 <-strobe // wait until clock pulse and discard received value 3888 </pre> 3889 3890 <p> 3891 A receive expression used in an <a href="#Assignments">assignment</a> or initialization of the special form 3892 </p> 3893 3894 <pre> 3895 x, ok = <-ch 3896 x, ok := <-ch 3897 var x, ok = <-ch 3898 var x, ok T = <-ch 3899 </pre> 3900 3901 <p> 3902 yields an additional untyped boolean result reporting whether the 3903 communication succeeded. The value of <code>ok</code> is <code>true</code> 3904 if the value received was delivered by a successful send operation to the 3905 channel, or <code>false</code> if it is a zero value generated because the 3906 channel is closed and empty. 3907 </p> 3908 3909 3910 <h3 id="Conversions">Conversions</h3> 3911 3912 <p> 3913 Conversions are expressions of the form <code>T(x)</code> 3914 where <code>T</code> is a type and <code>x</code> is an expression 3915 that can be converted to type <code>T</code>. 3916 </p> 3917 3918 <pre class="ebnf"> 3919 Conversion = Type "(" Expression [ "," ] ")" . 3920 </pre> 3921 3922 <p> 3923 If the type starts with the operator <code>*</code> or <code><-</code>, 3924 or if the type starts with the keyword <code>func</code> 3925 and has no result list, it must be parenthesized when 3926 necessary to avoid ambiguity: 3927 </p> 3928 3929 <pre> 3930 *Point(p) // same as *(Point(p)) 3931 (*Point)(p) // p is converted to *Point 3932 <-chan int(c) // same as <-(chan int(c)) 3933 (<-chan int)(c) // c is converted to <-chan int 3934 func()(x) // function signature func() x 3935 (func())(x) // x is converted to func() 3936 (func() int)(x) // x is converted to func() int 3937 func() int(x) // x is converted to func() int (unambiguous) 3938 </pre> 3939 3940 <p> 3941 A <a href="#Constants">constant</a> value <code>x</code> can be converted to 3942 type <code>T</code> if <code>x</code> is <a href="#Representability">representable</a> 3943 by a value of <code>T</code>. 3944 As a special case, an integer constant <code>x</code> can be converted to a 3945 <a href="#String_types">string type</a> using the 3946 <a href="#Conversions_to_and_from_a_string_type">same rule</a> 3947 as for non-constant <code>x</code>. 3948 </p> 3949 3950 <p> 3951 Converting a constant yields a typed constant as result. 3952 </p> 3953 3954 <pre> 3955 uint(iota) // iota value of type uint 3956 float32(2.718281828) // 2.718281828 of type float32 3957 complex128(1) // 1.0 + 0.0i of type complex128 3958 float32(0.49999999) // 0.5 of type float32 3959 float64(-1e-1000) // 0.0 of type float64 3960 string('x') // "x" of type string 3961 string(0x266c) // "♬" of type string 3962 MyString("foo" + "bar") // "foobar" of type MyString 3963 string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant 3964 (*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type 3965 int(1.2) // illegal: 1.2 cannot be represented as an int 3966 string(65.0) // illegal: 65.0 is not an integer constant 3967 </pre> 3968 3969 <p> 3970 A non-constant value <code>x</code> can be converted to type <code>T</code> 3971 in any of these cases: 3972 </p> 3973 3974 <ul> 3975 <li> 3976 <code>x</code> is <a href="#Assignability">assignable</a> 3977 to <code>T</code>. 3978 </li> 3979 <li> 3980 ignoring struct tags (see below), 3981 <code>x</code>'s type and <code>T</code> have <a href="#Type_identity">identical</a> 3982 <a href="#Types">underlying types</a>. 3983 </li> 3984 <li> 3985 ignoring struct tags (see below), 3986 <code>x</code>'s type and <code>T</code> are pointer types 3987 that are not <a href="#Type_definitions">defined types</a>, 3988 and their pointer base types have identical underlying types. 3989 </li> 3990 <li> 3991 <code>x</code>'s type and <code>T</code> are both integer or floating 3992 point types. 3993 </li> 3994 <li> 3995 <code>x</code>'s type and <code>T</code> are both complex types. 3996 </li> 3997 <li> 3998 <code>x</code> is an integer or a slice of bytes or runes 3999 and <code>T</code> is a string type. 4000 </li> 4001 <li> 4002 <code>x</code> is a string and <code>T</code> is a slice of bytes or runes. 4003 </li> 4004 </ul> 4005 4006 <p> 4007 <a href="#Struct_types">Struct tags</a> are ignored when comparing struct types 4008 for identity for the purpose of conversion: 4009 </p> 4010 4011 <pre> 4012 type Person struct { 4013 Name string 4014 Address *struct { 4015 Street string 4016 City string 4017 } 4018 } 4019 4020 var data *struct { 4021 Name string `json:"name"` 4022 Address *struct { 4023 Street string `json:"street"` 4024 City string `json:"city"` 4025 } `json:"address"` 4026 } 4027 4028 var person = (*Person)(data) // ignoring tags, the underlying types are identical 4029 </pre> 4030 4031 <p> 4032 Specific rules apply to (non-constant) conversions between numeric types or 4033 to and from a string type. 4034 These conversions may change the representation of <code>x</code> 4035 and incur a run-time cost. 4036 All other conversions only change the type but not the representation 4037 of <code>x</code>. 4038 </p> 4039 4040 <p> 4041 There is no linguistic mechanism to convert between pointers and integers. 4042 The package <a href="#Package_unsafe"><code>unsafe</code></a> 4043 implements this functionality under 4044 restricted circumstances. 4045 </p> 4046 4047 <h4>Conversions between numeric types</h4> 4048 4049 <p> 4050 For the conversion of non-constant numeric values, the following rules apply: 4051 </p> 4052 4053 <ol> 4054 <li> 4055 When converting between integer types, if the value is a signed integer, it is 4056 sign extended to implicit infinite precision; otherwise it is zero extended. 4057 It is then truncated to fit in the result type's size. 4058 For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>. 4059 The conversion always yields a valid value; there is no indication of overflow. 4060 </li> 4061 <li> 4062 When converting a floating-point number to an integer, the fraction is discarded 4063 (truncation towards zero). 4064 </li> 4065 <li> 4066 When converting an integer or floating-point number to a floating-point type, 4067 or a complex number to another complex type, the result value is rounded 4068 to the precision specified by the destination type. 4069 For instance, the value of a variable <code>x</code> of type <code>float32</code> 4070 may be stored using additional precision beyond that of an IEEE-754 32-bit number, 4071 but float32(x) represents the result of rounding <code>x</code>'s value to 4072 32-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits 4073 of precision, but <code>float32(x + 0.1)</code> does not. 4074 </li> 4075 </ol> 4076 4077 <p> 4078 In all non-constant conversions involving floating-point or complex values, 4079 if the result type cannot represent the value the conversion 4080 succeeds but the result value is implementation-dependent. 4081 </p> 4082 4083 <h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4> 4084 4085 <ol> 4086 <li> 4087 Converting a signed or unsigned integer value to a string type yields a 4088 string containing the UTF-8 representation of the integer. Values outside 4089 the range of valid Unicode code points are converted to <code>"\uFFFD"</code>. 4090 4091 <pre> 4092 string('a') // "a" 4093 string(-1) // "\ufffd" == "\xef\xbf\xbd" 4094 string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8" 4095 type MyString string 4096 MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5" 4097 </pre> 4098 </li> 4099 4100 <li> 4101 Converting a slice of bytes to a string type yields 4102 a string whose successive bytes are the elements of the slice. 4103 4104 <pre> 4105 string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø" 4106 string([]byte{}) // "" 4107 string([]byte(nil)) // "" 4108 4109 type MyBytes []byte 4110 string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø" 4111 </pre> 4112 </li> 4113 4114 <li> 4115 Converting a slice of runes to a string type yields 4116 a string that is the concatenation of the individual rune values 4117 converted to strings. 4118 4119 <pre> 4120 string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" 4121 string([]rune{}) // "" 4122 string([]rune(nil)) // "" 4123 4124 type MyRunes []rune 4125 string(MyRunes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" 4126 </pre> 4127 </li> 4128 4129 <li> 4130 Converting a value of a string type to a slice of bytes type 4131 yields a slice whose successive elements are the bytes of the string. 4132 4133 <pre> 4134 []byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} 4135 []byte("") // []byte{} 4136 4137 MyBytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} 4138 </pre> 4139 </li> 4140 4141 <li> 4142 Converting a value of a string type to a slice of runes type 4143 yields a slice containing the individual Unicode code points of the string. 4144 4145 <pre> 4146 []rune(MyString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4} 4147 []rune("") // []rune{} 4148 4149 MyRunes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4} 4150 </pre> 4151 </li> 4152 </ol> 4153 4154 4155 <h3 id="Constant_expressions">Constant expressions</h3> 4156 4157 <p> 4158 Constant expressions may contain only <a href="#Constants">constant</a> 4159 operands and are evaluated at compile time. 4160 </p> 4161 4162 <p> 4163 Untyped boolean, numeric, and string constants may be used as operands 4164 wherever it is legal to use an operand of boolean, numeric, or string type, 4165 respectively. 4166 Except for shift operations, if the operands of a binary operation are 4167 different kinds of untyped constants, the operation and, for non-boolean operations, the result use 4168 the kind that appears later in this list: integer, rune, floating-point, complex. 4169 For example, an untyped integer constant divided by an 4170 untyped complex constant yields an untyped complex constant. 4171 </p> 4172 4173 <p> 4174 A constant <a href="#Comparison_operators">comparison</a> always yields 4175 an untyped boolean constant. If the left operand of a constant 4176 <a href="#Operators">shift expression</a> is an untyped constant, the 4177 result is an integer constant; otherwise it is a constant of the same 4178 type as the left operand, which must be of 4179 <a href="#Numeric_types">integer type</a>. 4180 Applying all other operators to untyped constants results in an untyped 4181 constant of the same kind (that is, a boolean, integer, floating-point, 4182 complex, or string constant). 4183 </p> 4184 4185 <pre> 4186 const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant) 4187 const b = 15 / 4 // b == 3 (untyped integer constant) 4188 const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant) 4189 const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division) 4190 const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division) 4191 const d = 1 << 3.0 // d == 8 (untyped integer constant) 4192 const e = 1.0 << 3 // e == 8 (untyped integer constant) 4193 const f = int32(1) << 33 // illegal (constant 8589934592 overflows int32) 4194 const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant) 4195 const h = "foo" > "bar" // h == true (untyped boolean constant) 4196 const j = true // j == true (untyped boolean constant) 4197 const k = 'w' + 1 // k == 'x' (untyped rune constant) 4198 const l = "hi" // l == "hi" (untyped string constant) 4199 const m = string(k) // m == "x" (type string) 4200 const Σ = 1 - 0.707i // (untyped complex constant) 4201 const Δ = Σ + 2.0e-4 // (untyped complex constant) 4202 const Φ = iota*1i - 1/1i // (untyped complex constant) 4203 </pre> 4204 4205 <p> 4206 Applying the built-in function <code>complex</code> to untyped 4207 integer, rune, or floating-point constants yields 4208 an untyped complex constant. 4209 </p> 4210 4211 <pre> 4212 const ic = complex(0, c) // ic == 3.75i (untyped complex constant) 4213 const iΘ = complex(0, Θ) // iΘ == 1i (type complex128) 4214 </pre> 4215 4216 <p> 4217 Constant expressions are always evaluated exactly; intermediate values and the 4218 constants themselves may require precision significantly larger than supported 4219 by any predeclared type in the language. The following are legal declarations: 4220 </p> 4221 4222 <pre> 4223 const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (untyped integer constant) 4224 const Four int8 = Huge >> 98 // Four == 4 (type int8) 4225 </pre> 4226 4227 <p> 4228 The divisor of a constant division or remainder operation must not be zero: 4229 </p> 4230 4231 <pre> 4232 3.14 / 0.0 // illegal: division by zero 4233 </pre> 4234 4235 <p> 4236 The values of <i>typed</i> constants must always be accurately 4237 <a href="#Representability">representable</a> by values 4238 of the constant type. The following constant expressions are illegal: 4239 </p> 4240 4241 <pre> 4242 uint(-1) // -1 cannot be represented as a uint 4243 int(3.14) // 3.14 cannot be represented as an int 4244 int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64 4245 Four * 300 // operand 300 cannot be represented as an int8 (type of Four) 4246 Four * 100 // product 400 cannot be represented as an int8 (type of Four) 4247 </pre> 4248 4249 <p> 4250 The mask used by the unary bitwise complement operator <code>^</code> matches 4251 the rule for non-constants: the mask is all 1s for unsigned constants 4252 and -1 for signed and untyped constants. 4253 </p> 4254 4255 <pre> 4256 ^1 // untyped integer constant, equal to -2 4257 uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8 4258 ^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE) 4259 int8(^1) // same as int8(-2) 4260 ^int8(1) // same as -1 ^ int8(1) = -2 4261 </pre> 4262 4263 <p> 4264 Implementation restriction: A compiler may use rounding while 4265 computing untyped floating-point or complex constant expressions; see 4266 the implementation restriction in the section 4267 on <a href="#Constants">constants</a>. This rounding may cause a 4268 floating-point constant expression to be invalid in an integer 4269 context, even if it would be integral when calculated using infinite 4270 precision, and vice versa. 4271 </p> 4272 4273 4274 <h3 id="Order_of_evaluation">Order of evaluation</h3> 4275 4276 <p> 4277 At package level, <a href="#Package_initialization">initialization dependencies</a> 4278 determine the evaluation order of individual initialization expressions in 4279 <a href="#Variable_declarations">variable declarations</a>. 4280 Otherwise, when evaluating the <a href="#Operands">operands</a> of an 4281 expression, assignment, or 4282 <a href="#Return_statements">return statement</a>, 4283 all function calls, method calls, and 4284 communication operations are evaluated in lexical left-to-right 4285 order. 4286 </p> 4287 4288 <p> 4289 For example, in the (function-local) assignment 4290 </p> 4291 <pre> 4292 y[f()], ok = g(h(), i()+x[j()], <-c), k() 4293 </pre> 4294 <p> 4295 the function calls and communication happen in the order 4296 <code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>, 4297 <code><-c</code>, <code>g()</code>, and <code>k()</code>. 4298 However, the order of those events compared to the evaluation 4299 and indexing of <code>x</code> and the evaluation 4300 of <code>y</code> is not specified. 4301 </p> 4302 4303 <pre> 4304 a := 1 4305 f := func() int { a++; return a } 4306 x := []int{a, f()} // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified 4307 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 4308 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 4309 </pre> 4310 4311 <p> 4312 At package level, initialization dependencies override the left-to-right rule 4313 for individual initialization expressions, but not for operands within each 4314 expression: 4315 </p> 4316 4317 <pre> 4318 var a, b, c = f() + v(), g(), sqr(u()) + v() 4319 4320 func f() int { return c } 4321 func g() int { return a } 4322 func sqr(x int) int { return x*x } 4323 4324 // functions u and v are independent of all other variables and functions 4325 </pre> 4326 4327 <p> 4328 The function calls happen in the order 4329 <code>u()</code>, <code>sqr()</code>, <code>v()</code>, 4330 <code>f()</code>, <code>v()</code>, and <code>g()</code>. 4331 </p> 4332 4333 <p> 4334 Floating-point operations within a single expression are evaluated according to 4335 the associativity of the operators. Explicit parentheses affect the evaluation 4336 by overriding the default associativity. 4337 In the expression <code>x + (y + z)</code> the addition <code>y + z</code> 4338 is performed before adding <code>x</code>. 4339 </p> 4340 4341 <h2 id="Statements">Statements</h2> 4342 4343 <p> 4344 Statements control execution. 4345 </p> 4346 4347 <pre class="ebnf"> 4348 Statement = 4349 Declaration | LabeledStmt | SimpleStmt | 4350 GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt | 4351 FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt | 4352 DeferStmt . 4353 4354 SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl . 4355 </pre> 4356 4357 <h3 id="Terminating_statements">Terminating statements</h3> 4358 4359 <p> 4360 A <i>terminating statement</i> prevents execution of all statements that lexically 4361 appear after it in the same <a href="#Blocks">block</a>. The following statements 4362 are terminating: 4363 </p> 4364 4365 <ol> 4366 <li> 4367 A <a href="#Return_statements">"return"</a> or 4368 <a href="#Goto_statements">"goto"</a> statement. 4369 <!-- ul below only for regular layout --> 4370 <ul> </ul> 4371 </li> 4372 4373 <li> 4374 A call to the built-in function 4375 <a href="#Handling_panics"><code>panic</code></a>. 4376 <!-- ul below only for regular layout --> 4377 <ul> </ul> 4378 </li> 4379 4380 <li> 4381 A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement. 4382 <!-- ul below only for regular layout --> 4383 <ul> </ul> 4384 </li> 4385 4386 <li> 4387 An <a href="#If_statements">"if" statement</a> in which: 4388 <ul> 4389 <li>the "else" branch is present, and</li> 4390 <li>both branches are terminating statements.</li> 4391 </ul> 4392 </li> 4393 4394 <li> 4395 A <a href="#For_statements">"for" statement</a> in which: 4396 <ul> 4397 <li>there are no "break" statements referring to the "for" statement, and</li> 4398 <li>the loop condition is absent.</li> 4399 </ul> 4400 </li> 4401 4402 <li> 4403 A <a href="#Switch_statements">"switch" statement</a> in which: 4404 <ul> 4405 <li>there are no "break" statements referring to the "switch" statement,</li> 4406 <li>there is a default case, and</li> 4407 <li>the statement lists in each case, including the default, end in a terminating 4408 statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough" 4409 statement</a>.</li> 4410 </ul> 4411 </li> 4412 4413 <li> 4414 A <a href="#Select_statements">"select" statement</a> in which: 4415 <ul> 4416 <li>there are no "break" statements referring to the "select" statement, and</li> 4417 <li>the statement lists in each case, including the default if present, 4418 end in a terminating statement.</li> 4419 </ul> 4420 </li> 4421 4422 <li> 4423 A <a href="#Labeled_statements">labeled statement</a> labeling 4424 a terminating statement. 4425 </li> 4426 </ol> 4427 4428 <p> 4429 All other statements are not terminating. 4430 </p> 4431 4432 <p> 4433 A <a href="#Blocks">statement list</a> ends in a terminating statement if the list 4434 is not empty and its final non-empty statement is terminating. 4435 </p> 4436 4437 4438 <h3 id="Empty_statements">Empty statements</h3> 4439 4440 <p> 4441 The empty statement does nothing. 4442 </p> 4443 4444 <pre class="ebnf"> 4445 EmptyStmt = . 4446 </pre> 4447 4448 4449 <h3 id="Labeled_statements">Labeled statements</h3> 4450 4451 <p> 4452 A labeled statement may be the target of a <code>goto</code>, 4453 <code>break</code> or <code>continue</code> statement. 4454 </p> 4455 4456 <pre class="ebnf"> 4457 LabeledStmt = Label ":" Statement . 4458 Label = identifier . 4459 </pre> 4460 4461 <pre> 4462 Error: log.Panic("error encountered") 4463 </pre> 4464 4465 4466 <h3 id="Expression_statements">Expression statements</h3> 4467 4468 <p> 4469 With the exception of specific built-in functions, 4470 function and method <a href="#Calls">calls</a> and 4471 <a href="#Receive_operator">receive operations</a> 4472 can appear in statement context. Such statements may be parenthesized. 4473 </p> 4474 4475 <pre class="ebnf"> 4476 ExpressionStmt = Expression . 4477 </pre> 4478 4479 <p> 4480 The following built-in functions are not permitted in statement context: 4481 </p> 4482 4483 <pre> 4484 append cap complex imag len make new real 4485 unsafe.Alignof unsafe.Offsetof unsafe.Sizeof 4486 </pre> 4487 4488 <pre> 4489 h(x+y) 4490 f.Close() 4491 <-ch 4492 (<-ch) 4493 len("foo") // illegal if len is the built-in function 4494 </pre> 4495 4496 4497 <h3 id="Send_statements">Send statements</h3> 4498 4499 <p> 4500 A send statement sends a value on a channel. 4501 The channel expression must be of <a href="#Channel_types">channel type</a>, 4502 the channel direction must permit send operations, 4503 and the type of the value to be sent must be <a href="#Assignability">assignable</a> 4504 to the channel's element type. 4505 </p> 4506 4507 <pre class="ebnf"> 4508 SendStmt = Channel "<-" Expression . 4509 Channel = Expression . 4510 </pre> 4511 4512 <p> 4513 Both the channel and the value expression are evaluated before communication 4514 begins. Communication blocks until the send can proceed. 4515 A send on an unbuffered channel can proceed if a receiver is ready. 4516 A send on a buffered channel can proceed if there is room in the buffer. 4517 A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>. 4518 A send on a <code>nil</code> channel blocks forever. 4519 </p> 4520 4521 <pre> 4522 ch <- 3 // send value 3 to channel ch 4523 </pre> 4524 4525 4526 <h3 id="IncDec_statements">IncDec statements</h3> 4527 4528 <p> 4529 The "++" and "--" statements increment or decrement their operands 4530 by the untyped <a href="#Constants">constant</a> <code>1</code>. 4531 As with an assignment, the operand must be <a href="#Address_operators">addressable</a> 4532 or a map index expression. 4533 </p> 4534 4535 <pre class="ebnf"> 4536 IncDecStmt = Expression ( "++" | "--" ) . 4537 </pre> 4538 4539 <p> 4540 The following <a href="#Assignments">assignment statements</a> are semantically 4541 equivalent: 4542 </p> 4543 4544 <pre class="grammar"> 4545 IncDec statement Assignment 4546 x++ x += 1 4547 x-- x -= 1 4548 </pre> 4549 4550 4551 <h3 id="Assignments">Assignments</h3> 4552 4553 <pre class="ebnf"> 4554 Assignment = ExpressionList assign_op ExpressionList . 4555 4556 assign_op = [ add_op | mul_op ] "=" . 4557 </pre> 4558 4559 <p> 4560 Each left-hand side operand must be <a href="#Address_operators">addressable</a>, 4561 a map index expression, or (for <code>=</code> assignments only) the 4562 <a href="#Blank_identifier">blank identifier</a>. 4563 Operands may be parenthesized. 4564 </p> 4565 4566 <pre> 4567 x = 1 4568 *p = f() 4569 a[i] = 23 4570 (k) = <-ch // same as: k = <-ch 4571 </pre> 4572 4573 <p> 4574 An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code> 4575 <code>y</code> where <i>op</i> is a binary <a href="#Arithmetic_operators">arithmetic operator</a> 4576 is equivalent to <code>x</code> <code>=</code> <code>x</code> <i>op</i> 4577 <code>(y)</code> but evaluates <code>x</code> 4578 only once. The <i>op</i><code>=</code> construct is a single token. 4579 In assignment operations, both the left- and right-hand expression lists 4580 must contain exactly one single-valued expression, and the left-hand 4581 expression must not be the blank identifier. 4582 </p> 4583 4584 <pre> 4585 a[i] <<= 2 4586 i &^= 1<<n 4587 </pre> 4588 4589 <p> 4590 A tuple assignment assigns the individual elements of a multi-valued 4591 operation to a list of variables. There are two forms. In the 4592 first, the right hand operand is a single multi-valued expression 4593 such as a function call, a <a href="#Channel_types">channel</a> or 4594 <a href="#Map_types">map</a> operation, or a <a href="#Type_assertions">type assertion</a>. 4595 The number of operands on the left 4596 hand side must match the number of values. For instance, if 4597 <code>f</code> is a function returning two values, 4598 </p> 4599 4600 <pre> 4601 x, y = f() 4602 </pre> 4603 4604 <p> 4605 assigns the first value to <code>x</code> and the second to <code>y</code>. 4606 In the second form, the number of operands on the left must equal the number 4607 of expressions on the right, each of which must be single-valued, and the 4608 <i>n</i>th expression on the right is assigned to the <i>n</i>th 4609 operand on the left: 4610 </p> 4611 4612 <pre> 4613 one, two, three = '一', '二', '三' 4614 </pre> 4615 4616 <p> 4617 The <a href="#Blank_identifier">blank identifier</a> provides a way to 4618 ignore right-hand side values in an assignment: 4619 </p> 4620 4621 <pre> 4622 _ = x // evaluate x but ignore it 4623 x, _ = f() // evaluate f() but ignore second result value 4624 </pre> 4625 4626 <p> 4627 The assignment proceeds in two phases. 4628 First, the operands of <a href="#Index_expressions">index expressions</a> 4629 and <a href="#Address_operators">pointer indirections</a> 4630 (including implicit pointer indirections in <a href="#Selectors">selectors</a>) 4631 on the left and the expressions on the right are all 4632 <a href="#Order_of_evaluation">evaluated in the usual order</a>. 4633 Second, the assignments are carried out in left-to-right order. 4634 </p> 4635 4636 <pre> 4637 a, b = b, a // exchange a and b 4638 4639 x := []int{1, 2, 3} 4640 i := 0 4641 i, x[i] = 1, 2 // set i = 1, x[0] = 2 4642 4643 i = 0 4644 x[i], i = 2, 1 // set x[0] = 2, i = 1 4645 4646 x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end) 4647 4648 x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5. 4649 4650 type Point struct { x, y int } 4651 var p *Point 4652 x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7 4653 4654 i = 2 4655 x = []int{3, 5, 7} 4656 for i, x[i] = range x { // set i, x[2] = 0, x[0] 4657 break 4658 } 4659 // after this loop, i == 0 and x == []int{3, 5, 3} 4660 </pre> 4661 4662 <p> 4663 In assignments, each value must be <a href="#Assignability">assignable</a> 4664 to the type of the operand to which it is assigned, with the following special cases: 4665 </p> 4666 4667 <ol> 4668 <li> 4669 Any typed value may be assigned to the blank identifier. 4670 </li> 4671 4672 <li> 4673 If an untyped constant 4674 is assigned to a variable of interface type or the blank identifier, 4675 the constant is first <a href="#Conversions">converted</a> to its 4676 <a href="#Constants">default type</a>. 4677 </li> 4678 4679 <li> 4680 If an untyped boolean value is assigned to a variable of interface type or 4681 the blank identifier, it is first converted to type <code>bool</code>. 4682 </li> 4683 </ol> 4684 4685 <h3 id="If_statements">If statements</h3> 4686 4687 <p> 4688 "If" statements specify the conditional execution of two branches 4689 according to the value of a boolean expression. If the expression 4690 evaluates to true, the "if" branch is executed, otherwise, if 4691 present, the "else" branch is executed. 4692 </p> 4693 4694 <pre class="ebnf"> 4695 IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] . 4696 </pre> 4697 4698 <pre> 4699 if x > max { 4700 x = max 4701 } 4702 </pre> 4703 4704 <p> 4705 The expression may be preceded by a simple statement, which 4706 executes before the expression is evaluated. 4707 </p> 4708 4709 <pre> 4710 if x := f(); x < y { 4711 return x 4712 } else if x > z { 4713 return z 4714 } else { 4715 return y 4716 } 4717 </pre> 4718 4719 4720 <h3 id="Switch_statements">Switch statements</h3> 4721 4722 <p> 4723 "Switch" statements provide multi-way execution. 4724 An expression or type specifier is compared to the "cases" 4725 inside the "switch" to determine which branch 4726 to execute. 4727 </p> 4728 4729 <pre class="ebnf"> 4730 SwitchStmt = ExprSwitchStmt | TypeSwitchStmt . 4731 </pre> 4732 4733 <p> 4734 There are two forms: expression switches and type switches. 4735 In an expression switch, the cases contain expressions that are compared 4736 against the value of the switch expression. 4737 In a type switch, the cases contain types that are compared against the 4738 type of a specially annotated switch expression. 4739 The switch expression is evaluated exactly once in a switch statement. 4740 </p> 4741 4742 <h4 id="Expression_switches">Expression switches</h4> 4743 4744 <p> 4745 In an expression switch, 4746 the switch expression is evaluated and 4747 the case expressions, which need not be constants, 4748 are evaluated left-to-right and top-to-bottom; the first one that equals the 4749 switch expression 4750 triggers execution of the statements of the associated case; 4751 the other cases are skipped. 4752 If no case matches and there is a "default" case, 4753 its statements are executed. 4754 There can be at most one default case and it may appear anywhere in the 4755 "switch" statement. 4756 A missing switch expression is equivalent to the boolean value 4757 <code>true</code>. 4758 </p> 4759 4760 <pre class="ebnf"> 4761 ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" . 4762 ExprCaseClause = ExprSwitchCase ":" StatementList . 4763 ExprSwitchCase = "case" ExpressionList | "default" . 4764 </pre> 4765 4766 <p> 4767 If the switch expression evaluates to an untyped constant, it is first 4768 <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>; 4769 if it is an untyped boolean value, it is first converted to type <code>bool</code>. 4770 The predeclared untyped value <code>nil</code> cannot be used as a switch expression. 4771 </p> 4772 4773 <p> 4774 If a case expression is untyped, it is first <a href="#Conversions">converted</a> 4775 to the type of the switch expression. 4776 For each (possibly converted) case expression <code>x</code> and the value <code>t</code> 4777 of the switch expression, <code>x == t</code> must be a valid <a href="#Comparison_operators">comparison</a>. 4778 </p> 4779 4780 <p> 4781 In other words, the switch expression is treated as if it were used to declare and 4782 initialize a temporary variable <code>t</code> without explicit type; it is that 4783 value of <code>t</code> against which each case expression <code>x</code> is tested 4784 for equality. 4785 </p> 4786 4787 <p> 4788 In a case or default clause, the last non-empty statement 4789 may be a (possibly <a href="#Labeled_statements">labeled</a>) 4790 <a href="#Fallthrough_statements">"fallthrough" statement</a> to 4791 indicate that control should flow from the end of this clause to 4792 the first statement of the next clause. 4793 Otherwise control flows to the end of the "switch" statement. 4794 A "fallthrough" statement may appear as the last statement of all 4795 but the last clause of an expression switch. 4796 </p> 4797 4798 <p> 4799 The switch expression may be preceded by a simple statement, which 4800 executes before the expression is evaluated. 4801 </p> 4802 4803 <pre> 4804 switch tag { 4805 default: s3() 4806 case 0, 1, 2, 3: s1() 4807 case 4, 5, 6, 7: s2() 4808 } 4809 4810 switch x := f(); { // missing switch expression means "true" 4811 case x < 0: return -x 4812 default: return x 4813 } 4814 4815 switch { 4816 case x < y: f1() 4817 case x < z: f2() 4818 case x == 4: f3() 4819 } 4820 </pre> 4821 4822 <p> 4823 Implementation restriction: A compiler may disallow multiple case 4824 expressions evaluating to the same constant. 4825 For instance, the current compilers disallow duplicate integer, 4826 floating point, or string constants in case expressions. 4827 </p> 4828 4829 <h4 id="Type_switches">Type switches</h4> 4830 4831 <p> 4832 A type switch compares types rather than values. It is otherwise similar 4833 to an expression switch. It is marked by a special switch expression that 4834 has the form of a <a href="#Type_assertions">type assertion</a> 4835 using the reserved word <code>type</code> rather than an actual type: 4836 </p> 4837 4838 <pre> 4839 switch x.(type) { 4840 // cases 4841 } 4842 </pre> 4843 4844 <p> 4845 Cases then match actual types <code>T</code> against the dynamic type of the 4846 expression <code>x</code>. As with type assertions, <code>x</code> must be of 4847 <a href="#Interface_types">interface type</a>, and each non-interface type 4848 <code>T</code> listed in a case must implement the type of <code>x</code>. 4849 The types listed in the cases of a type switch must all be 4850 <a href="#Type_identity">different</a>. 4851 </p> 4852 4853 <pre class="ebnf"> 4854 TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" . 4855 TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" . 4856 TypeCaseClause = TypeSwitchCase ":" StatementList . 4857 TypeSwitchCase = "case" TypeList | "default" . 4858 TypeList = Type { "," Type } . 4859 </pre> 4860 4861 <p> 4862 The TypeSwitchGuard may include a 4863 <a href="#Short_variable_declarations">short variable declaration</a>. 4864 When that form is used, the variable is declared at the end of the 4865 TypeSwitchCase in the <a href="#Blocks">implicit block</a> of each clause. 4866 In clauses with a case listing exactly one type, the variable 4867 has that type; otherwise, the variable has the type of the expression 4868 in the TypeSwitchGuard. 4869 </p> 4870 4871 <p> 4872 Instead of a type, a case may use the predeclared identifier 4873 <a href="#Predeclared_identifiers"><code>nil</code></a>; 4874 that case is selected when the expression in the TypeSwitchGuard 4875 is a <code>nil</code> interface value. 4876 There may be at most one <code>nil</code> case. 4877 </p> 4878 4879 <p> 4880 Given an expression <code>x</code> of type <code>interface{}</code>, 4881 the following type switch: 4882 </p> 4883 4884 <pre> 4885 switch i := x.(type) { 4886 case nil: 4887 printString("x is nil") // type of i is type of x (interface{}) 4888 case int: 4889 printInt(i) // type of i is int 4890 case float64: 4891 printFloat64(i) // type of i is float64 4892 case func(int) float64: 4893 printFunction(i) // type of i is func(int) float64 4894 case bool, string: 4895 printString("type is bool or string") // type of i is type of x (interface{}) 4896 default: 4897 printString("don't know the type") // type of i is type of x (interface{}) 4898 } 4899 </pre> 4900 4901 <p> 4902 could be rewritten: 4903 </p> 4904 4905 <pre> 4906 v := x // x is evaluated exactly once 4907 if v == nil { 4908 i := v // type of i is type of x (interface{}) 4909 printString("x is nil") 4910 } else if i, isInt := v.(int); isInt { 4911 printInt(i) // type of i is int 4912 } else if i, isFloat64 := v.(float64); isFloat64 { 4913 printFloat64(i) // type of i is float64 4914 } else if i, isFunc := v.(func(int) float64); isFunc { 4915 printFunction(i) // type of i is func(int) float64 4916 } else { 4917 _, isBool := v.(bool) 4918 _, isString := v.(string) 4919 if isBool || isString { 4920 i := v // type of i is type of x (interface{}) 4921 printString("type is bool or string") 4922 } else { 4923 i := v // type of i is type of x (interface{}) 4924 printString("don't know the type") 4925 } 4926 } 4927 </pre> 4928 4929 <p> 4930 The type switch guard may be preceded by a simple statement, which 4931 executes before the guard is evaluated. 4932 </p> 4933 4934 <p> 4935 The "fallthrough" statement is not permitted in a type switch. 4936 </p> 4937 4938 <h3 id="For_statements">For statements</h3> 4939 4940 <p> 4941 A "for" statement specifies repeated execution of a block. There are three forms: 4942 The iteration may be controlled by a single condition, a "for" clause, or a "range" clause. 4943 </p> 4944 4945 <pre class="ebnf"> 4946 ForStmt = "for" [ Condition | ForClause | RangeClause ] Block . 4947 Condition = Expression . 4948 </pre> 4949 4950 <h4 id="For_condition">For statements with single condition</h4> 4951 4952 <p> 4953 In its simplest form, a "for" statement specifies the repeated execution of 4954 a block as long as a boolean condition evaluates to true. 4955 The condition is evaluated before each iteration. 4956 If the condition is absent, it is equivalent to the boolean value 4957 <code>true</code>. 4958 </p> 4959 4960 <pre> 4961 for a < b { 4962 a *= 2 4963 } 4964 </pre> 4965 4966 <h4 id="For_clause">For statements with <code>for</code> clause</h4> 4967 4968 <p> 4969 A "for" statement with a ForClause is also controlled by its condition, but 4970 additionally it may specify an <i>init</i> 4971 and a <i>post</i> statement, such as an assignment, 4972 an increment or decrement statement. The init statement may be a 4973 <a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not. 4974 Variables declared by the init statement are re-used in each iteration. 4975 </p> 4976 4977 <pre class="ebnf"> 4978 ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] . 4979 InitStmt = SimpleStmt . 4980 PostStmt = SimpleStmt . 4981 </pre> 4982 4983 <pre> 4984 for i := 0; i < 10; i++ { 4985 f(i) 4986 } 4987 </pre> 4988 4989 <p> 4990 If non-empty, the init statement is executed once before evaluating the 4991 condition for the first iteration; 4992 the post statement is executed after each execution of the block (and 4993 only if the block was executed). 4994 Any element of the ForClause may be empty but the 4995 <a href="#Semicolons">semicolons</a> are 4996 required unless there is only a condition. 4997 If the condition is absent, it is equivalent to the boolean value 4998 <code>true</code>. 4999 </p> 5000 5001 <pre> 5002 for cond { S() } is the same as for ; cond ; { S() } 5003 for { S() } is the same as for true { S() } 5004 </pre> 5005 5006 <h4 id="For_range">For statements with <code>range</code> clause</h4> 5007 5008 <p> 5009 A "for" statement with a "range" clause 5010 iterates through all entries of an array, slice, string or map, 5011 or values received on a channel. For each entry it assigns <i>iteration values</i> 5012 to corresponding <i>iteration variables</i> if present and then executes the block. 5013 </p> 5014 5015 <pre class="ebnf"> 5016 RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression . 5017 </pre> 5018 5019 <p> 5020 The expression on the right in the "range" clause is called the <i>range expression</i>, 5021 which may be an array, pointer to an array, slice, string, map, or channel permitting 5022 <a href="#Receive_operator">receive operations</a>. 5023 As with an assignment, if present the operands on the left must be 5024 <a href="#Address_operators">addressable</a> or map index expressions; they 5025 denote the iteration variables. If the range expression is a channel, at most 5026 one iteration variable is permitted, otherwise there may be up to two. 5027 If the last iteration variable is the <a href="#Blank_identifier">blank identifier</a>, 5028 the range clause is equivalent to the same clause without that identifier. 5029 </p> 5030 5031 <p> 5032 The range expression <code>x</code> is evaluated once before beginning the loop, 5033 with one exception: if at most one iteration variable is present and 5034 <code>len(x)</code> is <a href="#Length_and_capacity">constant</a>, 5035 the range expression is not evaluated. 5036 </p> 5037 5038 <p> 5039 Function calls on the left are evaluated once per iteration. 5040 For each iteration, iteration values are produced as follows 5041 if the respective iteration variables are present: 5042 </p> 5043 5044 <pre class="grammar"> 5045 Range expression 1st value 2nd value 5046 5047 array or slice a [n]E, *[n]E, or []E index i int a[i] E 5048 string s string type index i int see below rune 5049 map m map[K]V key k K m[k] V 5050 channel c chan E, <-chan E element e E 5051 </pre> 5052 5053 <ol> 5054 <li> 5055 For an array, pointer to array, or slice value <code>a</code>, the index iteration 5056 values are produced in increasing order, starting at element index 0. 5057 If at most one iteration variable is present, the range loop produces 5058 iteration values from 0 up to <code>len(a)-1</code> and does not index into the array 5059 or slice itself. For a <code>nil</code> slice, the number of iterations is 0. 5060 </li> 5061 5062 <li> 5063 For a string value, the "range" clause iterates over the Unicode code points 5064 in the string starting at byte index 0. On successive iterations, the index value will be the 5065 index of the first byte of successive UTF-8-encoded code points in the string, 5066 and the second value, of type <code>rune</code>, will be the value of 5067 the corresponding code point. If the iteration encounters an invalid 5068 UTF-8 sequence, the second value will be <code>0xFFFD</code>, 5069 the Unicode replacement character, and the next iteration will advance 5070 a single byte in the string. 5071 </li> 5072 5073 <li> 5074 The iteration order over maps is not specified 5075 and is not guaranteed to be the same from one iteration to the next. 5076 If a map entry that has not yet been reached is removed during iteration, 5077 the corresponding iteration value will not be produced. If a map entry is 5078 created during iteration, that entry may be produced during the iteration or 5079 may be skipped. The choice may vary for each entry created and from one 5080 iteration to the next. 5081 If the map is <code>nil</code>, the number of iterations is 0. 5082 </li> 5083 5084 <li> 5085 For channels, the iteration values produced are the successive values sent on 5086 the channel until the channel is <a href="#Close">closed</a>. If the channel 5087 is <code>nil</code>, the range expression blocks forever. 5088 </li> 5089 </ol> 5090 5091 <p> 5092 The iteration values are assigned to the respective 5093 iteration variables as in an <a href="#Assignments">assignment statement</a>. 5094 </p> 5095 5096 <p> 5097 The iteration variables may be declared by the "range" clause using a form of 5098 <a href="#Short_variable_declarations">short variable declaration</a> 5099 (<code>:=</code>). 5100 In this case their types are set to the types of the respective iteration values 5101 and their <a href="#Declarations_and_scope">scope</a> is the block of the "for" 5102 statement; they are re-used in each iteration. 5103 If the iteration variables are declared outside the "for" statement, 5104 after execution their values will be those of the last iteration. 5105 </p> 5106 5107 <pre> 5108 var testdata *struct { 5109 a *[7]int 5110 } 5111 for i, _ := range testdata.a { 5112 // testdata.a is never evaluated; len(testdata.a) is constant 5113 // i ranges from 0 to 6 5114 f(i) 5115 } 5116 5117 var a [10]string 5118 for i, s := range a { 5119 // type of i is int 5120 // type of s is string 5121 // s == a[i] 5122 g(i, s) 5123 } 5124 5125 var key string 5126 var val interface {} // element type of m is assignable to val 5127 m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6} 5128 for key, val = range m { 5129 h(key, val) 5130 } 5131 // key == last map key encountered in iteration 5132 // val == map[key] 5133 5134 var ch chan Work = producer() 5135 for w := range ch { 5136 doWork(w) 5137 } 5138 5139 // empty a channel 5140 for range ch {} 5141 </pre> 5142 5143 5144 <h3 id="Go_statements">Go statements</h3> 5145 5146 <p> 5147 A "go" statement starts the execution of a function call 5148 as an independent concurrent thread of control, or <i>goroutine</i>, 5149 within the same address space. 5150 </p> 5151 5152 <pre class="ebnf"> 5153 GoStmt = "go" Expression . 5154 </pre> 5155 5156 <p> 5157 The expression must be a function or method call; it cannot be parenthesized. 5158 Calls of built-in functions are restricted as for 5159 <a href="#Expression_statements">expression statements</a>. 5160 </p> 5161 5162 <p> 5163 The function value and parameters are 5164 <a href="#Calls">evaluated as usual</a> 5165 in the calling goroutine, but 5166 unlike with a regular call, program execution does not wait 5167 for the invoked function to complete. 5168 Instead, the function begins executing independently 5169 in a new goroutine. 5170 When the function terminates, its goroutine also terminates. 5171 If the function has any return values, they are discarded when the 5172 function completes. 5173 </p> 5174 5175 <pre> 5176 go Server() 5177 go func(ch chan<- bool) { for { sleep(10); ch <- true }} (c) 5178 </pre> 5179 5180 5181 <h3 id="Select_statements">Select statements</h3> 5182 5183 <p> 5184 A "select" statement chooses which of a set of possible 5185 <a href="#Send_statements">send</a> or 5186 <a href="#Receive_operator">receive</a> 5187 operations will proceed. 5188 It looks similar to a 5189 <a href="#Switch_statements">"switch"</a> statement but with the 5190 cases all referring to communication operations. 5191 </p> 5192 5193 <pre class="ebnf"> 5194 SelectStmt = "select" "{" { CommClause } "}" . 5195 CommClause = CommCase ":" StatementList . 5196 CommCase = "case" ( SendStmt | RecvStmt ) | "default" . 5197 RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr . 5198 RecvExpr = Expression . 5199 </pre> 5200 5201 <p> 5202 A case with a RecvStmt may assign the result of a RecvExpr to one or 5203 two variables, which may be declared using a 5204 <a href="#Short_variable_declarations">short variable declaration</a>. 5205 The RecvExpr must be a (possibly parenthesized) receive operation. 5206 There can be at most one default case and it may appear anywhere 5207 in the list of cases. 5208 </p> 5209 5210 <p> 5211 Execution of a "select" statement proceeds in several steps: 5212 </p> 5213 5214 <ol> 5215 <li> 5216 For all the cases in the statement, the channel operands of receive operations 5217 and the channel and right-hand-side expressions of send statements are 5218 evaluated exactly once, in source order, upon entering the "select" statement. 5219 The result is a set of channels to receive from or send to, 5220 and the corresponding values to send. 5221 Any side effects in that evaluation will occur irrespective of which (if any) 5222 communication operation is selected to proceed. 5223 Expressions on the left-hand side of a RecvStmt with a short variable declaration 5224 or assignment are not yet evaluated. 5225 </li> 5226 5227 <li> 5228 If one or more of the communications can proceed, 5229 a single one that can proceed is chosen via a uniform pseudo-random selection. 5230 Otherwise, if there is a default case, that case is chosen. 5231 If there is no default case, the "select" statement blocks until 5232 at least one of the communications can proceed. 5233 </li> 5234 5235 <li> 5236 Unless the selected case is the default case, the respective communication 5237 operation is executed. 5238 </li> 5239 5240 <li> 5241 If the selected case is a RecvStmt with a short variable declaration or 5242 an assignment, the left-hand side expressions are evaluated and the 5243 received value (or values) are assigned. 5244 </li> 5245 5246 <li> 5247 The statement list of the selected case is executed. 5248 </li> 5249 </ol> 5250 5251 <p> 5252 Since communication on <code>nil</code> channels can never proceed, 5253 a select with only <code>nil</code> channels and no default case blocks forever. 5254 </p> 5255 5256 <pre> 5257 var a []int 5258 var c, c1, c2, c3, c4 chan int 5259 var i1, i2 int 5260 select { 5261 case i1 = <-c1: 5262 print("received ", i1, " from c1\n") 5263 case c2 <- i2: 5264 print("sent ", i2, " to c2\n") 5265 case i3, ok := (<-c3): // same as: i3, ok := <-c3 5266 if ok { 5267 print("received ", i3, " from c3\n") 5268 } else { 5269 print("c3 is closed\n") 5270 } 5271 case a[f()] = <-c4: 5272 // same as: 5273 // case t := <-c4 5274 // a[f()] = t 5275 default: 5276 print("no communication\n") 5277 } 5278 5279 for { // send random sequence of bits to c 5280 select { 5281 case c <- 0: // note: no statement, no fallthrough, no folding of cases 5282 case c <- 1: 5283 } 5284 } 5285 5286 select {} // block forever 5287 </pre> 5288 5289 5290 <h3 id="Return_statements">Return statements</h3> 5291 5292 <p> 5293 A "return" statement in a function <code>F</code> terminates the execution 5294 of <code>F</code>, and optionally provides one or more result values. 5295 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code> 5296 are executed before <code>F</code> returns to its caller. 5297 </p> 5298 5299 <pre class="ebnf"> 5300 ReturnStmt = "return" [ ExpressionList ] . 5301 </pre> 5302 5303 <p> 5304 In a function without a result type, a "return" statement must not 5305 specify any result values. 5306 </p> 5307 <pre> 5308 func noResult() { 5309 return 5310 } 5311 </pre> 5312 5313 <p> 5314 There are three ways to return values from a function with a result 5315 type: 5316 </p> 5317 5318 <ol> 5319 <li>The return value or values may be explicitly listed 5320 in the "return" statement. Each expression must be single-valued 5321 and <a href="#Assignability">assignable</a> 5322 to the corresponding element of the function's result type. 5323 <pre> 5324 func simpleF() int { 5325 return 2 5326 } 5327 5328 func complexF1() (re float64, im float64) { 5329 return -7.0, -4.0 5330 } 5331 </pre> 5332 </li> 5333 <li>The expression list in the "return" statement may be a single 5334 call to a multi-valued function. The effect is as if each value 5335 returned from that function were assigned to a temporary 5336 variable with the type of the respective value, followed by a 5337 "return" statement listing these variables, at which point the 5338 rules of the previous case apply. 5339 <pre> 5340 func complexF2() (re float64, im float64) { 5341 return complexF1() 5342 } 5343 </pre> 5344 </li> 5345 <li>The expression list may be empty if the function's result 5346 type specifies names for its <a href="#Function_types">result parameters</a>. 5347 The result parameters act as ordinary local variables 5348 and the function may assign values to them as necessary. 5349 The "return" statement returns the values of these variables. 5350 <pre> 5351 func complexF3() (re float64, im float64) { 5352 re = 7.0 5353 im = 4.0 5354 return 5355 } 5356 5357 func (devnull) Write(p []byte) (n int, _ error) { 5358 n = len(p) 5359 return 5360 } 5361 </pre> 5362 </li> 5363 </ol> 5364 5365 <p> 5366 Regardless of how they are declared, all the result values are initialized to 5367 the <a href="#The_zero_value">zero values</a> for their type upon entry to the 5368 function. A "return" statement that specifies results sets the result parameters before 5369 any deferred functions are executed. 5370 </p> 5371 5372 <p> 5373 Implementation restriction: A compiler may disallow an empty expression list 5374 in a "return" statement if a different entity (constant, type, or variable) 5375 with the same name as a result parameter is in 5376 <a href="#Declarations_and_scope">scope</a> at the place of the return. 5377 </p> 5378 5379 <pre> 5380 func f(n int) (res int, err error) { 5381 if _, err := f(n-1); err != nil { 5382 return // invalid return statement: err is shadowed 5383 } 5384 return 5385 } 5386 </pre> 5387 5388 <h3 id="Break_statements">Break statements</h3> 5389 5390 <p> 5391 A "break" statement terminates execution of the innermost 5392 <a href="#For_statements">"for"</a>, 5393 <a href="#Switch_statements">"switch"</a>, or 5394 <a href="#Select_statements">"select"</a> statement 5395 within the same function. 5396 </p> 5397 5398 <pre class="ebnf"> 5399 BreakStmt = "break" [ Label ] . 5400 </pre> 5401 5402 <p> 5403 If there is a label, it must be that of an enclosing 5404 "for", "switch", or "select" statement, 5405 and that is the one whose execution terminates. 5406 </p> 5407 5408 <pre> 5409 OuterLoop: 5410 for i = 0; i < n; i++ { 5411 for j = 0; j < m; j++ { 5412 switch a[i][j] { 5413 case nil: 5414 state = Error 5415 break OuterLoop 5416 case item: 5417 state = Found 5418 break OuterLoop 5419 } 5420 } 5421 } 5422 </pre> 5423 5424 <h3 id="Continue_statements">Continue statements</h3> 5425 5426 <p> 5427 A "continue" statement begins the next iteration of the 5428 innermost <a href="#For_statements">"for" loop</a> at its post statement. 5429 The "for" loop must be within the same function. 5430 </p> 5431 5432 <pre class="ebnf"> 5433 ContinueStmt = "continue" [ Label ] . 5434 </pre> 5435 5436 <p> 5437 If there is a label, it must be that of an enclosing 5438 "for" statement, and that is the one whose execution 5439 advances. 5440 </p> 5441 5442 <pre> 5443 RowLoop: 5444 for y, row := range rows { 5445 for x, data := range row { 5446 if data == endOfRow { 5447 continue RowLoop 5448 } 5449 row[x] = data + bias(x, y) 5450 } 5451 } 5452 </pre> 5453 5454 <h3 id="Goto_statements">Goto statements</h3> 5455 5456 <p> 5457 A "goto" statement transfers control to the statement with the corresponding label 5458 within the same function. 5459 </p> 5460 5461 <pre class="ebnf"> 5462 GotoStmt = "goto" Label . 5463 </pre> 5464 5465 <pre> 5466 goto Error 5467 </pre> 5468 5469 <p> 5470 Executing the "goto" statement must not cause any variables to come into 5471 <a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto. 5472 For instance, this example: 5473 </p> 5474 5475 <pre> 5476 goto L // BAD 5477 v := 3 5478 L: 5479 </pre> 5480 5481 <p> 5482 is erroneous because the jump to label <code>L</code> skips 5483 the creation of <code>v</code>. 5484 </p> 5485 5486 <p> 5487 A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block. 5488 For instance, this example: 5489 </p> 5490 5491 <pre> 5492 if n%2 == 1 { 5493 goto L1 5494 } 5495 for n > 0 { 5496 f() 5497 n-- 5498 L1: 5499 f() 5500 n-- 5501 } 5502 </pre> 5503 5504 <p> 5505 is erroneous because the label <code>L1</code> is inside 5506 the "for" statement's block but the <code>goto</code> is not. 5507 </p> 5508 5509 <h3 id="Fallthrough_statements">Fallthrough statements</h3> 5510 5511 <p> 5512 A "fallthrough" statement transfers control to the first statement of the 5513 next case clause in an <a href="#Expression_switches">expression "switch" statement</a>. 5514 It may be used only as the final non-empty statement in such a clause. 5515 </p> 5516 5517 <pre class="ebnf"> 5518 FallthroughStmt = "fallthrough" . 5519 </pre> 5520 5521 5522 <h3 id="Defer_statements">Defer statements</h3> 5523 5524 <p> 5525 A "defer" statement invokes a function whose execution is deferred 5526 to the moment the surrounding function returns, either because the 5527 surrounding function executed a <a href="#Return_statements">return statement</a>, 5528 reached the end of its <a href="#Function_declarations">function body</a>, 5529 or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>. 5530 </p> 5531 5532 <pre class="ebnf"> 5533 DeferStmt = "defer" Expression . 5534 </pre> 5535 5536 <p> 5537 The expression must be a function or method call; it cannot be parenthesized. 5538 Calls of built-in functions are restricted as for 5539 <a href="#Expression_statements">expression statements</a>. 5540 </p> 5541 5542 <p> 5543 Each time a "defer" statement 5544 executes, the function value and parameters to the call are 5545 <a href="#Calls">evaluated as usual</a> 5546 and saved anew but the actual function is not invoked. 5547 Instead, deferred functions are invoked immediately before 5548 the surrounding function returns, in the reverse order 5549 they were deferred. 5550 If a deferred function value evaluates 5551 to <code>nil</code>, execution <a href="#Handling_panics">panics</a> 5552 when the function is invoked, not when the "defer" statement is executed. 5553 </p> 5554 5555 <p> 5556 For instance, if the deferred function is 5557 a <a href="#Function_literals">function literal</a> and the surrounding 5558 function has <a href="#Function_types">named result parameters</a> that 5559 are in scope within the literal, the deferred function may access and modify 5560 the result parameters before they are returned. 5561 If the deferred function has any return values, they are discarded when 5562 the function completes. 5563 (See also the section on <a href="#Handling_panics">handling panics</a>.) 5564 </p> 5565 5566 <pre> 5567 lock(l) 5568 defer unlock(l) // unlocking happens before surrounding function returns 5569 5570 // prints 3 2 1 0 before surrounding function returns 5571 for i := 0; i <= 3; i++ { 5572 defer fmt.Print(i) 5573 } 5574 5575 // f returns 1 5576 func f() (result int) { 5577 defer func() { 5578 result++ 5579 }() 5580 return 0 5581 } 5582 </pre> 5583 5584 <h2 id="Built-in_functions">Built-in functions</h2> 5585 5586 <p> 5587 Built-in functions are 5588 <a href="#Predeclared_identifiers">predeclared</a>. 5589 They are called like any other function but some of them 5590 accept a type instead of an expression as the first argument. 5591 </p> 5592 5593 <p> 5594 The built-in functions do not have standard Go types, 5595 so they can only appear in <a href="#Calls">call expressions</a>; 5596 they cannot be used as function values. 5597 </p> 5598 5599 <h3 id="Close">Close</h3> 5600 5601 <p> 5602 For a channel <code>c</code>, the built-in function <code>close(c)</code> 5603 records that no more values will be sent on the channel. 5604 It is an error if <code>c</code> is a receive-only channel. 5605 Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>. 5606 Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>. 5607 After calling <code>close</code>, and after any previously 5608 sent values have been received, receive operations will return 5609 the zero value for the channel's type without blocking. 5610 The multi-valued <a href="#Receive_operator">receive operation</a> 5611 returns a received value along with an indication of whether the channel is closed. 5612 </p> 5613 5614 5615 <h3 id="Length_and_capacity">Length and capacity</h3> 5616 5617 <p> 5618 The built-in functions <code>len</code> and <code>cap</code> take arguments 5619 of various types and return a result of type <code>int</code>. 5620 The implementation guarantees that the result always fits into an <code>int</code>. 5621 </p> 5622 5623 <pre class="grammar"> 5624 Call Argument type Result 5625 5626 len(s) string type string length in bytes 5627 [n]T, *[n]T array length (== n) 5628 []T slice length 5629 map[K]T map length (number of defined keys) 5630 chan T number of elements queued in channel buffer 5631 5632 cap(s) [n]T, *[n]T array length (== n) 5633 []T slice capacity 5634 chan T channel buffer capacity 5635 </pre> 5636 5637 <p> 5638 The capacity of a slice is the number of elements for which there is 5639 space allocated in the underlying array. 5640 At any time the following relationship holds: 5641 </p> 5642 5643 <pre> 5644 0 <= len(s) <= cap(s) 5645 </pre> 5646 5647 <p> 5648 The length of a <code>nil</code> slice, map or channel is 0. 5649 The capacity of a <code>nil</code> slice or channel is 0. 5650 </p> 5651 5652 <p> 5653 The expression <code>len(s)</code> is <a href="#Constants">constant</a> if 5654 <code>s</code> is a string constant. The expressions <code>len(s)</code> and 5655 <code>cap(s)</code> are constants if the type of <code>s</code> is an array 5656 or pointer to an array and the expression <code>s</code> does not contain 5657 <a href="#Receive_operator">channel receives</a> or (non-constant) 5658 <a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated. 5659 Otherwise, invocations of <code>len</code> and <code>cap</code> are not 5660 constant and <code>s</code> is evaluated. 5661 </p> 5662 5663 <pre> 5664 const ( 5665 c1 = imag(2i) // imag(2i) = 2.0 is a constant 5666 c2 = len([10]float64{2}) // [10]float64{2} contains no function calls 5667 c3 = len([10]float64{c1}) // [10]float64{c1} contains no function calls 5668 c4 = len([10]float64{imag(2i)}) // imag(2i) is a constant and no function call is issued 5669 c5 = len([10]float64{imag(z)}) // invalid: imag(z) is a (non-constant) function call 5670 ) 5671 var z complex128 5672 </pre> 5673 5674 <h3 id="Allocation">Allocation</h3> 5675 5676 <p> 5677 The built-in function <code>new</code> takes a type <code>T</code>, 5678 allocates storage for a <a href="#Variables">variable</a> of that type 5679 at run time, and returns a value of type <code>*T</code> 5680 <a href="#Pointer_types">pointing</a> to it. 5681 The variable is initialized as described in the section on 5682 <a href="#The_zero_value">initial values</a>. 5683 </p> 5684 5685 <pre class="grammar"> 5686 new(T) 5687 </pre> 5688 5689 <p> 5690 For instance 5691 </p> 5692 5693 <pre> 5694 type S struct { a int; b float64 } 5695 new(S) 5696 </pre> 5697 5698 <p> 5699 allocates storage for a variable of type <code>S</code>, 5700 initializes it (<code>a=0</code>, <code>b=0.0</code>), 5701 and returns a value of type <code>*S</code> containing the address 5702 of the location. 5703 </p> 5704 5705 <h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3> 5706 5707 <p> 5708 The built-in function <code>make</code> takes a type <code>T</code>, 5709 which must be a slice, map or channel type, 5710 optionally followed by a type-specific list of expressions. 5711 It returns a value of type <code>T</code> (not <code>*T</code>). 5712 The memory is initialized as described in the section on 5713 <a href="#The_zero_value">initial values</a>. 5714 </p> 5715 5716 <pre class="grammar"> 5717 Call Type T Result 5718 5719 make(T, n) slice slice of type T with length n and capacity n 5720 make(T, n, m) slice slice of type T with length n and capacity m 5721 5722 make(T) map map of type T 5723 make(T, n) map map of type T with initial space for approximately n elements 5724 5725 make(T) channel unbuffered channel of type T 5726 make(T, n) channel buffered channel of type T, buffer size n 5727 </pre> 5728 5729 5730 <p> 5731 Each of the size arguments <code>n</code> and <code>m</code> must be of integer type 5732 or an untyped <a href="#Constants">constant</a>. 5733 A constant size argument must be non-negative and <a href="#Representability">representable</a> 5734 by a value of type <code>int</code>; if it is an untyped constant it is given type <code>int</code>. 5735 If both <code>n</code> and <code>m</code> are provided and are constant, then 5736 <code>n</code> must be no larger than <code>m</code>. 5737 If <code>n</code> is negative or larger than <code>m</code> at run time, 5738 a <a href="#Run_time_panics">run-time panic</a> occurs. 5739 </p> 5740 5741 <pre> 5742 s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100 5743 s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000 5744 s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type int 5745 s := make([]int, 10, 0) // illegal: len(s) > cap(s) 5746 c := make(chan int, 10) // channel with a buffer size of 10 5747 m := make(map[string]int, 100) // map with initial space for approximately 100 elements 5748 </pre> 5749 5750 <p> 5751 Calling <code>make</code> with a map type and size hint <code>n</code> will 5752 create a map with initial space to hold <code>n</code> map elements. 5753 The precise behavior is implementation-dependent. 5754 </p> 5755 5756 5757 <h3 id="Appending_and_copying_slices">Appending to and copying slices</h3> 5758 5759 <p> 5760 The built-in functions <code>append</code> and <code>copy</code> assist in 5761 common slice operations. 5762 For both functions, the result is independent of whether the memory referenced 5763 by the arguments overlaps. 5764 </p> 5765 5766 <p> 5767 The <a href="#Function_types">variadic</a> function <code>append</code> 5768 appends zero or more values <code>x</code> 5769 to <code>s</code> of type <code>S</code>, which must be a slice type, and 5770 returns the resulting slice, also of type <code>S</code>. 5771 The values <code>x</code> are passed to a parameter of type <code>...T</code> 5772 where <code>T</code> is the <a href="#Slice_types">element type</a> of 5773 <code>S</code> and the respective 5774 <a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply. 5775 As a special case, <code>append</code> also accepts a first argument 5776 assignable to type <code>[]byte</code> with a second argument of 5777 string type followed by <code>...</code>. This form appends the 5778 bytes of the string. 5779 </p> 5780 5781 <pre class="grammar"> 5782 append(s S, x ...T) S // T is the element type of S 5783 </pre> 5784 5785 <p> 5786 If the capacity of <code>s</code> is not large enough to fit the additional 5787 values, <code>append</code> allocates a new, sufficiently large underlying 5788 array that fits both the existing slice elements and the additional values. 5789 Otherwise, <code>append</code> re-uses the underlying array. 5790 </p> 5791 5792 <pre> 5793 s0 := []int{0, 0} 5794 s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2} 5795 s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7} 5796 s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0} 5797 s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0} 5798 5799 var t []interface{} 5800 t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"} 5801 5802 var b []byte 5803 b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' } 5804 </pre> 5805 5806 <p> 5807 The function <code>copy</code> copies slice elements from 5808 a source <code>src</code> to a destination <code>dst</code> and returns the 5809 number of elements copied. 5810 Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be 5811 <a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>. 5812 The number of elements copied is the minimum of 5813 <code>len(src)</code> and <code>len(dst)</code>. 5814 As a special case, <code>copy</code> also accepts a destination argument assignable 5815 to type <code>[]byte</code> with a source argument of a string type. 5816 This form copies the bytes from the string into the byte slice. 5817 </p> 5818 5819 <pre class="grammar"> 5820 copy(dst, src []T) int 5821 copy(dst []byte, src string) int 5822 </pre> 5823 5824 <p> 5825 Examples: 5826 </p> 5827 5828 <pre> 5829 var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7} 5830 var s = make([]int, 6) 5831 var b = make([]byte, 5) 5832 n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5} 5833 n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5} 5834 n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello") 5835 </pre> 5836 5837 5838 <h3 id="Deletion_of_map_elements">Deletion of map elements</h3> 5839 5840 <p> 5841 The built-in function <code>delete</code> removes the element with key 5842 <code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The 5843 type of <code>k</code> must be <a href="#Assignability">assignable</a> 5844 to the key type of <code>m</code>. 5845 </p> 5846 5847 <pre class="grammar"> 5848 delete(m, k) // remove element m[k] from map m 5849 </pre> 5850 5851 <p> 5852 If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code> 5853 does not exist, <code>delete</code> is a no-op. 5854 </p> 5855 5856 5857 <h3 id="Complex_numbers">Manipulating complex numbers</h3> 5858 5859 <p> 5860 Three functions assemble and disassemble complex numbers. 5861 The built-in function <code>complex</code> constructs a complex 5862 value from a floating-point real and imaginary part, while 5863 <code>real</code> and <code>imag</code> 5864 extract the real and imaginary parts of a complex value. 5865 </p> 5866 5867 <pre class="grammar"> 5868 complex(realPart, imaginaryPart floatT) complexT 5869 real(complexT) floatT 5870 imag(complexT) floatT 5871 </pre> 5872 5873 <p> 5874 The type of the arguments and return value correspond. 5875 For <code>complex</code>, the two arguments must be of the same 5876 floating-point type and the return type is the complex type 5877 with the corresponding floating-point constituents: 5878 <code>complex64</code> for <code>float32</code> arguments, and 5879 <code>complex128</code> for <code>float64</code> arguments. 5880 If one of the arguments evaluates to an untyped constant, it is first 5881 <a href="#Conversions">converted</a> to the type of the other argument. 5882 If both arguments evaluate to untyped constants, they must be non-complex 5883 numbers or their imaginary parts must be zero, and the return value of 5884 the function is an untyped complex constant. 5885 </p> 5886 5887 <p> 5888 For <code>real</code> and <code>imag</code>, the argument must be 5889 of complex type, and the return type is the corresponding floating-point 5890 type: <code>float32</code> for a <code>complex64</code> argument, and 5891 <code>float64</code> for a <code>complex128</code> argument. 5892 If the argument evaluates to an untyped constant, it must be a number, 5893 and the return value of the function is an untyped floating-point constant. 5894 </p> 5895 5896 <p> 5897 The <code>real</code> and <code>imag</code> functions together form the inverse of 5898 <code>complex</code>, so for a value <code>z</code> of a complex type <code>Z</code>, 5899 <code>z == Z(complex(real(z), imag(z)))</code>. 5900 </p> 5901 5902 <p> 5903 If the operands of these functions are all constants, the return 5904 value is a constant. 5905 </p> 5906 5907 <pre> 5908 var a = complex(2, -2) // complex128 5909 const b = complex(1.0, -1.4) // untyped complex constant 1 - 1.4i 5910 x := float32(math.Cos(math.Pi/2)) // float32 5911 var c64 = complex(5, -x) // complex64 5912 var s uint = complex(1, 0) // untyped complex constant 1 + 0i can be converted to uint 5913 _ = complex(1, 2<<s) // illegal: 2 assumes floating-point type, cannot shift 5914 var rl = real(c64) // float32 5915 var im = imag(a) // float64 5916 const c = imag(b) // untyped constant -1.4 5917 _ = imag(3 << s) // illegal: 3 assumes complex type, cannot shift 5918 </pre> 5919 5920 <h3 id="Handling_panics">Handling panics</h3> 5921 5922 <p> Two built-in functions, <code>panic</code> and <code>recover</code>, 5923 assist in reporting and handling <a href="#Run_time_panics">run-time panics</a> 5924 and program-defined error conditions. 5925 </p> 5926 5927 <pre class="grammar"> 5928 func panic(interface{}) 5929 func recover() interface{} 5930 </pre> 5931 5932 <p> 5933 While executing a function <code>F</code>, 5934 an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a> 5935 terminates the execution of <code>F</code>. 5936 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code> 5937 are then executed as usual. 5938 Next, any deferred functions run by <code>F's</code> caller are run, 5939 and so on up to any deferred by the top-level function in the executing goroutine. 5940 At that point, the program is terminated and the error 5941 condition is reported, including the value of the argument to <code>panic</code>. 5942 This termination sequence is called <i>panicking</i>. 5943 </p> 5944 5945 <pre> 5946 panic(42) 5947 panic("unreachable") 5948 panic(Error("cannot parse")) 5949 </pre> 5950 5951 <p> 5952 The <code>recover</code> function allows a program to manage behavior 5953 of a panicking goroutine. 5954 Suppose a function <code>G</code> defers a function <code>D</code> that calls 5955 <code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code> 5956 is executing. 5957 When the running of deferred functions reaches <code>D</code>, 5958 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>. 5959 If <code>D</code> returns normally, without starting a new 5960 <code>panic</code>, the panicking sequence stops. In that case, 5961 the state of functions called between <code>G</code> and the call to <code>panic</code> 5962 is discarded, and normal execution resumes. 5963 Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s 5964 execution terminates by returning to its caller. 5965 </p> 5966 5967 <p> 5968 The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds: 5969 </p> 5970 <ul> 5971 <li> 5972 <code>panic</code>'s argument was <code>nil</code>; 5973 </li> 5974 <li> 5975 the goroutine is not panicking; 5976 </li> 5977 <li> 5978 <code>recover</code> was not called directly by a deferred function. 5979 </li> 5980 </ul> 5981 5982 <p> 5983 The <code>protect</code> function in the example below invokes 5984 the function argument <code>g</code> and protects callers from 5985 run-time panics raised by <code>g</code>. 5986 </p> 5987 5988 <pre> 5989 func protect(g func()) { 5990 defer func() { 5991 log.Println("done") // Println executes normally even if there is a panic 5992 if x := recover(); x != nil { 5993 log.Printf("run time panic: %v", x) 5994 } 5995 }() 5996 log.Println("start") 5997 g() 5998 } 5999 </pre> 6000 6001 6002 <h3 id="Bootstrapping">Bootstrapping</h3> 6003 6004 <p> 6005 Current implementations provide several built-in functions useful during 6006 bootstrapping. These functions are documented for completeness but are not 6007 guaranteed to stay in the language. They do not return a result. 6008 </p> 6009 6010 <pre class="grammar"> 6011 Function Behavior 6012 6013 print prints all arguments; formatting of arguments is implementation-specific 6014 println like print but prints spaces between arguments and a newline at the end 6015 </pre> 6016 6017 <p> 6018 Implementation restriction: <code>print</code> and <code>println</code> need not 6019 accept arbitrary argument types, but printing of boolean, numeric, and string 6020 <a href="#Types">types</a> must be supported. 6021 </p> 6022 6023 <h2 id="Packages">Packages</h2> 6024 6025 <p> 6026 Go programs are constructed by linking together <i>packages</i>. 6027 A package in turn is constructed from one or more source files 6028 that together declare constants, types, variables and functions 6029 belonging to the package and which are accessible in all files 6030 of the same package. Those elements may be 6031 <a href="#Exported_identifiers">exported</a> and used in another package. 6032 </p> 6033 6034 <h3 id="Source_file_organization">Source file organization</h3> 6035 6036 <p> 6037 Each source file consists of a package clause defining the package 6038 to which it belongs, followed by a possibly empty set of import 6039 declarations that declare packages whose contents it wishes to use, 6040 followed by a possibly empty set of declarations of functions, 6041 types, variables, and constants. 6042 </p> 6043 6044 <pre class="ebnf"> 6045 SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } . 6046 </pre> 6047 6048 <h3 id="Package_clause">Package clause</h3> 6049 6050 <p> 6051 A package clause begins each source file and defines the package 6052 to which the file belongs. 6053 </p> 6054 6055 <pre class="ebnf"> 6056 PackageClause = "package" PackageName . 6057 PackageName = identifier . 6058 </pre> 6059 6060 <p> 6061 The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>. 6062 </p> 6063 6064 <pre> 6065 package math 6066 </pre> 6067 6068 <p> 6069 A set of files sharing the same PackageName form the implementation of a package. 6070 An implementation may require that all source files for a package inhabit the same directory. 6071 </p> 6072 6073 <h3 id="Import_declarations">Import declarations</h3> 6074 6075 <p> 6076 An import declaration states that the source file containing the declaration 6077 depends on functionality of the <i>imported</i> package 6078 (<a href="#Program_initialization_and_execution">§Program initialization and execution</a>) 6079 and enables access to <a href="#Exported_identifiers">exported</a> identifiers 6080 of that package. 6081 The import names an identifier (PackageName) to be used for access and an ImportPath 6082 that specifies the package to be imported. 6083 </p> 6084 6085 <pre class="ebnf"> 6086 ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) . 6087 ImportSpec = [ "." | PackageName ] ImportPath . 6088 ImportPath = string_lit . 6089 </pre> 6090 6091 <p> 6092 The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a> 6093 to access exported identifiers of the package within the importing source file. 6094 It is declared in the <a href="#Blocks">file block</a>. 6095 If the PackageName is omitted, it defaults to the identifier specified in the 6096 <a href="#Package_clause">package clause</a> of the imported package. 6097 If an explicit period (<code>.</code>) appears instead of a name, all the 6098 package's exported identifiers declared in that package's 6099 <a href="#Blocks">package block</a> will be declared in the importing source 6100 file's file block and must be accessed without a qualifier. 6101 </p> 6102 6103 <p> 6104 The interpretation of the ImportPath is implementation-dependent but 6105 it is typically a substring of the full file name of the compiled 6106 package and may be relative to a repository of installed packages. 6107 </p> 6108 6109 <p> 6110 Implementation restriction: A compiler may restrict ImportPaths to 6111 non-empty strings using only characters belonging to 6112 <a href="http://www.unicode.org/versions/Unicode6.3.0/">Unicode's</a> 6113 L, M, N, P, and S general categories (the Graphic characters without 6114 spaces) and may also exclude the characters 6115 <code>!"#$%&'()*,:;<=>?[\]^`{|}</code> 6116 and the Unicode replacement character U+FFFD. 6117 </p> 6118 6119 <p> 6120 Assume we have compiled a package containing the package clause 6121 <code>package math</code>, which exports function <code>Sin</code>, and 6122 installed the compiled package in the file identified by 6123 <code>"lib/math"</code>. 6124 This table illustrates how <code>Sin</code> is accessed in files 6125 that import the package after the 6126 various types of import declaration. 6127 </p> 6128 6129 <pre class="grammar"> 6130 Import declaration Local name of Sin 6131 6132 import "lib/math" math.Sin 6133 import m "lib/math" m.Sin 6134 import . "lib/math" Sin 6135 </pre> 6136 6137 <p> 6138 An import declaration declares a dependency relation between 6139 the importing and imported package. 6140 It is illegal for a package to import itself, directly or indirectly, 6141 or to directly import a package without 6142 referring to any of its exported identifiers. To import a package solely for 6143 its side-effects (initialization), use the <a href="#Blank_identifier">blank</a> 6144 identifier as explicit package name: 6145 </p> 6146 6147 <pre> 6148 import _ "lib/math" 6149 </pre> 6150 6151 6152 <h3 id="An_example_package">An example package</h3> 6153 6154 <p> 6155 Here is a complete Go package that implements a concurrent prime sieve. 6156 </p> 6157 6158 <pre> 6159 package main 6160 6161 import "fmt" 6162 6163 // Send the sequence 2, 3, 4, … to channel 'ch'. 6164 func generate(ch chan<- int) { 6165 for i := 2; ; i++ { 6166 ch <- i // Send 'i' to channel 'ch'. 6167 } 6168 } 6169 6170 // Copy the values from channel 'src' to channel 'dst', 6171 // removing those divisible by 'prime'. 6172 func filter(src <-chan int, dst chan<- int, prime int) { 6173 for i := range src { // Loop over values received from 'src'. 6174 if i%prime != 0 { 6175 dst <- i // Send 'i' to channel 'dst'. 6176 } 6177 } 6178 } 6179 6180 // The prime sieve: Daisy-chain filter processes together. 6181 func sieve() { 6182 ch := make(chan int) // Create a new channel. 6183 go generate(ch) // Start generate() as a subprocess. 6184 for { 6185 prime := <-ch 6186 fmt.Print(prime, "\n") 6187 ch1 := make(chan int) 6188 go filter(ch, ch1, prime) 6189 ch = ch1 6190 } 6191 } 6192 6193 func main() { 6194 sieve() 6195 } 6196 </pre> 6197 6198 <h2 id="Program_initialization_and_execution">Program initialization and execution</h2> 6199 6200 <h3 id="The_zero_value">The zero value</h3> 6201 <p> 6202 When storage is allocated for a <a href="#Variables">variable</a>, 6203 either through a declaration or a call of <code>new</code>, or when 6204 a new value is created, either through a composite literal or a call 6205 of <code>make</code>, 6206 and no explicit initialization is provided, the variable or value is 6207 given a default value. Each element of such a variable or value is 6208 set to the <i>zero value</i> for its type: <code>false</code> for booleans, 6209 <code>0</code> for numeric types, <code>""</code> 6210 for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps. 6211 This initialization is done recursively, so for instance each element of an 6212 array of structs will have its fields zeroed if no value is specified. 6213 </p> 6214 <p> 6215 These two simple declarations are equivalent: 6216 </p> 6217 6218 <pre> 6219 var i int 6220 var i int = 0 6221 </pre> 6222 6223 <p> 6224 After 6225 </p> 6226 6227 <pre> 6228 type T struct { i int; f float64; next *T } 6229 t := new(T) 6230 </pre> 6231 6232 <p> 6233 the following holds: 6234 </p> 6235 6236 <pre> 6237 t.i == 0 6238 t.f == 0.0 6239 t.next == nil 6240 </pre> 6241 6242 <p> 6243 The same would also be true after 6244 </p> 6245 6246 <pre> 6247 var t T 6248 </pre> 6249 6250 <h3 id="Package_initialization">Package initialization</h3> 6251 6252 <p> 6253 Within a package, package-level variables are initialized in 6254 <i>declaration order</i> but after any of the variables 6255 they <i>depend</i> on. 6256 </p> 6257 6258 <p> 6259 More precisely, a package-level variable is considered <i>ready for 6260 initialization</i> if it is not yet initialized and either has 6261 no <a href="#Variable_declarations">initialization expression</a> or 6262 its initialization expression has no dependencies on uninitialized variables. 6263 Initialization proceeds by repeatedly initializing the next package-level 6264 variable that is earliest in declaration order and ready for initialization, 6265 until there are no variables ready for initialization. 6266 </p> 6267 6268 <p> 6269 If any variables are still uninitialized when this 6270 process ends, those variables are part of one or more initialization cycles, 6271 and the program is not valid. 6272 </p> 6273 6274 <p> 6275 The declaration order of variables declared in multiple files is determined 6276 by the order in which the files are presented to the compiler: Variables 6277 declared in the first file are declared before any of the variables declared 6278 in the second file, and so on. 6279 </p> 6280 6281 <p> 6282 Dependency analysis does not rely on the actual values of the 6283 variables, only on lexical <i>references</i> to them in the source, 6284 analyzed transitively. For instance, if a variable <code>x</code>'s 6285 initialization expression refers to a function whose body refers to 6286 variable <code>y</code> then <code>x</code> depends on <code>y</code>. 6287 Specifically: 6288 </p> 6289 6290 <ul> 6291 <li> 6292 A reference to a variable or function is an identifier denoting that 6293 variable or function. 6294 </li> 6295 6296 <li> 6297 A reference to a method <code>m</code> is a 6298 <a href="#Method_values">method value</a> or 6299 <a href="#Method_expressions">method expression</a> of the form 6300 <code>t.m</code>, where the (static) type of <code>t</code> is 6301 not an interface type, and the method <code>m</code> is in the 6302 <a href="#Method_sets">method set</a> of <code>t</code>. 6303 It is immaterial whether the resulting function value 6304 <code>t.m</code> is invoked. 6305 </li> 6306 6307 <li> 6308 A variable, function, or method <code>x</code> depends on a variable 6309 <code>y</code> if <code>x</code>'s initialization expression or body 6310 (for functions and methods) contains a reference to <code>y</code> 6311 or to a function or method that depends on <code>y</code>. 6312 </li> 6313 </ul> 6314 6315 <p> 6316 Dependency analysis is performed per package; only references referring 6317 to variables, functions, and methods declared in the current package 6318 are considered. 6319 </p> 6320 6321 <p> 6322 For example, given the declarations 6323 </p> 6324 6325 <pre> 6326 var ( 6327 a = c + b 6328 b = f() 6329 c = f() 6330 d = 3 6331 ) 6332 6333 func f() int { 6334 d++ 6335 return d 6336 } 6337 </pre> 6338 6339 <p> 6340 the initialization order is <code>d</code>, <code>b</code>, <code>c</code>, <code>a</code>. 6341 </p> 6342 6343 <p> 6344 Variables may also be initialized using functions named <code>init</code> 6345 declared in the package block, with no arguments and no result parameters. 6346 </p> 6347 6348 <pre> 6349 func init() { … } 6350 </pre> 6351 6352 <p> 6353 Multiple such functions may be defined per package, even within a single 6354 source file. In the package block, the <code>init</code> identifier can 6355 be used only to declare <code>init</code> functions, yet the identifier 6356 itself is not <a href="#Declarations_and_scope">declared</a>. Thus 6357 <code>init</code> functions cannot be referred to from anywhere 6358 in a program. 6359 </p> 6360 6361 <p> 6362 A package with no imports is initialized by assigning initial values 6363 to all its package-level variables followed by calling all <code>init</code> 6364 functions in the order they appear in the source, possibly in multiple files, 6365 as presented to the compiler. 6366 If a package has imports, the imported packages are initialized 6367 before initializing the package itself. If multiple packages import 6368 a package, the imported package will be initialized only once. 6369 The importing of packages, by construction, guarantees that there 6370 can be no cyclic initialization dependencies. 6371 </p> 6372 6373 <p> 6374 Package initialization—variable initialization and the invocation of 6375 <code>init</code> functions—happens in a single goroutine, 6376 sequentially, one package at a time. 6377 An <code>init</code> function may launch other goroutines, which can run 6378 concurrently with the initialization code. However, initialization 6379 always sequences 6380 the <code>init</code> functions: it will not invoke the next one 6381 until the previous one has returned. 6382 </p> 6383 6384 <p> 6385 To ensure reproducible initialization behavior, build systems are encouraged 6386 to present multiple files belonging to the same package in lexical file name 6387 order to a compiler. 6388 </p> 6389 6390 6391 <h3 id="Program_execution">Program execution</h3> 6392 <p> 6393 A complete program is created by linking a single, unimported package 6394 called the <i>main package</i> with all the packages it imports, transitively. 6395 The main package must 6396 have package name <code>main</code> and 6397 declare a function <code>main</code> that takes no 6398 arguments and returns no value. 6399 </p> 6400 6401 <pre> 6402 func main() { … } 6403 </pre> 6404 6405 <p> 6406 Program execution begins by initializing the main package and then 6407 invoking the function <code>main</code>. 6408 When that function invocation returns, the program exits. 6409 It does not wait for other (non-<code>main</code>) goroutines to complete. 6410 </p> 6411 6412 <h2 id="Errors">Errors</h2> 6413 6414 <p> 6415 The predeclared type <code>error</code> is defined as 6416 </p> 6417 6418 <pre> 6419 type error interface { 6420 Error() string 6421 } 6422 </pre> 6423 6424 <p> 6425 It is the conventional interface for representing an error condition, 6426 with the nil value representing no error. 6427 For instance, a function to read data from a file might be defined: 6428 </p> 6429 6430 <pre> 6431 func Read(f *File, b []byte) (n int, err error) 6432 </pre> 6433 6434 <h2 id="Run_time_panics">Run-time panics</h2> 6435 6436 <p> 6437 Execution errors such as attempting to index an array out 6438 of bounds trigger a <i>run-time panic</i> equivalent to a call of 6439 the built-in function <a href="#Handling_panics"><code>panic</code></a> 6440 with a value of the implementation-defined interface type <code>runtime.Error</code>. 6441 That type satisfies the predeclared interface type 6442 <a href="#Errors"><code>error</code></a>. 6443 The exact error values that 6444 represent distinct run-time error conditions are unspecified. 6445 </p> 6446 6447 <pre> 6448 package runtime 6449 6450 type Error interface { 6451 error 6452 // and perhaps other methods 6453 } 6454 </pre> 6455 6456 <h2 id="System_considerations">System considerations</h2> 6457 6458 <h3 id="Package_unsafe">Package <code>unsafe</code></h3> 6459 6460 <p> 6461 The built-in package <code>unsafe</code>, known to the compiler 6462 and accessible through the <a href="#Import_declarations">import path</a> <code>"unsafe"</code>, 6463 provides facilities for low-level programming including operations 6464 that violate the type system. A package using <code>unsafe</code> 6465 must be vetted manually for type safety and may not be portable. 6466 The package provides the following interface: 6467 </p> 6468 6469 <pre class="grammar"> 6470 package unsafe 6471 6472 type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type 6473 type Pointer *ArbitraryType 6474 6475 func Alignof(variable ArbitraryType) uintptr 6476 func Offsetof(selector ArbitraryType) uintptr 6477 func Sizeof(variable ArbitraryType) uintptr 6478 </pre> 6479 6480 <p> 6481 A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code> 6482 value may not be <a href="#Address_operators">dereferenced</a>. 6483 Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to 6484 a type of underlying type <code>Pointer</code> and vice versa. 6485 The effect of converting between <code>Pointer</code> and <code>uintptr</code> is implementation-defined. 6486 </p> 6487 6488 <pre> 6489 var f float64 6490 bits = *(*uint64)(unsafe.Pointer(&f)) 6491 6492 type ptr unsafe.Pointer 6493 bits = *(*uint64)(ptr(&f)) 6494 6495 var p ptr = nil 6496 </pre> 6497 6498 <p> 6499 The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code> 6500 of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code> 6501 as if <code>v</code> was declared via <code>var v = x</code>. 6502 </p> 6503 <p> 6504 The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a> 6505 <code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code> 6506 or <code>*s</code>, and returns the field offset in bytes relative to the struct's address. 6507 If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable 6508 without pointer indirections through fields of the struct. 6509 For a struct <code>s</code> with field <code>f</code>: 6510 </p> 6511 6512 <pre> 6513 uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&s.f)) 6514 </pre> 6515 6516 <p> 6517 Computer architectures may require memory addresses to be <i>aligned</i>; 6518 that is, for addresses of a variable to be a multiple of a factor, 6519 the variable's type's <i>alignment</i>. The function <code>Alignof</code> 6520 takes an expression denoting a variable of any type and returns the 6521 alignment of the (type of the) variable in bytes. For a variable 6522 <code>x</code>: 6523 </p> 6524 6525 <pre> 6526 uintptr(unsafe.Pointer(&x)) % unsafe.Alignof(x) == 0 6527 </pre> 6528 6529 <p> 6530 Calls to <code>Alignof</code>, <code>Offsetof</code>, and 6531 <code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>. 6532 </p> 6533 6534 <h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3> 6535 6536 <p> 6537 For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed: 6538 </p> 6539 6540 <pre class="grammar"> 6541 type size in bytes 6542 6543 byte, uint8, int8 1 6544 uint16, int16 2 6545 uint32, int32, float32 4 6546 uint64, int64, float64, complex64 8 6547 complex128 16 6548 </pre> 6549 6550 <p> 6551 The following minimal alignment properties are guaranteed: 6552 </p> 6553 <ol> 6554 <li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1. 6555 </li> 6556 6557 <li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of 6558 all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1. 6559 </li> 6560 6561 <li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as 6562 the alignment of a variable of the array's element type. 6563 </li> 6564 </ol> 6565 6566 <p> 6567 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. 6568 </p>