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