github.com/varialus/godfly@v0.0.0-20130904042352-1934f9f095ab/doc/go_spec.html (about) 1 <!--{ 2 "Title": "The Go Programming Language Specification", 3 "Subtitle": "Version of Aug 15, 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 array 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="#Slices"><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 </p> 884 885 <pre> 886 make([]T, length) 887 make([]T, length, capacity) 888 </pre> 889 890 <p> 891 A call to <code>make</code> allocates a new, hidden array to which the returned 892 slice value refers. That is, executing 893 </p> 894 895 <pre> 896 make([]T, length, capacity) 897 </pre> 898 899 <p> 900 produces the same slice as allocating an array and slicing it, so these two examples 901 result in the same slice: 902 </p> 903 904 <pre> 905 make([]int, 50, 100) 906 new([100]int)[0:50] 907 </pre> 908 909 <p> 910 Like arrays, slices are always one-dimensional but may be composed to construct 911 higher-dimensional objects. 912 With arrays of arrays, the inner arrays are, by construction, always the same length; 913 however with slices of slices (or arrays of slices), the lengths may vary dynamically. 914 Moreover, the inner slices must be allocated individually (with <code>make</code>). 915 </p> 916 917 <h3 id="Struct_types">Struct types</h3> 918 919 <p> 920 A struct is a sequence of named elements, called fields, each of which has a 921 name and a type. Field names may be specified explicitly (IdentifierList) or 922 implicitly (AnonymousField). 923 Within a struct, non-<a href="#Blank_identifier">blank</a> field names must 924 be <a href="#Uniqueness_of_identifiers">unique</a>. 925 </p> 926 927 <pre class="ebnf"> 928 StructType = "struct" "{" { FieldDecl ";" } "}" . 929 FieldDecl = (IdentifierList Type | AnonymousField) [ Tag ] . 930 AnonymousField = [ "*" ] TypeName . 931 Tag = string_lit . 932 </pre> 933 934 <pre> 935 // An empty struct. 936 struct {} 937 938 // A struct with 6 fields. 939 struct { 940 x, y int 941 u float32 942 _ float32 // padding 943 A *[]int 944 F func() 945 } 946 </pre> 947 948 <p> 949 A field declared with a type but no explicit field name is an <i>anonymous field</i>, 950 also called an <i>embedded</i> field or an embedding of the type in the struct. 951 An embedded type must be specified as 952 a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>, 953 and <code>T</code> itself may not be 954 a pointer type. The unqualified type name acts as the field name. 955 </p> 956 957 <pre> 958 // A struct with four anonymous fields of type T1, *T2, P.T3 and *P.T4 959 struct { 960 T1 // field name is T1 961 *T2 // field name is T2 962 P.T3 // field name is T3 963 *P.T4 // field name is T4 964 x, y int // field names are x and y 965 } 966 </pre> 967 968 <p> 969 The following declaration is illegal because field names must be unique 970 in a struct type: 971 </p> 972 973 <pre> 974 struct { 975 T // conflicts with anonymous field *T and *P.T 976 *T // conflicts with anonymous field T and *P.T 977 *P.T // conflicts with anonymous field T and *T 978 } 979 </pre> 980 981 <p> 982 A field or <a href="#Method_declarations">method</a> <code>f</code> of an 983 anonymous field in a struct <code>x</code> is called <i>promoted</i> if 984 <code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes 985 that field or method <code>f</code>. 986 </p> 987 988 <p> 989 Promoted fields act like ordinary fields 990 of a struct except that they cannot be used as field names in 991 <a href="#Composite_literals">composite literals</a> of the struct. 992 </p> 993 994 <p> 995 Given a struct type <code>S</code> and a type named <code>T</code>, 996 promoted methods are included in the method set of the struct as follows: 997 </p> 998 <ul> 999 <li> 1000 If <code>S</code> contains an anonymous field <code>T</code>, 1001 the <a href="#Method_sets">method sets</a> of <code>S</code> 1002 and <code>*S</code> both include promoted methods with receiver 1003 <code>T</code>. The method set of <code>*S</code> also 1004 includes promoted methods with receiver <code>*T</code>. 1005 </li> 1006 1007 <li> 1008 If <code>S</code> contains an anonymous field <code>*T</code>, 1009 the method sets of <code>S</code> and <code>*S</code> both 1010 include promoted methods with receiver <code>T</code> or 1011 <code>*T</code>. 1012 </li> 1013 </ul> 1014 1015 <p> 1016 A field declaration may be followed by an optional string literal <i>tag</i>, 1017 which becomes an attribute for all the fields in the corresponding 1018 field declaration. The tags are made 1019 visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a> 1020 and take part in <a href="Type_identity">type identity</a> for structs 1021 but are otherwise ignored. 1022 </p> 1023 1024 <pre> 1025 // A struct corresponding to the TimeStamp protocol buffer. 1026 // The tag strings define the protocol buffer field numbers. 1027 struct { 1028 microsec uint64 "field 1" 1029 serverIP6 uint64 "field 2" 1030 process string "field 3" 1031 } 1032 </pre> 1033 1034 <h3 id="Pointer_types">Pointer types</h3> 1035 1036 <p> 1037 A pointer type denotes the set of all pointers to variables of a given 1038 type, called the <i>base type</i> of the pointer. 1039 The value of an uninitialized pointer is <code>nil</code>. 1040 </p> 1041 1042 <pre class="ebnf"> 1043 PointerType = "*" BaseType . 1044 BaseType = Type . 1045 </pre> 1046 1047 <pre> 1048 *Point 1049 *[4]int 1050 </pre> 1051 1052 <h3 id="Function_types">Function types</h3> 1053 1054 <p> 1055 A function type denotes the set of all functions with the same parameter 1056 and result types. The value of an uninitialized variable of function type 1057 is <code>nil</code>. 1058 </p> 1059 1060 <pre class="ebnf"> 1061 FunctionType = "func" Signature . 1062 Signature = Parameters [ Result ] . 1063 Result = Parameters | Type . 1064 Parameters = "(" [ ParameterList [ "," ] ] ")" . 1065 ParameterList = ParameterDecl { "," ParameterDecl } . 1066 ParameterDecl = [ IdentifierList ] [ "..." ] Type . 1067 </pre> 1068 1069 <p> 1070 Within a list of parameters or results, the names (IdentifierList) 1071 must either all be present or all be absent. If present, each name 1072 stands for one item (parameter or result) of the specified type and 1073 all non-<a href="#Blank_identifier">blank</a> names in the signature 1074 must be <a href="#Uniqueness_of_identifiers">unique</a>. 1075 If absent, each type stands for one item of that type. 1076 Parameter and result 1077 lists are always parenthesized except that if there is exactly 1078 one unnamed result it may be written as an unparenthesized type. 1079 </p> 1080 1081 <p> 1082 The final parameter in a function signature may have 1083 a type prefixed with <code>...</code>. 1084 A function with such a parameter is called <i>variadic</i> and 1085 may be invoked with zero or more arguments for that parameter. 1086 </p> 1087 1088 <pre> 1089 func() 1090 func(x int) int 1091 func(a, _ int, z float32) bool 1092 func(a, b int, z float32) (bool) 1093 func(prefix string, values ...int) 1094 func(a, b int, z float64, opt ...interface{}) (success bool) 1095 func(int, int, float64) (float64, *[]int) 1096 func(n int) func(p *T) 1097 </pre> 1098 1099 1100 <h3 id="Interface_types">Interface types</h3> 1101 1102 <p> 1103 An interface type specifies a <a href="#Method_sets">method set</a> called its <i>interface</i>. 1104 A variable of interface type can store a value of any type with a method set 1105 that is any superset of the interface. Such a type is said to 1106 <i>implement the interface</i>. 1107 The value of an uninitialized variable of interface type is <code>nil</code>. 1108 </p> 1109 1110 <pre class="ebnf"> 1111 InterfaceType = "interface" "{" { MethodSpec ";" } "}" . 1112 MethodSpec = MethodName Signature | InterfaceTypeName . 1113 MethodName = identifier . 1114 InterfaceTypeName = TypeName . 1115 </pre> 1116 1117 <p> 1118 As with all method sets, in an interface type, each method must have a 1119 <a href="#Uniqueness_of_identifiers">unique</a> name. 1120 </p> 1121 1122 <pre> 1123 // A simple File interface 1124 interface { 1125 Read(b Buffer) bool 1126 Write(b Buffer) bool 1127 Close() 1128 } 1129 </pre> 1130 1131 <p> 1132 More than one type may implement an interface. 1133 For instance, if two types <code>S1</code> and <code>S2</code> 1134 have the method set 1135 </p> 1136 1137 <pre> 1138 func (p T) Read(b Buffer) bool { return … } 1139 func (p T) Write(b Buffer) bool { return … } 1140 func (p T) Close() { … } 1141 </pre> 1142 1143 <p> 1144 (where <code>T</code> stands for either <code>S1</code> or <code>S2</code>) 1145 then the <code>File</code> interface is implemented by both <code>S1</code> and 1146 <code>S2</code>, regardless of what other methods 1147 <code>S1</code> and <code>S2</code> may have or share. 1148 </p> 1149 1150 <p> 1151 A type implements any interface comprising any subset of its methods 1152 and may therefore implement several distinct interfaces. For 1153 instance, all types implement the <i>empty interface</i>: 1154 </p> 1155 1156 <pre> 1157 interface{} 1158 </pre> 1159 1160 <p> 1161 Similarly, consider this interface specification, 1162 which appears within a <a href="#Type_declarations">type declaration</a> 1163 to define an interface called <code>Lock</code>: 1164 </p> 1165 1166 <pre> 1167 type Lock interface { 1168 Lock() 1169 Unlock() 1170 } 1171 </pre> 1172 1173 <p> 1174 If <code>S1</code> and <code>S2</code> also implement 1175 </p> 1176 1177 <pre> 1178 func (p T) Lock() { … } 1179 func (p T) Unlock() { … } 1180 </pre> 1181 1182 <p> 1183 they implement the <code>Lock</code> interface as well 1184 as the <code>File</code> interface. 1185 </p> 1186 <p> 1187 An interface may use an interface type name <code>T</code> 1188 in place of a method specification. 1189 The effect, called embedding an interface, 1190 is equivalent to enumerating the methods of <code>T</code> explicitly 1191 in the interface. 1192 </p> 1193 1194 <pre> 1195 type ReadWrite interface { 1196 Read(b Buffer) bool 1197 Write(b Buffer) bool 1198 } 1199 1200 type File interface { 1201 ReadWrite // same as enumerating the methods in ReadWrite 1202 Lock // same as enumerating the methods in Lock 1203 Close() 1204 } 1205 </pre> 1206 1207 <p> 1208 An interface type <code>T</code> may not embed itself 1209 or any interface type that embeds <code>T</code>, recursively. 1210 </p> 1211 1212 <pre> 1213 // illegal: Bad cannot embed itself 1214 type Bad interface { 1215 Bad 1216 } 1217 1218 // illegal: Bad1 cannot embed itself using Bad2 1219 type Bad1 interface { 1220 Bad2 1221 } 1222 type Bad2 interface { 1223 Bad1 1224 } 1225 </pre> 1226 1227 <h3 id="Map_types">Map types</h3> 1228 1229 <p> 1230 A map is an unordered group of elements of one type, called the 1231 element type, indexed by a set of unique <i>keys</i> of another type, 1232 called the key type. 1233 The value of an uninitialized map is <code>nil</code>. 1234 </p> 1235 1236 <pre class="ebnf"> 1237 MapType = "map" "[" KeyType "]" ElementType . 1238 KeyType = Type . 1239 </pre> 1240 1241 <p> 1242 The <a href="#Comparison_operators">comparison operators</a> 1243 <code>==</code> and <code>!=</code> must be fully defined 1244 for operands of the key type; thus the key type must not be a function, map, or 1245 slice. 1246 If the key type is an interface type, these 1247 comparison operators must be defined for the dynamic key values; 1248 failure will cause a <a href="#Run_time_panics">run-time panic</a>. 1249 1250 </p> 1251 1252 <pre> 1253 map[string]int 1254 map[*T]struct{ x, y float64 } 1255 map[string]interface{} 1256 </pre> 1257 1258 <p> 1259 The number of map elements is called its length. 1260 For a map <code>m</code>, it can be discovered using the 1261 built-in function <a href="#Length_and_capacity"><code>len</code></a> 1262 and may change during execution. Elements may be added during execution 1263 using <a href="#Assignments">assignments</a> and retrieved with 1264 <a href="#Index_expressions">index expressions</a>; they may be removed with the 1265 <a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function. 1266 </p> 1267 <p> 1268 A new, empty map value is made using the built-in 1269 function <a href="#Making_slices_maps_and_channels"><code>make</code></a>, 1270 which takes the map type and an optional capacity hint as arguments: 1271 </p> 1272 1273 <pre> 1274 make(map[string]int) 1275 make(map[string]int, 100) 1276 </pre> 1277 1278 <p> 1279 The initial capacity does not bound its size: 1280 maps grow to accommodate the number of items 1281 stored in them, with the exception of <code>nil</code> maps. 1282 A <code>nil</code> map is equivalent to an empty map except that no elements 1283 may be added. 1284 1285 <h3 id="Channel_types">Channel types</h3> 1286 1287 <p> 1288 A channel provides a mechanism for two concurrently executing functions 1289 to synchronize execution and communicate by passing a value of a 1290 specified element type. 1291 The value of an uninitialized channel is <code>nil</code>. 1292 </p> 1293 1294 <pre class="ebnf"> 1295 ChannelType = ( "chan" [ "<-" ] | "<-" "chan" ) ElementType . 1296 </pre> 1297 1298 <p> 1299 The <code><-</code> operator specifies the channel <i>direction</i>, 1300 <i>send</i> or <i>receive</i>. If no direction is given, the channel is 1301 <i>bi-directional</i>. 1302 A channel may be constrained only to send or only to receive by 1303 <a href="#Conversions">conversion</a> or <a href="#Assignments">assignment</a>. 1304 </p> 1305 1306 <pre> 1307 chan T // can be used to send and receive values of type T 1308 chan<- float64 // can only be used to send float64s 1309 <-chan int // can only be used to receive ints 1310 </pre> 1311 1312 <p> 1313 The <code><-</code> operator associates with the leftmost <code>chan</code> 1314 possible: 1315 </p> 1316 1317 <pre> 1318 chan<- chan int // same as chan<- (chan int) 1319 chan<- <-chan int // same as chan<- (<-chan int) 1320 <-chan <-chan int // same as <-chan (<-chan int) 1321 chan (<-chan int) 1322 </pre> 1323 1324 <p> 1325 A new, initialized channel 1326 value can be made using the built-in function 1327 <a href="#Making_slices_maps_and_channels"><code>make</code></a>, 1328 which takes the channel type and an optional capacity as arguments: 1329 </p> 1330 1331 <pre> 1332 make(chan int, 100) 1333 </pre> 1334 1335 <p> 1336 The capacity, in number of elements, sets the size of the buffer in the channel. If the 1337 capacity is greater than zero, the channel is asynchronous: communication operations 1338 succeed without blocking if the buffer is not full (sends) or not empty (receives), 1339 and elements are received in the order they are sent. 1340 If the capacity is zero or absent, the communication succeeds only when both a sender and 1341 receiver are ready. 1342 A <code>nil</code> channel is never ready for communication. 1343 </p> 1344 1345 <p> 1346 A channel may be closed with the built-in function 1347 <a href="#Close"><code>close</code></a>; the 1348 multi-valued assignment form of the 1349 <a href="#Receive_operator">receive operator</a> 1350 tests whether a channel has been closed. 1351 </p> 1352 1353 <h2 id="Properties_of_types_and_values">Properties of types and values</h2> 1354 1355 <h3 id="Type_identity">Type identity</h3> 1356 1357 <p> 1358 Two types are either <i>identical</i> or <i>different</i>. 1359 </p> 1360 1361 <p> 1362 Two <a href="#Types">named types</a> are identical if their type names originate in the same 1363 <a href="#Type_declarations">TypeSpec</a>. 1364 A named and an <a href="#Types">unnamed type</a> are always different. Two unnamed types are identical 1365 if the corresponding type literals are identical, that is, if they have the same 1366 literal structure and corresponding components have identical types. In detail: 1367 </p> 1368 1369 <ul> 1370 <li>Two array types are identical if they have identical element types and 1371 the same array length.</li> 1372 1373 <li>Two slice types are identical if they have identical element types.</li> 1374 1375 <li>Two struct types are identical if they have the same sequence of fields, 1376 and if corresponding fields have the same names, and identical types, 1377 and identical tags. 1378 Two anonymous fields are considered to have the same name. Lower-case field 1379 names from different packages are always different.</li> 1380 1381 <li>Two pointer types are identical if they have identical base types.</li> 1382 1383 <li>Two function types are identical if they have the same number of parameters 1384 and result values, corresponding parameter and result types are 1385 identical, and either both functions are variadic or neither is. 1386 Parameter and result names are not required to match.</li> 1387 1388 <li>Two interface types are identical if they have the same set of methods 1389 with the same names and identical function types. Lower-case method names from 1390 different packages are always different. The order of the methods is irrelevant.</li> 1391 1392 <li>Two map types are identical if they have identical key and value types.</li> 1393 1394 <li>Two channel types are identical if they have identical value types and 1395 the same direction.</li> 1396 </ul> 1397 1398 <p> 1399 Given the declarations 1400 </p> 1401 1402 <pre> 1403 type ( 1404 T0 []string 1405 T1 []string 1406 T2 struct{ a, b int } 1407 T3 struct{ a, c int } 1408 T4 func(int, float64) *T0 1409 T5 func(x int, y float64) *[]string 1410 ) 1411 </pre> 1412 1413 <p> 1414 these types are identical: 1415 </p> 1416 1417 <pre> 1418 T0 and T0 1419 []int and []int 1420 struct{ a, b *T5 } and struct{ a, b *T5 } 1421 func(x int, y float64) *[]string and func(int, float64) (result *[]string) 1422 </pre> 1423 1424 <p> 1425 <code>T0</code> and <code>T1</code> are different because they are named types 1426 with distinct declarations; <code>func(int, float64) *T0</code> and 1427 <code>func(x int, y float64) *[]string</code> are different because <code>T0</code> 1428 is different from <code>[]string</code>. 1429 </p> 1430 1431 1432 <h3 id="Assignability">Assignability</h3> 1433 1434 <p> 1435 A value <code>x</code> is <i>assignable</i> to a variable of type <code>T</code> 1436 ("<code>x</code> is assignable to <code>T</code>") in any of these cases: 1437 </p> 1438 1439 <ul> 1440 <li> 1441 <code>x</code>'s type is identical to <code>T</code>. 1442 </li> 1443 <li> 1444 <code>x</code>'s type <code>V</code> and <code>T</code> have identical 1445 <a href="#Types">underlying types</a> and at least one of <code>V</code> 1446 or <code>T</code> is not a <a href="#Types">named type</a>. 1447 </li> 1448 <li> 1449 <code>T</code> is an interface type and 1450 <code>x</code> <a href="#Interface_types">implements</a> <code>T</code>. 1451 </li> 1452 <li> 1453 <code>x</code> is a bidirectional channel value, <code>T</code> is a channel type, 1454 <code>x</code>'s type <code>V</code> and <code>T</code> have identical element types, 1455 and at least one of <code>V</code> or <code>T</code> is not a named type. 1456 </li> 1457 <li> 1458 <code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code> 1459 is a pointer, function, slice, map, channel, or interface type. 1460 </li> 1461 <li> 1462 <code>x</code> is an untyped <a href="#Constants">constant</a> representable 1463 by a value of type <code>T</code>. 1464 </li> 1465 </ul> 1466 1467 <p> 1468 Any value may be assigned to the <a href="#Blank_identifier">blank identifier</a>. 1469 </p> 1470 1471 1472 <h2 id="Blocks">Blocks</h2> 1473 1474 <p> 1475 A <i>block</i> is a possibly empty sequence of declarations and statements 1476 within matching brace brackets. 1477 </p> 1478 1479 <pre class="ebnf"> 1480 Block = "{" StatementList "}" . 1481 StatementList = { Statement ";" } . 1482 </pre> 1483 1484 <p> 1485 In addition to explicit blocks in the source code, there are implicit blocks: 1486 </p> 1487 1488 <ol> 1489 <li>The <i>universe block</i> encompasses all Go source text.</li> 1490 1491 <li>Each <a href="#Packages">package</a> has a <i>package block</i> containing all 1492 Go source text for that package.</li> 1493 1494 <li>Each file has a <i>file block</i> containing all Go source text 1495 in that file.</li> 1496 1497 <li>Each <a href="#If_statements">"if"</a>, 1498 <a href="#For_statements">"for"</a>, and 1499 <a href="#Switch_statements">"switch"</a> 1500 statement is considered to be in its own implicit block.</li> 1501 1502 <li>Each clause in a <a href="#Switch_statements">"switch"</a> 1503 or <a href="#Select_statements">"select"</a> statement 1504 acts as an implicit block.</li> 1505 </ol> 1506 1507 <p> 1508 Blocks nest and influence <a href="#Declarations_and_scope">scoping</a>. 1509 </p> 1510 1511 1512 <h2 id="Declarations_and_scope">Declarations and scope</h2> 1513 1514 <p> 1515 A declaration binds a non-<a href="#Blank_identifier">blank</a> 1516 identifier to a constant, type, variable, function, or package. 1517 Every identifier in a program must be declared. 1518 No identifier may be declared twice in the same block, and 1519 no identifier may be declared in both the file and package block. 1520 </p> 1521 1522 <pre class="ebnf"> 1523 Declaration = ConstDecl | TypeDecl | VarDecl . 1524 TopLevelDecl = Declaration | FunctionDecl | MethodDecl . 1525 </pre> 1526 1527 <p> 1528 The <i>scope</i> of a declared identifier is the extent of source text in which 1529 the identifier denotes the specified constant, type, variable, function, or package. 1530 </p> 1531 1532 <p> 1533 Go is lexically scoped using blocks: 1534 </p> 1535 1536 <ol> 1537 <li>The scope of a predeclared identifier is the universe block.</li> 1538 1539 <li>The scope of an identifier denoting a constant, type, variable, 1540 or function (but not method) declared at top level (outside any 1541 function) is the package block.</li> 1542 1543 <li>The scope of the package name of an imported package is the file block 1544 of the file containing the import declaration.</li> 1545 1546 <li>The scope of an identifier denoting a method receiver, function parameter, 1547 or result variable is the function body.</li> 1548 1549 <li>The scope of a constant or variable identifier declared 1550 inside a function begins at the end of the ConstSpec or VarSpec 1551 (ShortVarDecl for short variable declarations) 1552 and ends at the end of the innermost containing block.</li> 1553 1554 <li>The scope of a type identifier declared inside a function 1555 begins at the identifier in the TypeSpec 1556 and ends at the end of the innermost containing block.</li> 1557 </ol> 1558 1559 <p> 1560 An identifier declared in a block may be redeclared in an inner block. 1561 While the identifier of the inner declaration is in scope, it denotes 1562 the entity declared by the inner declaration. 1563 </p> 1564 1565 <p> 1566 The <a href="#Package_clause">package clause</a> is not a declaration; the package name 1567 does not appear in any scope. Its purpose is to identify the files belonging 1568 to the same <a href="#Packages">package</a> and to specify the default package name for import 1569 declarations. 1570 </p> 1571 1572 1573 <h3 id="Label_scopes">Label scopes</h3> 1574 1575 <p> 1576 Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are 1577 used in the <a href="#Break_statements">"break"</a>, 1578 <a href="#Continue_statements">"continue"</a>, and 1579 <a href="#Goto_statements">"goto"</a> statements. 1580 It is illegal to define a label that is never used. 1581 In contrast to other identifiers, labels are not block scoped and do 1582 not conflict with identifiers that are not labels. The scope of a label 1583 is the body of the function in which it is declared and excludes 1584 the body of any nested function. 1585 </p> 1586 1587 1588 <h3 id="Blank_identifier">Blank identifier</h3> 1589 1590 <p> 1591 The <i>blank identifier</i>, represented by the underscore character <code>_</code>, may be used in a declaration like 1592 any other identifier but the declaration does not introduce a new binding. 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>) identifier 2084 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 <pre class="ebnf"> 2093 Operand = Literal | OperandName | MethodExpr | "(" Expression ")" . 2094 Literal = BasicLit | CompositeLit | FunctionLit . 2095 BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit . 2096 OperandName = identifier | QualifiedIdent. 2097 </pre> 2098 2099 <h3 id="Qualified_identifiers">Qualified identifiers</h3> 2100 2101 <p> 2102 A qualified identifier is an identifier qualified with a package name prefix. 2103 Both the package name and the identifier must not be 2104 <a href="#Blank_identifier">blank</a>. 2105 </p> 2106 2107 <pre class="ebnf"> 2108 QualifiedIdent = PackageName "." identifier . 2109 </pre> 2110 2111 <p> 2112 A qualified identifier accesses an identifier in a different package, which 2113 must be <a href="#Import_declarations">imported</a>. 2114 The identifier must be <a href="#Exported_identifiers">exported</a> and 2115 declared in the <a href="#Blocks">package block</a> of that package. 2116 </p> 2117 2118 <pre> 2119 math.Sin // denotes the Sin function in package math 2120 </pre> 2121 2122 <h3 id="Composite_literals">Composite literals</h3> 2123 2124 <p> 2125 Composite literals construct values for structs, arrays, slices, and maps 2126 and create a new value each time they are evaluated. 2127 They consist of the type of the value 2128 followed by a brace-bound list of composite elements. An element may be 2129 a single expression or a key-value pair. 2130 </p> 2131 2132 <pre class="ebnf"> 2133 CompositeLit = LiteralType LiteralValue . 2134 LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | 2135 SliceType | MapType | TypeName . 2136 LiteralValue = "{" [ ElementList [ "," ] ] "}" . 2137 ElementList = Element { "," Element } . 2138 Element = [ Key ":" ] Value . 2139 Key = FieldName | ElementIndex . 2140 FieldName = identifier . 2141 ElementIndex = Expression . 2142 Value = Expression | LiteralValue . 2143 </pre> 2144 2145 <p> 2146 The LiteralType must be a struct, array, slice, or map type 2147 (the grammar enforces this constraint except when the type is given 2148 as a TypeName). 2149 The types of the expressions must be <a href="#Assignability">assignable</a> 2150 to the respective field, element, and key types of the LiteralType; 2151 there is no additional conversion. 2152 The key is interpreted as a field name for struct literals, 2153 an index for array and slice literals, and a key for map literals. 2154 For map literals, all elements must have a key. It is an error 2155 to specify multiple elements with the same field name or 2156 constant key value. 2157 </p> 2158 2159 <p> 2160 For struct literals the following rules apply: 2161 </p> 2162 <ul> 2163 <li>A key must be a field name declared in the LiteralType. 2164 </li> 2165 <li>An element list that does not contain any keys must 2166 list an element for each struct field in the 2167 order in which the fields are declared. 2168 </li> 2169 <li>If any element has a key, every element must have a key. 2170 </li> 2171 <li>An element list that contains keys does not need to 2172 have an element for each struct field. Omitted fields 2173 get the zero value for that field. 2174 </li> 2175 <li>A literal may omit the element list; such a literal evaluates 2176 to the zero value for its type. 2177 </li> 2178 <li>It is an error to specify an element for a non-exported 2179 field of a struct belonging to a different package. 2180 </li> 2181 </ul> 2182 2183 <p> 2184 Given the declarations 2185 </p> 2186 <pre> 2187 type Point3D struct { x, y, z float64 } 2188 type Line struct { p, q Point3D } 2189 </pre> 2190 2191 <p> 2192 one may write 2193 </p> 2194 2195 <pre> 2196 origin := Point3D{} // zero value for Point3D 2197 line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x 2198 </pre> 2199 2200 <p> 2201 For array and slice literals the following rules apply: 2202 </p> 2203 <ul> 2204 <li>Each element has an associated integer index marking 2205 its position in the array. 2206 </li> 2207 <li>An element with a key uses the key as its index; the 2208 key must be a constant integer expression. 2209 </li> 2210 <li>An element without a key uses the previous element's index plus one. 2211 If the first element has no key, its index is zero. 2212 </li> 2213 </ul> 2214 2215 <p> 2216 <a href="#Address_operators">Taking the address</a> of a composite literal 2217 generates a pointer to a unique instance of the literal's value. 2218 </p> 2219 <pre> 2220 var pointer *Point3D = &Point3D{y: 1000} 2221 </pre> 2222 2223 <p> 2224 The length of an array literal is the length specified in the LiteralType. 2225 If fewer elements than the length are provided in the literal, the missing 2226 elements are set to the zero value for the array element type. 2227 It is an error to provide elements with index values outside the index range 2228 of the array. The notation <code>...</code> specifies an array length equal 2229 to the maximum element index plus one. 2230 </p> 2231 2232 <pre> 2233 buffer := [10]string{} // len(buffer) == 10 2234 intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6 2235 days := [...]string{"Sat", "Sun"} // len(days) == 2 2236 </pre> 2237 2238 <p> 2239 A slice literal describes the entire underlying array literal. 2240 Thus, the length and capacity of a slice literal are the maximum 2241 element index plus one. A slice literal has the form 2242 </p> 2243 2244 <pre> 2245 []T{x1, x2, … xn} 2246 </pre> 2247 2248 <p> 2249 and is shorthand for a slice operation applied to an array: 2250 </p> 2251 2252 <pre> 2253 tmp := [n]T{x1, x2, … xn} 2254 tmp[0 : n] 2255 </pre> 2256 2257 <p> 2258 Within a composite literal of array, slice, or map type <code>T</code>, 2259 elements that are themselves composite literals may elide the respective 2260 literal type if it is identical to the element type of <code>T</code>. 2261 Similarly, elements that are addresses of composite literals may elide 2262 the <code>&T</code> when the element type is <code>*T</code>. 2263 </p> 2264 2265 2266 2267 <pre> 2268 [...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}} 2269 [][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}} 2270 2271 [...]*Point{{1.5, -3.5}, {0, 0}} // same as [...]*Point{&Point{1.5, -3.5}, &Point{0, 0}} 2272 </pre> 2273 2274 <p> 2275 A parsing ambiguity arises when a composite literal using the 2276 TypeName form of the LiteralType appears between the 2277 <a href="#Keywords">keyword</a> and the opening brace of the block of an 2278 "if", "for", or "switch" statement, because the braces surrounding 2279 the expressions in the literal are confused with those introducing 2280 the block of statements. To resolve the ambiguity in this rare case, 2281 the composite literal must appear within 2282 parentheses. 2283 </p> 2284 2285 <pre> 2286 if x == (T{a,b,c}[i]) { … } 2287 if (x == T{a,b,c}[i]) { … } 2288 </pre> 2289 2290 <p> 2291 Examples of valid array, slice, and map literals: 2292 </p> 2293 2294 <pre> 2295 // list of prime numbers 2296 primes := []int{2, 3, 5, 7, 9, 2147483647} 2297 2298 // vowels[ch] is true if ch is a vowel 2299 vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true} 2300 2301 // the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1} 2302 filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1} 2303 2304 // frequencies in Hz for equal-tempered scale (A4 = 440Hz) 2305 noteFrequency := map[string]float32{ 2306 "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83, 2307 "G0": 24.50, "A0": 27.50, "B0": 30.87, 2308 } 2309 </pre> 2310 2311 2312 <h3 id="Function_literals">Function literals</h3> 2313 2314 <p> 2315 A function literal represents an anonymous <a href="#Function_declarations">function</a>. 2316 </p> 2317 2318 <pre class="ebnf"> 2319 FunctionLit = "func" Function . 2320 </pre> 2321 2322 <pre> 2323 func(a, b int, z float64) bool { return a*b < int(z) } 2324 </pre> 2325 2326 <p> 2327 A function literal can be assigned to a variable or invoked directly. 2328 </p> 2329 2330 <pre> 2331 f := func(x, y int) int { return x + y } 2332 func(ch chan int) { ch <- ACK }(replyChan) 2333 </pre> 2334 2335 <p> 2336 Function literals are <i>closures</i>: they may refer to variables 2337 defined in a surrounding function. Those variables are then shared between 2338 the surrounding function and the function literal, and they survive as long 2339 as they are accessible. 2340 </p> 2341 2342 2343 <h3 id="Primary_expressions">Primary expressions</h3> 2344 2345 <p> 2346 Primary expressions are the operands for unary and binary expressions. 2347 </p> 2348 2349 <pre class="ebnf"> 2350 PrimaryExpr = 2351 Operand | 2352 Conversion | 2353 BuiltinCall | 2354 PrimaryExpr Selector | 2355 PrimaryExpr Index | 2356 PrimaryExpr Slice | 2357 PrimaryExpr TypeAssertion | 2358 PrimaryExpr Call . 2359 2360 Selector = "." identifier . 2361 Index = "[" Expression "]" . 2362 Slice = "[" [ Expression ] ":" [ Expression ] "]" . 2363 TypeAssertion = "." "(" Type ")" . 2364 Call = "(" [ ArgumentList [ "," ] ] ")" . 2365 ArgumentList = ExpressionList [ "..." ] . 2366 </pre> 2367 2368 2369 <pre> 2370 x 2371 2 2372 (s + ".txt") 2373 f(3.1415, true) 2374 Point{1, 2} 2375 m["foo"] 2376 s[i : j + 1] 2377 obj.color 2378 f.p[i].x() 2379 </pre> 2380 2381 2382 <h3 id="Selectors">Selectors</h3> 2383 2384 <p> 2385 For a <a href="#Primary_expressions">primary expression</a> <code>x</code> 2386 that is not a <a href="#Package_clause">package name</a>, the 2387 <i>selector expression</i> 2388 </p> 2389 2390 <pre> 2391 x.f 2392 </pre> 2393 2394 <p> 2395 denotes the field or method <code>f</code> of the value <code>x</code> 2396 (or sometimes <code>*x</code>; see below). 2397 The identifier <code>f</code> is called the (field or method) <i>selector</i>; 2398 it must not be the <a href="#Blank_identifier">blank identifier</a>. 2399 The type of the selector expression is the type of <code>f</code>. 2400 If <code>x</code> is a package name, see the section on 2401 <a href="#Qualified_identifiers">qualified identifiers</a>. 2402 </p> 2403 2404 <p> 2405 A selector <code>f</code> may denote a field or method <code>f</code> of 2406 a type <code>T</code>, or it may refer 2407 to a field or method <code>f</code> of a nested 2408 <a href="#Struct_types">anonymous field</a> of <code>T</code>. 2409 The number of anonymous fields traversed 2410 to reach <code>f</code> is called its <i>depth</i> in <code>T</code>. 2411 The depth of a field or method <code>f</code> 2412 declared in <code>T</code> is zero. 2413 The depth of a field or method <code>f</code> declared in 2414 an anonymous field <code>A</code> in <code>T</code> is the 2415 depth of <code>f</code> in <code>A</code> plus one. 2416 </p> 2417 2418 <p> 2419 The following rules apply to selectors: 2420 </p> 2421 2422 <ol> 2423 <li> 2424 For a value <code>x</code> of type <code>T</code> or <code>*T</code> 2425 where <code>T</code> is not an interface type, 2426 <code>x.f</code> denotes the field or method at the shallowest depth 2427 in <code>T</code> where there 2428 is such an <code>f</code>. 2429 If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a> 2430 with shallowest depth, the selector expression is illegal. 2431 </li> 2432 <li> 2433 For a variable <code>x</code> of type <code>I</code> where <code>I</code> 2434 is an interface type, <code>x.f</code> denotes the actual method with name 2435 <code>f</code> of the value assigned to <code>x</code>. 2436 If there is no method with name <code>f</code> in the 2437 <a href="#Method_sets">method set</a> of <code>I</code>, the selector 2438 expression is illegal. 2439 </li> 2440 <li> 2441 In all other cases, <code>x.f</code> is illegal. 2442 </li> 2443 <li> 2444 If <code>x</code> is of pointer type and has the value 2445 <code>nil</code> and <code>x.f</code> denotes a struct field, 2446 assigning to or evaluating <code>x.f</code> 2447 causes a <a href="#Run_time_panics">run-time panic</a>. 2448 </li> 2449 <li> 2450 If <code>x</code> is of interface type and has the value 2451 <code>nil</code>, <a href="#Calls">calling</a> or 2452 <a href="#Method_values">evaluating</a> the method <code>x.f</code> 2453 causes a <a href="#Run_time_panics">run-time panic</a>. 2454 </li> 2455 </ol> 2456 2457 <p> 2458 Selectors automatically <a href="#Address_operators">dereference</a> 2459 pointers to structs. 2460 If <code>x</code> is a pointer to a struct, <code>x.y</code> 2461 is shorthand for <code>(*x).y</code>; if the field <code>y</code> 2462 is also a pointer to a struct, <code>x.y.z</code> is shorthand 2463 for <code>(*(*x).y).z</code>, and so on. 2464 If <code>x</code> contains an anonymous field of type <code>*A</code>, 2465 where <code>A</code> is also a struct type, 2466 <code>x.f</code> is shorthand for <code>(*x.A).f</code>. 2467 </p> 2468 2469 <p> 2470 For example, given the declarations: 2471 </p> 2472 2473 <pre> 2474 type T0 struct { 2475 x int 2476 } 2477 2478 func (recv *T0) M0() 2479 2480 type T1 struct { 2481 y int 2482 } 2483 2484 func (recv T1) M1() 2485 2486 type T2 struct { 2487 z int 2488 T1 2489 *T0 2490 } 2491 2492 func (recv *T2) M2() 2493 2494 var p *T2 // with p != nil and p.T0 != nil 2495 </pre> 2496 2497 <p> 2498 one may write: 2499 </p> 2500 2501 <pre> 2502 p.z // (*p).z 2503 p.y // ((*p).T1).y 2504 p.x // (*(*p).T0).x 2505 2506 p.M2() // (*p).M2() 2507 p.M1() // ((*p).T1).M1() 2508 p.M0() // ((*p).T0).M0() 2509 </pre> 2510 2511 2512 <h3 id="Index_expressions">Index expressions</h3> 2513 2514 <p> 2515 A primary expression of the form 2516 </p> 2517 2518 <pre> 2519 a[x] 2520 </pre> 2521 2522 <p> 2523 denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>. 2524 The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively. 2525 The following rules apply: 2526 </p> 2527 2528 <p> 2529 If <code>a</code> is not a map: 2530 </p> 2531 <ul> 2532 <li>the index <code>x</code> must be of integer type or untyped; 2533 it is <i>in range</i> if <code>0 <= x < len(a)</code>, 2534 otherwise it is <i>out of range</i></li> 2535 <li>a <a href="#Constants">constant</a> index must be non-negative 2536 and representable by a value of type <code>int</code> 2537 </ul> 2538 2539 <p> 2540 For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>: 2541 </p> 2542 <ul> 2543 <li>a <a href="#Constants">constant</a> index must be in range</li> 2544 <li>if <code>x</code> is out of range at run time, 2545 a <a href="#Run_time_panics">run-time panic</a> occurs</li> 2546 <li><code>a[x]</code> is the array element at index <code>x</code> and the type of 2547 <code>a[x]</code> is the element type of <code>A</code></li> 2548 </ul> 2549 2550 <p> 2551 For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type: 2552 </p> 2553 <ul> 2554 <li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li> 2555 </ul> 2556 2557 <p> 2558 For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>: 2559 </p> 2560 <ul> 2561 <li>if <code>x</code> is out of range at run time, 2562 a <a href="#Run_time_panics">run-time panic</a> occurs</li> 2563 <li><code>a[x]</code> is the slice element at index <code>x</code> and the type of 2564 <code>a[x]</code> is the element type of <code>S</code></li> 2565 </ul> 2566 2567 <p> 2568 For <code>a</code> of <a href="#String_types">string type</a>: 2569 </p> 2570 <ul> 2571 <li>a <a href="#Constants">constant</a> index must be in range 2572 if the string <code>a</code> is also constant</li> 2573 <li>if <code>x</code> is out of range at run time, 2574 a <a href="#Run_time_panics">run-time panic</a> occurs</li> 2575 <li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of 2576 <code>a[x]</code> is <code>byte</code></li> 2577 <li><code>a[x]</code> may not be assigned to</li> 2578 </ul> 2579 2580 <p> 2581 For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>: 2582 </p> 2583 <ul> 2584 <li><code>x</code>'s type must be 2585 <a href="#Assignability">assignable</a> 2586 to the key type of <code>M</code></li> 2587 <li>if the map contains an entry with key <code>x</code>, 2588 <code>a[x]</code> is the map value with key <code>x</code> 2589 and the type of <code>a[x]</code> is the value type of <code>M</code></li> 2590 <li>if the map is <code>nil</code> or does not contain such an entry, 2591 <code>a[x]</code> is the <a href="#The_zero_value">zero value</a> 2592 for the value type of <code>M</code></li> 2593 </ul> 2594 2595 <p> 2596 Otherwise <code>a[x]</code> is illegal. 2597 </p> 2598 2599 <p> 2600 An index expression on a map <code>a</code> of type <code>map[K]V</code> 2601 may be used in an assignment or initialization of the special form 2602 </p> 2603 2604 <pre> 2605 v, ok = a[x] 2606 v, ok := a[x] 2607 var v, ok = a[x] 2608 </pre> 2609 2610 <p> 2611 where the result of the index expression is a pair of values with types 2612 <code>(V, bool)</code>. In this form, the value of <code>ok</code> is 2613 <code>true</code> if the key <code>x</code> is present in the map, and 2614 <code>false</code> otherwise. The value of <code>v</code> is the value 2615 <code>a[x]</code> as in the single-result form. 2616 </p> 2617 2618 <p> 2619 Assigning to an element of a <code>nil</code> map causes a 2620 <a href="#Run_time_panics">run-time panic</a>. 2621 </p> 2622 2623 2624 <h3 id="Slices">Slices</h3> 2625 2626 <p> 2627 For a string, array, pointer to array, or slice <code>a</code>, the primary expression 2628 </p> 2629 2630 <pre> 2631 a[low : high] 2632 </pre> 2633 2634 <p> 2635 constructs a substring or slice. The <i>indices</i> <code>low</code> and 2636 <code>high</code> select which elements of operand <code>a</code> appear 2637 in the result. The result has indices starting at 0 and length equal to 2638 <code>high</code> - <code>low</code>. 2639 After slicing the array <code>a</code> 2640 </p> 2641 2642 <pre> 2643 a := [5]int{1, 2, 3, 4, 5} 2644 s := a[1:4] 2645 </pre> 2646 2647 <p> 2648 the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements 2649 </p> 2650 2651 <pre> 2652 s[0] == 2 2653 s[1] == 3 2654 s[2] == 4 2655 </pre> 2656 2657 <p> 2658 For convenience, any of the indices may be omitted. A missing <code>low</code> 2659 index defaults to zero; a missing <code>high</code> index defaults to the length of the 2660 sliced operand: 2661 </p> 2662 2663 <pre> 2664 a[2:] // same a[2 : len(a)] 2665 a[:3] // same as a[0 : 3] 2666 a[:] // same as a[0 : len(a)] 2667 </pre> 2668 2669 <p> 2670 If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for 2671 <code>(*a)[low : high]</code>. 2672 </p> 2673 2674 <p> 2675 For arrays or strings, the indices are <i>in range</i> if 2676 <code>0</code> <= <code>low</code> <= <code>high</code> <= <code>len(a)</code>, 2677 otherwise they are <i>out of range</i>. 2678 For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length. 2679 A <a href="#Constants">constant</a> index must be non-negative and representable by a value of type 2680 <code>int</code>. 2681 If both indices are constant, they must satisfy <code>low <= high</code>. 2682 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. 2683 </p> 2684 2685 <p> 2686 Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice, 2687 the result of the slice operation is a non-constant value of the same type as the operand. 2688 For untyped string operands the result is a non-constant value of type <code>string</code>. 2689 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a> 2690 and the result of the slice operation is a slice with the same element type as the array. 2691 </p> 2692 2693 <p> 2694 If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result 2695 is a <code>nil</code> slice. 2696 </p> 2697 2698 <h3 id="Type_assertions">Type assertions</h3> 2699 2700 <p> 2701 For an expression <code>x</code> of <a href="#Interface_types">interface type</a> 2702 and a type <code>T</code>, the primary expression 2703 </p> 2704 2705 <pre> 2706 x.(T) 2707 </pre> 2708 2709 <p> 2710 asserts that <code>x</code> is not <code>nil</code> 2711 and that the value stored in <code>x</code> is of type <code>T</code>. 2712 The notation <code>x.(T)</code> is called a <i>type assertion</i>. 2713 </p> 2714 <p> 2715 More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts 2716 that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a> 2717 to the type <code>T</code>. 2718 In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>; 2719 otherwise the type assertion is invalid since it is not possible for <code>x</code> 2720 to store a value of type <code>T</code>. 2721 If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type 2722 of <code>x</code> implements the interface <code>T</code>. 2723 </p> 2724 <p> 2725 If the type assertion holds, the value of the expression is the value 2726 stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false, 2727 a <a href="#Run_time_panics">run-time panic</a> occurs. 2728 In other words, even though the dynamic type of <code>x</code> 2729 is known only at run time, the type of <code>x.(T)</code> is 2730 known to be <code>T</code> in a correct program. 2731 </p> 2732 2733 <pre> 2734 var x interface{} = 7 // x has dynamic type int and value 7 2735 i := x.(int) // i has type int and value 7 2736 2737 type I interface { m() } 2738 var y I 2739 s := y.(string) // illegal: string does not implement I (missing method m) 2740 r := y.(io.Reader) // r has type io.Reader and y must implement both I and io.Reader 2741 </pre> 2742 2743 <p> 2744 If a type assertion is used in an <a href="#Assignments">assignment</a> or initialization of the form 2745 </p> 2746 2747 <pre> 2748 v, ok = x.(T) 2749 v, ok := x.(T) 2750 var v, ok = x.(T) 2751 </pre> 2752 2753 <p> 2754 the result of the assertion is a pair of values with types <code>(T, bool)</code>. 2755 If the assertion holds, the expression returns the pair <code>(x.(T), true)</code>; 2756 otherwise, the expression returns <code>(Z, false)</code> where <code>Z</code> 2757 is the <a href="#The_zero_value">zero value</a> for type <code>T</code>. 2758 No run-time panic occurs in this case. 2759 The type assertion in this construct thus acts like a function call 2760 returning a value and a boolean indicating success. 2761 </p> 2762 2763 2764 <h3 id="Calls">Calls</h3> 2765 2766 <p> 2767 Given an expression <code>f</code> of function type 2768 <code>F</code>, 2769 </p> 2770 2771 <pre> 2772 f(a1, a2, … an) 2773 </pre> 2774 2775 <p> 2776 calls <code>f</code> with arguments <code>a1, a2, … an</code>. 2777 Except for one special case, arguments must be single-valued expressions 2778 <a href="#Assignability">assignable</a> to the parameter types of 2779 <code>F</code> and are evaluated before the function is called. 2780 The type of the expression is the result type 2781 of <code>F</code>. 2782 A method invocation is similar but the method itself 2783 is specified as a selector upon a value of the receiver type for 2784 the method. 2785 </p> 2786 2787 <pre> 2788 math.Atan2(x, y) // function call 2789 var pt *Point 2790 pt.Scale(3.5) // method call with receiver pt 2791 </pre> 2792 2793 <p> 2794 In a function call, the function value and arguments are evaluated in 2795 <a href="#Order_of_evaluation">the usual order</a>. 2796 After they are evaluated, the parameters of the call are passed by value to the function 2797 and the called function begins execution. 2798 The return parameters of the function are passed by value 2799 back to the calling function when the function returns. 2800 </p> 2801 2802 <p> 2803 Calling a <code>nil</code> function value 2804 causes a <a href="#Run_time_panics">run-time panic</a>. 2805 </p> 2806 2807 <p> 2808 As a special case, if the return values of a function or method 2809 <code>g</code> are equal in number and individually 2810 assignable to the parameters of another function or method 2811 <code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code> 2812 will invoke <code>f</code> after binding the return values of 2813 <code>g</code> to the parameters of <code>f</code> in order. The call 2814 of <code>f</code> must contain no parameters other than the call of <code>g</code>, 2815 and <code>g</code> must have at least one return value. 2816 If <code>f</code> has a final <code>...</code> parameter, it is 2817 assigned the return values of <code>g</code> that remain after 2818 assignment of regular parameters. 2819 </p> 2820 2821 <pre> 2822 func Split(s string, pos int) (string, string) { 2823 return s[0:pos], s[pos:] 2824 } 2825 2826 func Join(s, t string) string { 2827 return s + t 2828 } 2829 2830 if Join(Split(value, len(value)/2)) != value { 2831 log.Panic("test fails") 2832 } 2833 </pre> 2834 2835 <p> 2836 A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a> 2837 of (the type of) <code>x</code> contains <code>m</code> and the 2838 argument list can be assigned to the parameter list of <code>m</code>. 2839 If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&x</code>'s method 2840 set contains <code>m</code>, <code>x.m()</code> is shorthand 2841 for <code>(&x).m()</code>: 2842 </p> 2843 2844 <pre> 2845 var p Point 2846 p.Scale(3.5) 2847 </pre> 2848 2849 <p> 2850 There is no distinct method type and there are no method literals. 2851 </p> 2852 2853 <h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3> 2854 2855 <p> 2856 If <code>f</code> is variadic with final parameter type <code>...T</code>, 2857 then within the function the argument is equivalent to a parameter of type 2858 <code>[]T</code>. At each call of <code>f</code>, the argument 2859 passed to the final parameter is 2860 a new slice of type <code>[]T</code> whose successive elements are 2861 the actual arguments, which all must be <a href="#Assignability">assignable</a> 2862 to the type <code>T</code>. The length of the slice is therefore the number of 2863 arguments bound to the final parameter and may differ for each call site. 2864 </p> 2865 2866 <p> 2867 Given the function and call 2868 </p> 2869 <pre> 2870 func Greeting(prefix string, who ...string) 2871 Greeting("hello:", "Joe", "Anna", "Eileen") 2872 </pre> 2873 2874 <p> 2875 within <code>Greeting</code>, <code>who</code> will have the value 2876 <code>[]string{"Joe", "Anna", "Eileen"}</code> 2877 </p> 2878 2879 <p> 2880 If the final argument is assignable to a slice type <code>[]T</code>, it may be 2881 passed unchanged as the value for a <code>...T</code> parameter if the argument 2882 is followed by <code>...</code>. In this case no new slice is created. 2883 </p> 2884 2885 <p> 2886 Given the slice <code>s</code> and call 2887 </p> 2888 2889 <pre> 2890 s := []string{"James", "Jasmine"} 2891 Greeting("goodbye:", s...) 2892 </pre> 2893 2894 <p> 2895 within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code> 2896 with the same underlying array. 2897 </p> 2898 2899 2900 <h3 id="Operators">Operators</h3> 2901 2902 <p> 2903 Operators combine operands into expressions. 2904 </p> 2905 2906 <pre class="ebnf"> 2907 Expression = UnaryExpr | Expression binary_op UnaryExpr . 2908 UnaryExpr = PrimaryExpr | unary_op UnaryExpr . 2909 2910 binary_op = "||" | "&&" | rel_op | add_op | mul_op . 2911 rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" . 2912 add_op = "+" | "-" | "|" | "^" . 2913 mul_op = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" . 2914 2915 unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-" . 2916 </pre> 2917 2918 <p> 2919 Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>. 2920 For other binary operators, the operand types must be <a href="#Type_identity">identical</a> 2921 unless the operation involves shifts or untyped <a href="#Constants">constants</a>. 2922 For operations involving constants only, see the section on 2923 <a href="#Constant_expressions">constant expressions</a>. 2924 </p> 2925 2926 <p> 2927 Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a> 2928 and the other operand is not, the constant is <a href="#Conversions">converted</a> 2929 to the type of the other operand. 2930 </p> 2931 2932 <p> 2933 The right operand in a shift expression must have unsigned integer type 2934 or be an untyped constant that can be converted to unsigned integer type. 2935 If the left operand of a non-constant shift expression is an untyped constant, 2936 the type of the constant is what it would be if the shift expression were 2937 replaced by its left operand alone. 2938 </p> 2939 2940 <pre> 2941 var s uint = 33 2942 var i = 1<<s // 1 has type int 2943 var j int32 = 1<<s // 1 has type int32; j == 0 2944 var k = uint64(1<<s) // 1 has type uint64; k == 1<<33 2945 var m int = 1.0<<s // 1.0 has type int 2946 var n = 1.0<<s != i // 1.0 has type int; n == false if ints are 32bits in size 2947 var o = 1<<s == 2<<s // 1 and 2 have type int; o == true if ints are 32bits in size 2948 var p = 1<<s == 1<<33 // illegal if ints are 32bits in size: 1 has type int, but 1<<33 overflows int 2949 var u = 1.0<<s // illegal: 1.0 has type float64, cannot shift 2950 var u1 = 1.0<<s != 0 // illegal: 1.0 has type float64, cannot shift 2951 var u2 = 1<<s != 1.0 // illegal: 1 has type float64, cannot shift 2952 var v float32 = 1<<s // illegal: 1 has type float32, cannot shift 2953 var w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression 2954 </pre> 2955 2956 <h3 id="Operator_precedence">Operator precedence</h3> 2957 <p> 2958 Unary operators have the highest precedence. 2959 As the <code>++</code> and <code>--</code> operators form 2960 statements, not expressions, they fall 2961 outside the operator hierarchy. 2962 As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>. 2963 <p> 2964 There are five precedence levels for binary operators. 2965 Multiplication operators bind strongest, followed by addition 2966 operators, comparison operators, <code>&&</code> (logical AND), 2967 and finally <code>||</code> (logical OR): 2968 </p> 2969 2970 <pre class="grammar"> 2971 Precedence Operator 2972 5 * / % << >> & &^ 2973 4 + - | ^ 2974 3 == != < <= > >= 2975 2 && 2976 1 || 2977 </pre> 2978 2979 <p> 2980 Binary operators of the same precedence associate from left to right. 2981 For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>. 2982 </p> 2983 2984 <pre> 2985 +x 2986 23 + 3*x[i] 2987 x <= f() 2988 ^a >> b 2989 f() || g() 2990 x == y+1 && <-chanPtr > 0 2991 </pre> 2992 2993 2994 <h3 id="Arithmetic_operators">Arithmetic operators</h3> 2995 <p> 2996 Arithmetic operators apply to numeric values and yield a result of the same 2997 type as the first operand. The four standard arithmetic operators (<code>+</code>, 2998 <code>-</code>, <code>*</code>, <code>/</code>) apply to integer, 2999 floating-point, and complex types; <code>+</code> also applies 3000 to strings. All other arithmetic operators apply to integers only. 3001 </p> 3002 3003 <pre class="grammar"> 3004 + sum integers, floats, complex values, strings 3005 - difference integers, floats, complex values 3006 * product integers, floats, complex values 3007 / quotient integers, floats, complex values 3008 % remainder integers 3009 3010 & bitwise AND integers 3011 | bitwise OR integers 3012 ^ bitwise XOR integers 3013 &^ bit clear (AND NOT) integers 3014 3015 << left shift integer << unsigned integer 3016 >> right shift integer >> unsigned integer 3017 </pre> 3018 3019 <p> 3020 Strings can be concatenated using the <code>+</code> operator 3021 or the <code>+=</code> assignment operator: 3022 </p> 3023 3024 <pre> 3025 s := "hi" + string(c) 3026 s += " and good bye" 3027 </pre> 3028 3029 <p> 3030 String addition creates a new string by concatenating the operands. 3031 </p> 3032 <p> 3033 For two integer values <code>x</code> and <code>y</code>, the integer quotient 3034 <code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following 3035 relationships: 3036 </p> 3037 3038 <pre> 3039 x = q*y + r and |r| < |y| 3040 </pre> 3041 3042 <p> 3043 with <code>x / y</code> truncated towards zero 3044 (<a href="http://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>). 3045 </p> 3046 3047 <pre> 3048 x y x / y x % y 3049 5 3 1 2 3050 -5 3 -1 -2 3051 5 -3 -1 2 3052 -5 -3 1 -2 3053 </pre> 3054 3055 <p> 3056 As an exception to this rule, if the dividend <code>x</code> is the most 3057 negative value for the int type of <code>x</code>, the quotient 3058 <code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>). 3059 </p> 3060 3061 <pre> 3062 x, q 3063 int8 -128 3064 int16 -32768 3065 int32 -2147483648 3066 int64 -9223372036854775808 3067 </pre> 3068 3069 <p> 3070 If the divisor is a <a href="#Constants">constant</a>, it must not be zero. 3071 If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. 3072 If the dividend is non-negative and the divisor is a constant power of 2, 3073 the division may be replaced by a right shift, and computing the remainder may 3074 be replaced by a bitwise AND operation: 3075 </p> 3076 3077 <pre> 3078 x x / 4 x % 4 x >> 2 x & 3 3079 11 2 3 2 3 3080 -11 -2 -3 -3 1 3081 </pre> 3082 3083 <p> 3084 The shift operators shift the left operand by the shift count specified by the 3085 right operand. They implement arithmetic shifts if the left operand is a signed 3086 integer and logical shifts if it is an unsigned integer. 3087 There is no upper limit on the shift count. Shifts behave 3088 as if the left operand is shifted <code>n</code> times by 1 for a shift 3089 count of <code>n</code>. 3090 As a result, <code>x << 1</code> is the same as <code>x*2</code> 3091 and <code>x >> 1</code> is the same as 3092 <code>x/2</code> but truncated towards negative infinity. 3093 </p> 3094 3095 <p> 3096 For integer operands, the unary operators 3097 <code>+</code>, <code>-</code>, and <code>^</code> are defined as 3098 follows: 3099 </p> 3100 3101 <pre class="grammar"> 3102 +x is 0 + x 3103 -x negation is 0 - x 3104 ^x bitwise complement is m ^ x with m = "all bits set to 1" for unsigned x 3105 and m = -1 for signed x 3106 </pre> 3107 3108 <p> 3109 For floating-point and complex numbers, 3110 <code>+x</code> is the same as <code>x</code>, 3111 while <code>-x</code> is the negation of <code>x</code>. 3112 The result of a floating-point or complex division by zero is not specified beyond the 3113 IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a> 3114 occurs is implementation-specific. 3115 </p> 3116 3117 <h3 id="Integer_overflow">Integer overflow</h3> 3118 3119 <p> 3120 For unsigned integer values, the operations <code>+</code>, 3121 <code>-</code>, <code>*</code>, and <code><<</code> are 3122 computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of 3123 the <a href="#Numeric_types">unsigned integer</a>'s type. 3124 Loosely speaking, these unsigned integer operations 3125 discard high bits upon overflow, and programs may rely on ``wrap around''. 3126 </p> 3127 <p> 3128 For signed integers, the operations <code>+</code>, 3129 <code>-</code>, <code>*</code>, and <code><<</code> may legally 3130 overflow and the resulting value exists and is deterministically defined 3131 by the signed integer representation, the operation, and its operands. 3132 No exception is raised as a result of overflow. A 3133 compiler may not optimize code under the assumption that overflow does 3134 not occur. For instance, it may not assume that <code>x < x + 1</code> is always true. 3135 </p> 3136 3137 3138 <h3 id="Comparison_operators">Comparison operators</h3> 3139 3140 <p> 3141 Comparison operators compare two operands and yield an untyped boolean value. 3142 </p> 3143 3144 <pre class="grammar"> 3145 == equal 3146 != not equal 3147 < less 3148 <= less or equal 3149 > greater 3150 >= greater or equal 3151 </pre> 3152 3153 <p> 3154 In any comparison, the first operand 3155 must be <a href="#Assignability">assignable</a> 3156 to the type of the second operand, or vice versa. 3157 </p> 3158 <p> 3159 The equality operators <code>==</code> and <code>!=</code> apply 3160 to operands that are <i>comparable</i>. 3161 The ordering operators <code><</code>, <code><=</code>, <code>></code>, and <code>>=</code> 3162 apply to operands that are <i>ordered</i>. 3163 These terms and the result of the comparisons are defined as follows: 3164 </p> 3165 3166 <ul> 3167 <li> 3168 Boolean values are comparable. 3169 Two boolean values are equal if they are either both 3170 <code>true</code> or both <code>false</code>. 3171 </li> 3172 3173 <li> 3174 Integer values are comparable and ordered, in the usual way. 3175 </li> 3176 3177 <li> 3178 Floating point values are comparable and ordered, 3179 as defined by the IEEE-754 standard. 3180 </li> 3181 3182 <li> 3183 Complex values are comparable. 3184 Two complex values <code>u</code> and <code>v</code> are 3185 equal if both <code>real(u) == real(v)</code> and 3186 <code>imag(u) == imag(v)</code>. 3187 </li> 3188 3189 <li> 3190 String values are comparable and ordered, lexically byte-wise. 3191 </li> 3192 3193 <li> 3194 Pointer values are comparable. 3195 Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>. 3196 Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal. 3197 </li> 3198 3199 <li> 3200 Channel values are comparable. 3201 Two channel values are equal if they were created by the same call to 3202 <a href="#Making_slices_maps_and_channels"><code>make</code></a> 3203 or if both have value <code>nil</code>. 3204 </li> 3205 3206 <li> 3207 Interface values are comparable. 3208 Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types 3209 and equal dynamic values or if both have value <code>nil</code>. 3210 </li> 3211 3212 <li> 3213 A value <code>x</code> of non-interface type <code>X</code> and 3214 a value <code>t</code> of interface type <code>T</code> are comparable when values 3215 of type <code>X</code> are comparable and 3216 <code>X</code> implements <code>T</code>. 3217 They are equal if <code>t</code>'s dynamic type is identical to <code>X</code> 3218 and <code>t</code>'s dynamic value is equal to <code>x</code>. 3219 </li> 3220 3221 <li> 3222 Struct values are comparable if all their fields are comparable. 3223 Two struct values are equal if their corresponding 3224 non-<a href="#Blank_identifier">blank</a> fields are equal. 3225 </li> 3226 3227 <li> 3228 Array values are comparable if values of the array element type are comparable. 3229 Two array values are equal if their corresponding elements are equal. 3230 </li> 3231 </ul> 3232 3233 <p> 3234 A comparison of two interface values with identical dynamic types 3235 causes a <a href="#Run_time_panics">run-time panic</a> if values 3236 of that type are not comparable. This behavior applies not only to direct interface 3237 value comparisons but also when comparing arrays of interface values 3238 or structs with interface-valued fields. 3239 </p> 3240 3241 <p> 3242 Slice, map, and function values are not comparable. 3243 However, as a special case, a slice, map, or function value may 3244 be compared to the predeclared identifier <code>nil</code>. 3245 Comparison of pointer, channel, and interface values to <code>nil</code> 3246 is also allowed and follows from the general rules above. 3247 </p> 3248 3249 <pre> 3250 const c = 3 < 4 // c is the untyped bool constant true 3251 3252 type MyBool bool 3253 var x, y int 3254 var ( 3255 // The result of a comparison is an untyped bool. 3256 // The usual assignment rules apply. 3257 b3 = x == y // b3 has type bool 3258 b4 bool = x == y // b4 has type bool 3259 b5 MyBool = x == y // b5 has type MyBool 3260 ) 3261 </pre> 3262 3263 <h3 id="Logical_operators">Logical operators</h3> 3264 3265 <p> 3266 Logical operators apply to <a href="#Boolean_types">boolean</a> values 3267 and yield a result of the same type as the operands. 3268 The right operand is evaluated conditionally. 3269 </p> 3270 3271 <pre class="grammar"> 3272 && conditional AND p && q is "if p then q else false" 3273 || conditional OR p || q is "if p then true else q" 3274 ! NOT !p is "not p" 3275 </pre> 3276 3277 3278 <h3 id="Address_operators">Address operators</h3> 3279 3280 <p> 3281 For an operand <code>x</code> of type <code>T</code>, the address operation 3282 <code>&x</code> generates a pointer of type <code>*T</code> to <code>x</code>. 3283 The operand must be <i>addressable</i>, 3284 that is, either a variable, pointer indirection, or slice indexing 3285 operation; or a field selector of an addressable struct operand; 3286 or an array indexing operation of an addressable array. 3287 As an exception to the addressability requirement, <code>x</code> may also be a 3288 (possibly parenthesized) 3289 <a href="#Composite_literals">composite literal</a>. 3290 If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>, 3291 then the evaluation of <code>&x</code> does too. 3292 </p> 3293 3294 <p> 3295 For an operand <code>x</code> of pointer type <code>*T</code>, the pointer 3296 indirection <code>*x</code> denotes the value of type <code>T</code> pointed 3297 to by <code>x</code>. 3298 If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code> 3299 will cause a <a href="#Run_time_panics">run-time panic</a>. 3300 </p> 3301 3302 <pre> 3303 &x 3304 &a[f(2)] 3305 &Point{2, 3} 3306 *p 3307 *pf(x) 3308 3309 var x *int = nil 3310 *x // causes a run-time panic 3311 &*x // causes a run-time panic 3312 </pre> 3313 3314 3315 <h3 id="Receive_operator">Receive operator</h3> 3316 3317 <p> 3318 For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>, 3319 the value of the receive operation <code><-ch</code> is the value received 3320 from the channel <code>ch</code>. The channel direction must permit receive operations, 3321 and the type of the receive operation is the element type of the channel. 3322 The expression blocks until a value is available. 3323 Receiving from a <code>nil</code> channel blocks forever. 3324 A receive operation on a <a href="#Close">closed</a> channel can always proceed 3325 immediately, yielding the element type's <a href="#The_zero_value">zero value</a>. 3326 </p> 3327 3328 <pre> 3329 v1 := <-ch 3330 v2 = <-ch 3331 f(<-ch) 3332 <-strobe // wait until clock pulse and discard received value 3333 </pre> 3334 3335 <p> 3336 A receive expression used in an assignment or initialization of the form 3337 </p> 3338 3339 <pre> 3340 x, ok = <-ch 3341 x, ok := <-ch 3342 var x, ok = <-ch 3343 </pre> 3344 3345 <p> 3346 yields an additional result of type <code>bool</code> reporting whether the 3347 communication succeeded. The value of <code>ok</code> is <code>true</code> 3348 if the value received was delivered by a successful send operation to the 3349 channel, or <code>false</code> if it is a zero value generated because the 3350 channel is closed and empty. 3351 </p> 3352 3353 3354 <h3 id="Method_expressions">Method expressions</h3> 3355 3356 <p> 3357 If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>, 3358 <code>T.M</code> is a function that is callable as a regular function 3359 with the same arguments as <code>M</code> prefixed by an additional 3360 argument that is the receiver of the method. 3361 </p> 3362 3363 <pre class="ebnf"> 3364 MethodExpr = ReceiverType "." MethodName . 3365 ReceiverType = TypeName | "(" "*" TypeName ")" | "(" ReceiverType ")" . 3366 </pre> 3367 3368 <p> 3369 Consider a struct type <code>T</code> with two methods, 3370 <code>Mv</code>, whose receiver is of type <code>T</code>, and 3371 <code>Mp</code>, whose receiver is of type <code>*T</code>. 3372 </p> 3373 3374 <pre> 3375 type T struct { 3376 a int 3377 } 3378 func (tv T) Mv(a int) int { return 0 } // value receiver 3379 func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver 3380 3381 var t T 3382 </pre> 3383 3384 <p> 3385 The expression 3386 </p> 3387 3388 <pre> 3389 T.Mv 3390 </pre> 3391 3392 <p> 3393 yields a function equivalent to <code>Mv</code> but 3394 with an explicit receiver as its first argument; it has signature 3395 </p> 3396 3397 <pre> 3398 func(tv T, a int) int 3399 </pre> 3400 3401 <p> 3402 That function may be called normally with an explicit receiver, so 3403 these five invocations are equivalent: 3404 </p> 3405 3406 <pre> 3407 t.Mv(7) 3408 T.Mv(t, 7) 3409 (T).Mv(t, 7) 3410 f1 := T.Mv; f1(t, 7) 3411 f2 := (T).Mv; f2(t, 7) 3412 </pre> 3413 3414 <p> 3415 Similarly, the expression 3416 </p> 3417 3418 <pre> 3419 (*T).Mp 3420 </pre> 3421 3422 <p> 3423 yields a function value representing <code>Mp</code> with signature 3424 </p> 3425 3426 <pre> 3427 func(tp *T, f float32) float32 3428 </pre> 3429 3430 <p> 3431 For a method with a value receiver, one can derive a function 3432 with an explicit pointer receiver, so 3433 </p> 3434 3435 <pre> 3436 (*T).Mv 3437 </pre> 3438 3439 <p> 3440 yields a function value representing <code>Mv</code> with signature 3441 </p> 3442 3443 <pre> 3444 func(tv *T, a int) int 3445 </pre> 3446 3447 <p> 3448 Such a function indirects through the receiver to create a value 3449 to pass as the receiver to the underlying method; 3450 the method does not overwrite the value whose address is passed in 3451 the function call. 3452 </p> 3453 3454 <p> 3455 The final case, a value-receiver function for a pointer-receiver method, 3456 is illegal because pointer-receiver methods are not in the method set 3457 of the value type. 3458 </p> 3459 3460 <p> 3461 Function values derived from methods are called with function call syntax; 3462 the receiver is provided as the first argument to the call. 3463 That is, given <code>f := T.Mv</code>, <code>f</code> is invoked 3464 as <code>f(t, 7)</code> not <code>t.f(7)</code>. 3465 To construct a function that binds the receiver, use a 3466 <a href="#Function_literals">function literal</a> or 3467 <a href="#Method_values">method value</a>. 3468 </p> 3469 3470 <p> 3471 It is legal to derive a function value from a method of an interface type. 3472 The resulting function takes an explicit receiver of that interface type. 3473 </p> 3474 3475 <h3 id="Method_values">Method values</h3> 3476 3477 <p> 3478 If the expression <code>x</code> has static type <code>T</code> and 3479 <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>, 3480 <code>x.M</code> is called a <i>method value</i>. 3481 The method value <code>x.M</code> is a function value that is callable 3482 with the same arguments as a method call of <code>x.M</code>. 3483 The expression <code>x</code> is evaluated and saved during the evaluation of the 3484 method value; the saved copy is then used as the receiver in any calls, 3485 which may be executed later. 3486 </p> 3487 3488 <p> 3489 The type <code>T</code> may be an interface or non-interface type. 3490 </p> 3491 3492 <p> 3493 As in the discussion of <a href="#Method_expressions">method expressions</a> above, 3494 consider a struct type <code>T</code> with two methods, 3495 <code>Mv</code>, whose receiver is of type <code>T</code>, and 3496 <code>Mp</code>, whose receiver is of type <code>*T</code>. 3497 </p> 3498 3499 <pre> 3500 type T struct { 3501 a int 3502 } 3503 func (tv T) Mv(a int) int { return 0 } // value receiver 3504 func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver 3505 3506 var t T 3507 var pt *T 3508 func makeT() T 3509 </pre> 3510 3511 <p> 3512 The expression 3513 </p> 3514 3515 <pre> 3516 t.Mv 3517 </pre> 3518 3519 <p> 3520 yields a function value of type 3521 </p> 3522 3523 <pre> 3524 func(int) int 3525 </pre> 3526 3527 <p> 3528 These two invocations are equivalent: 3529 </p> 3530 3531 <pre> 3532 t.Mv(7) 3533 f := t.Mv; f(7) 3534 </pre> 3535 3536 <p> 3537 Similarly, the expression 3538 </p> 3539 3540 <pre> 3541 pt.Mp 3542 </pre> 3543 3544 <p> 3545 yields a function value of type 3546 </p> 3547 3548 <pre> 3549 func(float32) float32 3550 </pre> 3551 3552 <p> 3553 As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver 3554 using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>. 3555 </p> 3556 3557 <p> 3558 As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver 3559 using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&t).Mp</code>. 3560 </p> 3561 3562 <pre> 3563 f := t.Mv; f(7) // like t.Mv(7) 3564 f := pt.Mp; f(7) // like pt.Mp(7) 3565 f := pt.Mv; f(7) // like (*pt).Mv(7) 3566 f := t.Mp; f(7) // like (&t).Mp(7) 3567 f := makeT().Mp // invalid: result of makeT() is not addressable 3568 </pre> 3569 3570 <p> 3571 Although the examples above use non-interface types, it is also legal to create a method value 3572 from a value of interface type. 3573 </p> 3574 3575 <pre> 3576 var i interface { M(int) } = myVal 3577 f := i.M; f(7) // like i.M(7) 3578 </pre> 3579 3580 <h3 id="Conversions">Conversions</h3> 3581 3582 <p> 3583 Conversions are expressions of the form <code>T(x)</code> 3584 where <code>T</code> is a type and <code>x</code> is an expression 3585 that can be converted to type <code>T</code>. 3586 </p> 3587 3588 <pre class="ebnf"> 3589 Conversion = Type "(" Expression [ "," ] ")" . 3590 </pre> 3591 3592 <p> 3593 If the type starts with the operator <code>*</code> or <code><-</code>, 3594 or if the type starts with the keyword <code>func</code> 3595 and has no result list, it must be parenthesized when 3596 necessary to avoid ambiguity: 3597 </p> 3598 3599 <pre> 3600 *Point(p) // same as *(Point(p)) 3601 (*Point)(p) // p is converted to *Point 3602 <-chan int(c) // same as <-(chan int(c)) 3603 (<-chan int)(c) // c is converted to <-chan int 3604 func()(x) // function signature func() x 3605 (func())(x) // x is converted to func() 3606 (func() int)(x) // x is converted to func() int 3607 func() int(x) // x is converted to func() int (unambiguous) 3608 </pre> 3609 3610 <p> 3611 A <a href="#Constants">constant</a> value <code>x</code> can be converted to 3612 type <code>T</code> in any of these cases: 3613 </p> 3614 3615 <ul> 3616 <li> 3617 <code>x</code> is representable by a value of type <code>T</code>. 3618 </li> 3619 <li> 3620 <code>x</code> is a floating-point constant, 3621 <code>T</code> is a floating-point type, 3622 and <code>x</code> is representable by a value 3623 of type <code>T</code> after rounding using 3624 IEEE 754 round-to-even rules. 3625 The constant <code>T(x)</code> is the rounded value. 3626 </li> 3627 <li> 3628 <code>x</code> is an integer constant and <code>T</code> is a 3629 <a href="#String_types">string type</a>. 3630 The <a href="#Conversions_to_and_from_a_string_type">same rule</a> 3631 as for non-constant <code>x</code> applies in this case. 3632 </li> 3633 </ul> 3634 3635 <p> 3636 Converting a constant yields a typed constant as result. 3637 </p> 3638 3639 <pre> 3640 uint(iota) // iota value of type uint 3641 float32(2.718281828) // 2.718281828 of type float32 3642 complex128(1) // 1.0 + 0.0i of type complex128 3643 float32(0.49999999) // 0.5 of type float32 3644 string('x') // "x" of type string 3645 string(0x266c) // "♬" of type string 3646 MyString("foo" + "bar") // "foobar" of type MyString 3647 string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant 3648 (*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type 3649 int(1.2) // illegal: 1.2 cannot be represented as an int 3650 string(65.0) // illegal: 65.0 is not an integer constant 3651 </pre> 3652 3653 <p> 3654 A non-constant value <code>x</code> can be converted to type <code>T</code> 3655 in any of these cases: 3656 </p> 3657 3658 <ul> 3659 <li> 3660 <code>x</code> is <a href="#Assignability">assignable</a> 3661 to <code>T</code>. 3662 </li> 3663 <li> 3664 <code>x</code>'s type and <code>T</code> have identical 3665 <a href="#Types">underlying types</a>. 3666 </li> 3667 <li> 3668 <code>x</code>'s type and <code>T</code> are unnamed pointer types 3669 and their pointer base types have identical underlying types. 3670 </li> 3671 <li> 3672 <code>x</code>'s type and <code>T</code> are both integer or floating 3673 point types. 3674 </li> 3675 <li> 3676 <code>x</code>'s type and <code>T</code> are both complex types. 3677 </li> 3678 <li> 3679 <code>x</code> is an integer or a slice of bytes or runes 3680 and <code>T</code> is a string type. 3681 </li> 3682 <li> 3683 <code>x</code> is a string and <code>T</code> is a slice of bytes or runes. 3684 </li> 3685 </ul> 3686 3687 <p> 3688 Specific rules apply to (non-constant) conversions between numeric types or 3689 to and from a string type. 3690 These conversions may change the representation of <code>x</code> 3691 and incur a run-time cost. 3692 All other conversions only change the type but not the representation 3693 of <code>x</code>. 3694 </p> 3695 3696 <p> 3697 There is no linguistic mechanism to convert between pointers and integers. 3698 The package <a href="#Package_unsafe"><code>unsafe</code></a> 3699 implements this functionality under 3700 restricted circumstances. 3701 </p> 3702 3703 <h4>Conversions between numeric types</h4> 3704 3705 <p> 3706 For the conversion of non-constant numeric values, the following rules apply: 3707 </p> 3708 3709 <ol> 3710 <li> 3711 When converting between integer types, if the value is a signed integer, it is 3712 sign extended to implicit infinite precision; otherwise it is zero extended. 3713 It is then truncated to fit in the result type's size. 3714 For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>. 3715 The conversion always yields a valid value; there is no indication of overflow. 3716 </li> 3717 <li> 3718 When converting a floating-point number to an integer, the fraction is discarded 3719 (truncation towards zero). 3720 </li> 3721 <li> 3722 When converting an integer or floating-point number to a floating-point type, 3723 or a complex number to another complex type, the result value is rounded 3724 to the precision specified by the destination type. 3725 For instance, the value of a variable <code>x</code> of type <code>float32</code> 3726 may be stored using additional precision beyond that of an IEEE-754 32-bit number, 3727 but float32(x) represents the result of rounding <code>x</code>'s value to 3728 32-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits 3729 of precision, but <code>float32(x + 0.1)</code> does not. 3730 </li> 3731 </ol> 3732 3733 <p> 3734 In all non-constant conversions involving floating-point or complex values, 3735 if the result type cannot represent the value the conversion 3736 succeeds but the result value is implementation-dependent. 3737 </p> 3738 3739 <h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4> 3740 3741 <ol> 3742 <li> 3743 Converting a signed or unsigned integer value to a string type yields a 3744 string containing the UTF-8 representation of the integer. Values outside 3745 the range of valid Unicode code points are converted to <code>"\uFFFD"</code>. 3746 3747 <pre> 3748 string('a') // "a" 3749 string(-1) // "\ufffd" == "\xef\xbf\xbd" 3750 string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8" 3751 type MyString string 3752 MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5" 3753 </pre> 3754 </li> 3755 3756 <li> 3757 Converting a slice of bytes to a string type yields 3758 a string whose successive bytes are the elements of the slice. 3759 3760 <pre> 3761 string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø" 3762 string([]byte{}) // "" 3763 string([]byte(nil)) // "" 3764 3765 type MyBytes []byte 3766 string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø" 3767 </pre> 3768 </li> 3769 3770 <li> 3771 Converting a slice of runes to a string type yields 3772 a string that is the concatenation of the individual rune values 3773 converted to strings. 3774 3775 <pre> 3776 string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" 3777 string([]rune{}) // "" 3778 string([]rune(nil)) // "" 3779 3780 type MyRunes []rune 3781 string(MyRunes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔" 3782 </pre> 3783 </li> 3784 3785 <li> 3786 Converting a value of a string type to a slice of bytes type 3787 yields a slice whose successive elements are the bytes of the string. 3788 3789 <pre> 3790 []byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} 3791 []byte("") // []byte{} 3792 3793 MyBytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} 3794 </pre> 3795 </li> 3796 3797 <li> 3798 Converting a value of a string type to a slice of runes type 3799 yields a slice containing the individual Unicode code points of the string. 3800 3801 <pre> 3802 []rune(MyString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4} 3803 []rune("") // []rune{} 3804 3805 MyRunes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4} 3806 </pre> 3807 </li> 3808 </ol> 3809 3810 3811 <h3 id="Constant_expressions">Constant expressions</h3> 3812 3813 <p> 3814 Constant expressions may contain only <a href="#Constants">constant</a> 3815 operands and are evaluated at compile time. 3816 </p> 3817 3818 <p> 3819 Untyped boolean, numeric, and string constants may be used as operands 3820 wherever it is legal to use an operand of boolean, numeric, or string type, 3821 respectively. 3822 Except for shift operations, if the operands of a binary operation are 3823 different kinds of untyped constants, the operation and, for non-boolean operations, the result use 3824 the kind that appears later in this list: integer, rune, floating-point, complex. 3825 For example, an untyped integer constant divided by an 3826 untyped complex constant yields an untyped complex constant. 3827 </p> 3828 3829 <p> 3830 A constant <a href="#Comparison_operators">comparison</a> always yields 3831 an untyped boolean constant. If the left operand of a constant 3832 <a href="#Operators">shift expression</a> is an untyped constant, the 3833 result is an integer constant; otherwise it is a constant of the same 3834 type as the left operand, which must be of 3835 <a href="#Numeric_types">integer type</a>. 3836 Applying all other operators to untyped constants results in an untyped 3837 constant of the same kind (that is, a boolean, integer, floating-point, 3838 complex, or string constant). 3839 </p> 3840 3841 <pre> 3842 const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant) 3843 const b = 15 / 4 // b == 3 (untyped integer constant) 3844 const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant) 3845 const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division) 3846 const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division) 3847 const d = 1 << 3.0 // d == 8 (untyped integer constant) 3848 const e = 1.0 << 3 // e == 8 (untyped integer constant) 3849 const f = int32(1) << 33 // illegal (constant 8589934592 overflows int32) 3850 const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant) 3851 const h = "foo" > "bar" // h == true (untyped boolean constant) 3852 const j = true // j == true (untyped boolean constant) 3853 const k = 'w' + 1 // k == 'x' (untyped rune constant) 3854 const l = "hi" // l == "hi" (untyped string constant) 3855 const m = string(k) // m == "x" (type string) 3856 const Σ = 1 - 0.707i // (untyped complex constant) 3857 const Δ = Σ + 2.0e-4 // (untyped complex constant) 3858 const Φ = iota*1i - 1/1i // (untyped complex constant) 3859 </pre> 3860 3861 <p> 3862 Applying the built-in function <code>complex</code> to untyped 3863 integer, rune, or floating-point constants yields 3864 an untyped complex constant. 3865 </p> 3866 3867 <pre> 3868 const ic = complex(0, c) // ic == 3.75i (untyped complex constant) 3869 const iΘ = complex(0, Θ) // iΘ == 1.5i (type complex128) 3870 </pre> 3871 3872 <p> 3873 Constant expressions are always evaluated exactly; intermediate values and the 3874 constants themselves may require precision significantly larger than supported 3875 by any predeclared type in the language. The following are legal declarations: 3876 </p> 3877 3878 <pre> 3879 const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (untyped integer constant) 3880 const Four int8 = Huge >> 98 // Four == 4 (type int8) 3881 </pre> 3882 3883 <p> 3884 The divisor of a constant division or remainder operation must not be zero: 3885 </p> 3886 3887 <pre> 3888 3.14 / 0.0 // illegal: division by zero 3889 </pre> 3890 3891 <p> 3892 The values of <i>typed</i> constants must always be accurately representable as values 3893 of the constant type. The following constant expressions are illegal: 3894 </p> 3895 3896 <pre> 3897 uint(-1) // -1 cannot be represented as a uint 3898 int(3.14) // 3.14 cannot be represented as an int 3899 int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64 3900 Four * 300 // operand 300 cannot be represented as an int8 (type of Four) 3901 Four * 100 // product 400 cannot be represented as an int8 (type of Four) 3902 </pre> 3903 3904 <p> 3905 The mask used by the unary bitwise complement operator <code>^</code> matches 3906 the rule for non-constants: the mask is all 1s for unsigned constants 3907 and -1 for signed and untyped constants. 3908 </p> 3909 3910 <pre> 3911 ^1 // untyped integer constant, equal to -2 3912 uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8 3913 ^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE) 3914 int8(^1) // same as int8(-2) 3915 ^int8(1) // same as -1 ^ int8(1) = -2 3916 </pre> 3917 3918 <p> 3919 Implementation restriction: A compiler may use rounding while 3920 computing untyped floating-point or complex constant expressions; see 3921 the implementation restriction in the section 3922 on <a href="#Constants">constants</a>. This rounding may cause a 3923 floating-point constant expression to be invalid in an integer 3924 context, even if it would be integral when calculated using infinite 3925 precision. 3926 </p> 3927 3928 3929 <h3 id="Order_of_evaluation">Order of evaluation</h3> 3930 3931 <p> 3932 When evaluating the <a href="#Operands">operands</a> of an expression, 3933 <a href="#Assignments">assignment</a>, or 3934 <a href="#Return_statements">return statement</a>, 3935 all function calls, method calls, and 3936 communication operations are evaluated in lexical left-to-right 3937 order. 3938 </p> 3939 3940 <p> 3941 For example, in the assignment 3942 </p> 3943 <pre> 3944 y[f()], ok = g(h(), i()+x[j()], <-c), k() 3945 </pre> 3946 <p> 3947 the function calls and communication happen in the order 3948 <code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>, 3949 <code><-c</code>, <code>g()</code>, and <code>k()</code>. 3950 However, the order of those events compared to the evaluation 3951 and indexing of <code>x</code> and the evaluation 3952 of <code>y</code> is not specified. 3953 </p> 3954 3955 <pre> 3956 a := 1 3957 f := func() int { a++; return a } 3958 x := []int{a, f()} // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified 3959 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 3960 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 3961 </pre> 3962 3963 <p> 3964 Floating-point operations within a single expression are evaluated according to 3965 the associativity of the operators. Explicit parentheses affect the evaluation 3966 by overriding the default associativity. 3967 In the expression <code>x + (y + z)</code> the addition <code>y + z</code> 3968 is performed before adding <code>x</code>. 3969 </p> 3970 3971 <h2 id="Statements">Statements</h2> 3972 3973 <p> 3974 Statements control execution. 3975 </p> 3976 3977 <pre class="ebnf"> 3978 Statement = 3979 Declaration | LabeledStmt | SimpleStmt | 3980 GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt | 3981 FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt | 3982 DeferStmt . 3983 3984 SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl . 3985 </pre> 3986 3987 <h3 id="Terminating_statements">Terminating statements</h3> 3988 3989 <p> 3990 A terminating statement is one of the following: 3991 </p> 3992 3993 <ol> 3994 <li> 3995 A <a href="#Return_statements">"return"</a> or 3996 <a href="#Goto_statements">"goto"</a> statement. 3997 <!-- ul below only for regular layout --> 3998 <ul> </ul> 3999 </li> 4000 4001 <li> 4002 A call to the built-in function 4003 <a href="#Handling_panics"><code>panic</code></a>. 4004 <!-- ul below only for regular layout --> 4005 <ul> </ul> 4006 </li> 4007 4008 <li> 4009 A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement. 4010 <!-- ul below only for regular layout --> 4011 <ul> </ul> 4012 </li> 4013 4014 <li> 4015 An <a href="#If_statements">"if" statement</a> in which: 4016 <ul> 4017 <li>the "else" branch is present, and</li> 4018 <li>both branches are terminating statements.</li> 4019 </ul> 4020 </li> 4021 4022 <li> 4023 A <a href="#For_statements">"for" statement</a> in which: 4024 <ul> 4025 <li>there are no "break" statements referring to the "for" statement, and</li> 4026 <li>the loop condition is absent.</li> 4027 </ul> 4028 </li> 4029 4030 <li> 4031 A <a href="#Switch_statements">"switch" statement</a> in which: 4032 <ul> 4033 <li>there are no "break" statements referring to the "switch" statement,</li> 4034 <li>there is a default case, and</li> 4035 <li>the statement lists in each case, including the default, end in a terminating 4036 statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough" 4037 statement</a>.</li> 4038 </ul> 4039 </li> 4040 4041 <li> 4042 A <a href="#Select_statements">"select" statement</a> in which: 4043 <ul> 4044 <li>there are no "break" statements referring to the "select" statement, and</li> 4045 <li>the statement lists in each case, including the default if present, 4046 end in a terminating statement.</li> 4047 </ul> 4048 </li> 4049 4050 <li> 4051 A <a href="#Labeled_statements">labeled statement</a> labeling 4052 a terminating statement. 4053 </li> 4054 </ol> 4055 4056 <p> 4057 All other statements are not terminating. 4058 </p> 4059 4060 <p> 4061 A <a href="#Blocks">statement list</a> ends in a terminating statement if the list 4062 is not empty and its final statement is terminating. 4063 </p> 4064 4065 4066 <h3 id="Empty_statements">Empty statements</h3> 4067 4068 <p> 4069 The empty statement does nothing. 4070 </p> 4071 4072 <pre class="ebnf"> 4073 EmptyStmt = . 4074 </pre> 4075 4076 4077 <h3 id="Labeled_statements">Labeled statements</h3> 4078 4079 <p> 4080 A labeled statement may be the target of a <code>goto</code>, 4081 <code>break</code> or <code>continue</code> statement. 4082 </p> 4083 4084 <pre class="ebnf"> 4085 LabeledStmt = Label ":" Statement . 4086 Label = identifier . 4087 </pre> 4088 4089 <pre> 4090 Error: log.Panic("error encountered") 4091 </pre> 4092 4093 4094 <h3 id="Expression_statements">Expression statements</h3> 4095 4096 <p> 4097 With the exception of specific built-in functions, 4098 function and method <a href="#Calls">calls</a> and 4099 <a href="#Receive_operator">receive operations</a> 4100 can appear in statement context. Such statements may be parenthesized. 4101 </p> 4102 4103 <pre class="ebnf"> 4104 ExpressionStmt = Expression . 4105 </pre> 4106 4107 <p> 4108 The following built-in functions are not permitted in statement context: 4109 </p> 4110 4111 <pre> 4112 append cap complex imag len make new real 4113 unsafe.Alignof unsafe.Offsetof unsafe.Sizeof 4114 </pre> 4115 4116 <pre> 4117 h(x+y) 4118 f.Close() 4119 <-ch 4120 (<-ch) 4121 len("foo") // illegal if len is the built-in function 4122 </pre> 4123 4124 4125 <h3 id="Send_statements">Send statements</h3> 4126 4127 <p> 4128 A send statement sends a value on a channel. 4129 The channel expression must be of <a href="#Channel_types">channel type</a>, 4130 the channel direction must permit send operations, 4131 and the type of the value to be sent must be <a href="#Assignability">assignable</a> 4132 to the channel's element type. 4133 </p> 4134 4135 <pre class="ebnf"> 4136 SendStmt = Channel "<-" Expression . 4137 Channel = Expression . 4138 </pre> 4139 4140 <p> 4141 Both the channel and the value expression are evaluated before communication 4142 begins. Communication blocks until the send can proceed. 4143 A send on an unbuffered channel can proceed if a receiver is ready. 4144 A send on a buffered channel can proceed if there is room in the buffer. 4145 A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>. 4146 A send on a <code>nil</code> channel blocks forever. 4147 </p> 4148 4149 <p> 4150 Channels act as first-in-first-out queues. 4151 For example, if a single goroutine sends on a channel values 4152 that are received by a single goroutine, the values are received in the order sent. 4153 </p> 4154 4155 <p> 4156 A single channel may be used for send and receive 4157 operations and calls to the built-in functions 4158 <a href="#Length_and_capacity"><code>cap</code></a> and 4159 <a href="#Length_and_capacity"><code>len</code></a> 4160 by any number of goroutines without further synchronization. 4161 </p> 4162 4163 <pre> 4164 ch <- 3 4165 </pre> 4166 4167 4168 <h3 id="IncDec_statements">IncDec statements</h3> 4169 4170 <p> 4171 The "++" and "--" statements increment or decrement their operands 4172 by the untyped <a href="#Constants">constant</a> <code>1</code>. 4173 As with an assignment, the operand must be <a href="#Address_operators">addressable</a> 4174 or a map index expression. 4175 </p> 4176 4177 <pre class="ebnf"> 4178 IncDecStmt = Expression ( "++" | "--" ) . 4179 </pre> 4180 4181 <p> 4182 The following <a href="#Assignments">assignment statements</a> are semantically 4183 equivalent: 4184 </p> 4185 4186 <pre class="grammar"> 4187 IncDec statement Assignment 4188 x++ x += 1 4189 x-- x -= 1 4190 </pre> 4191 4192 4193 <h3 id="Assignments">Assignments</h3> 4194 4195 <pre class="ebnf"> 4196 Assignment = ExpressionList assign_op ExpressionList . 4197 4198 assign_op = [ add_op | mul_op ] "=" . 4199 </pre> 4200 4201 <p> 4202 Each left-hand side operand must be <a href="#Address_operators">addressable</a>, 4203 a map index expression, or the <a href="#Blank_identifier">blank identifier</a>. 4204 Operands may be parenthesized. 4205 </p> 4206 4207 <pre> 4208 x = 1 4209 *p = f() 4210 a[i] = 23 4211 (k) = <-ch // same as: k = <-ch 4212 </pre> 4213 4214 <p> 4215 An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code> 4216 <code>y</code> where <i>op</i> is a binary arithmetic operation is equivalent 4217 to <code>x</code> <code>=</code> <code>x</code> <i>op</i> 4218 <code>y</code> but evaluates <code>x</code> 4219 only once. The <i>op</i><code>=</code> construct is a single token. 4220 In assignment operations, both the left- and right-hand expression lists 4221 must contain exactly one single-valued expression. 4222 </p> 4223 4224 <pre> 4225 a[i] <<= 2 4226 i &^= 1<<n 4227 </pre> 4228 4229 <p> 4230 A tuple assignment assigns the individual elements of a multi-valued 4231 operation to a list of variables. There are two forms. In the 4232 first, the right hand operand is a single multi-valued expression 4233 such as a function evaluation or <a href="#Channel_types">channel</a> or 4234 <a href="#Map_types">map</a> operation or a <a href="#Type_assertions">type assertion</a>. 4235 The number of operands on the left 4236 hand side must match the number of values. For instance, if 4237 <code>f</code> is a function returning two values, 4238 </p> 4239 4240 <pre> 4241 x, y = f() 4242 </pre> 4243 4244 <p> 4245 assigns the first value to <code>x</code> and the second to <code>y</code>. 4246 The <a href="#Blank_identifier">blank identifier</a> provides a 4247 way to ignore values returned by a multi-valued expression: 4248 </p> 4249 4250 <pre> 4251 x, _ = f() // ignore second value returned by f() 4252 </pre> 4253 4254 <p> 4255 In the second form, the number of operands on the left must equal the number 4256 of expressions on the right, each of which must be single-valued, and the 4257 <i>n</i>th expression on the right is assigned to the <i>n</i>th 4258 operand on the left. 4259 </p> 4260 4261 <p> 4262 The assignment proceeds in two phases. 4263 First, the operands of <a href="#Index_expressions">index expressions</a> 4264 and <a href="#Address_operators">pointer indirections</a> 4265 (including implicit pointer indirections in <a href="#Selectors">selectors</a>) 4266 on the left and the expressions on the right are all 4267 <a href="#Order_of_evaluation">evaluated in the usual order</a>. 4268 Second, the assignments are carried out in left-to-right order. 4269 </p> 4270 4271 <pre> 4272 a, b = b, a // exchange a and b 4273 4274 x := []int{1, 2, 3} 4275 i := 0 4276 i, x[i] = 1, 2 // set i = 1, x[0] = 2 4277 4278 i = 0 4279 x[i], i = 2, 1 // set x[0] = 2, i = 1 4280 4281 x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end) 4282 4283 x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5. 4284 4285 type Point struct { x, y int } 4286 var p *Point 4287 x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7 4288 4289 i = 2 4290 x = []int{3, 5, 7} 4291 for i, x[i] = range x { // set i, x[2] = 0, x[0] 4292 break 4293 } 4294 // after this loop, i == 0 and x == []int{3, 5, 3} 4295 </pre> 4296 4297 <p> 4298 In assignments, each value must be 4299 <a href="#Assignability">assignable</a> to the type of the 4300 operand to which it is assigned. If an untyped <a href="#Constants">constant</a> 4301 is assigned to a variable of interface type, the constant is <a href="#Conversions">converted</a> 4302 to type <code>bool</code>, <code>rune</code>, <code>int</code>, <code>float64</code>, 4303 <code>complex128</code> or <code>string</code> 4304 respectively, depending on whether the value is a 4305 boolean, rune, integer, floating-point, complex, or string constant. 4306 </p> 4307 4308 4309 <h3 id="If_statements">If statements</h3> 4310 4311 <p> 4312 "If" statements specify the conditional execution of two branches 4313 according to the value of a boolean expression. If the expression 4314 evaluates to true, the "if" branch is executed, otherwise, if 4315 present, the "else" branch is executed. 4316 </p> 4317 4318 <pre class="ebnf"> 4319 IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] . 4320 </pre> 4321 4322 <pre> 4323 if x > max { 4324 x = max 4325 } 4326 </pre> 4327 4328 <p> 4329 The expression may be preceded by a simple statement, which 4330 executes before the expression is evaluated. 4331 </p> 4332 4333 <pre> 4334 if x := f(); x < y { 4335 return x 4336 } else if x > z { 4337 return z 4338 } else { 4339 return y 4340 } 4341 </pre> 4342 4343 4344 <h3 id="Switch_statements">Switch statements</h3> 4345 4346 <p> 4347 "Switch" statements provide multi-way execution. 4348 An expression or type specifier is compared to the "cases" 4349 inside the "switch" to determine which branch 4350 to execute. 4351 </p> 4352 4353 <pre class="ebnf"> 4354 SwitchStmt = ExprSwitchStmt | TypeSwitchStmt . 4355 </pre> 4356 4357 <p> 4358 There are two forms: expression switches and type switches. 4359 In an expression switch, the cases contain expressions that are compared 4360 against the value of the switch expression. 4361 In a type switch, the cases contain types that are compared against the 4362 type of a specially annotated switch expression. 4363 </p> 4364 4365 <h4 id="Expression_switches">Expression switches</h4> 4366 4367 <p> 4368 In an expression switch, 4369 the switch expression is evaluated and 4370 the case expressions, which need not be constants, 4371 are evaluated left-to-right and top-to-bottom; the first one that equals the 4372 switch expression 4373 triggers execution of the statements of the associated case; 4374 the other cases are skipped. 4375 If no case matches and there is a "default" case, 4376 its statements are executed. 4377 There can be at most one default case and it may appear anywhere in the 4378 "switch" statement. 4379 A missing switch expression is equivalent to 4380 the expression <code>true</code>. 4381 </p> 4382 4383 <pre class="ebnf"> 4384 ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" . 4385 ExprCaseClause = ExprSwitchCase ":" StatementList . 4386 ExprSwitchCase = "case" ExpressionList | "default" . 4387 </pre> 4388 4389 <p> 4390 In a case or default clause, the last non-empty statement 4391 may be a (possibly <a href="#Labeled_statements">labeled</a>) 4392 <a href="#Fallthrough_statements">"fallthrough" statement</a> to 4393 indicate that control should flow from the end of this clause to 4394 the first statement of the next clause. 4395 Otherwise control flows to the end of the "switch" statement. 4396 A "fallthrough" statement may appear as the last statement of all 4397 but the last clause of an expression switch. 4398 </p> 4399 4400 <p> 4401 The expression may be preceded by a simple statement, which 4402 executes before the expression is evaluated. 4403 </p> 4404 4405 <pre> 4406 switch tag { 4407 default: s3() 4408 case 0, 1, 2, 3: s1() 4409 case 4, 5, 6, 7: s2() 4410 } 4411 4412 switch x := f(); { // missing switch expression means "true" 4413 case x < 0: return -x 4414 default: return x 4415 } 4416 4417 switch { 4418 case x < y: f1() 4419 case x < z: f2() 4420 case x == 4: f3() 4421 } 4422 </pre> 4423 4424 <h4 id="Type_switches">Type switches</h4> 4425 4426 <p> 4427 A type switch compares types rather than values. It is otherwise similar 4428 to an expression switch. It is marked by a special switch expression that 4429 has the form of a <a href="#Type_assertions">type assertion</a> 4430 using the reserved word <code>type</code> rather than an actual type: 4431 </p> 4432 4433 <pre> 4434 switch x.(type) { 4435 // cases 4436 } 4437 </pre> 4438 4439 <p> 4440 Cases then match actual types <code>T</code> against the dynamic type of the 4441 expression <code>x</code>. As with type assertions, <code>x</code> must be of 4442 <a href="#Interface_types">interface type</a>, and each non-interface type 4443 <code>T</code> listed in a case must implement the type of <code>x</code>. 4444 </p> 4445 4446 <pre class="ebnf"> 4447 TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" . 4448 TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" . 4449 TypeCaseClause = TypeSwitchCase ":" StatementList . 4450 TypeSwitchCase = "case" TypeList | "default" . 4451 TypeList = Type { "," Type } . 4452 </pre> 4453 4454 <p> 4455 The TypeSwitchGuard may include a 4456 <a href="#Short_variable_declarations">short variable declaration</a>. 4457 When that form is used, the variable is declared at the beginning of 4458 the <a href="#Blocks">implicit block</a> in each clause. 4459 In clauses with a case listing exactly one type, the variable 4460 has that type; otherwise, the variable has the type of the expression 4461 in the TypeSwitchGuard. 4462 </p> 4463 4464 <p> 4465 The type in a case may be <a href="#Predeclared_identifiers"><code>nil</code></a>; 4466 that case is used when the expression in the TypeSwitchGuard 4467 is a <code>nil</code> interface value. 4468 </p> 4469 4470 <p> 4471 Given an expression <code>x</code> of type <code>interface{}</code>, 4472 the following type switch: 4473 </p> 4474 4475 <pre> 4476 switch i := x.(type) { 4477 case nil: 4478 printString("x is nil") // type of i is type of x (interface{}) 4479 case int: 4480 printInt(i) // type of i is int 4481 case float64: 4482 printFloat64(i) // type of i is float64 4483 case func(int) float64: 4484 printFunction(i) // type of i is func(int) float64 4485 case bool, string: 4486 printString("type is bool or string") // type of i is type of x (interface{}) 4487 default: 4488 printString("don't know the type") // type of i is type of x (interface{}) 4489 } 4490 </pre> 4491 4492 <p> 4493 could be rewritten: 4494 </p> 4495 4496 <pre> 4497 v := x // x is evaluated exactly once 4498 if v == nil { 4499 i := v // type of i is type of x (interface{}) 4500 printString("x is nil") 4501 } else if i, isInt := v.(int); isInt { 4502 printInt(i) // type of i is int 4503 } else if i, isFloat64 := v.(float64); isFloat64 { 4504 printFloat64(i) // type of i is float64 4505 } else if i, isFunc := v.(func(int) float64); isFunc { 4506 printFunction(i) // type of i is func(int) float64 4507 } else { 4508 _, isBool := v.(bool) 4509 _, isString := v.(string) 4510 if isBool || isString { 4511 i := v // type of i is type of x (interface{}) 4512 printString("type is bool or string") 4513 } else { 4514 i := v // type of i is type of x (interface{}) 4515 printString("don't know the type") 4516 } 4517 } 4518 </pre> 4519 4520 <p> 4521 The type switch guard may be preceded by a simple statement, which 4522 executes before the guard is evaluated. 4523 </p> 4524 4525 <p> 4526 The "fallthrough" statement is not permitted in a type switch. 4527 </p> 4528 4529 <h3 id="For_statements">For statements</h3> 4530 4531 <p> 4532 A "for" statement specifies repeated execution of a block. The iteration is 4533 controlled by a condition, a "for" clause, or a "range" clause. 4534 </p> 4535 4536 <pre class="ebnf"> 4537 ForStmt = "for" [ Condition | ForClause | RangeClause ] Block . 4538 Condition = Expression . 4539 </pre> 4540 4541 <p> 4542 In its simplest form, a "for" statement specifies the repeated execution of 4543 a block as long as a boolean condition evaluates to true. 4544 The condition is evaluated before each iteration. 4545 If the condition is absent, it is equivalent to <code>true</code>. 4546 </p> 4547 4548 <pre> 4549 for a < b { 4550 a *= 2 4551 } 4552 </pre> 4553 4554 <p> 4555 A "for" statement with a ForClause is also controlled by its condition, but 4556 additionally it may specify an <i>init</i> 4557 and a <i>post</i> statement, such as an assignment, 4558 an increment or decrement statement. The init statement may be a 4559 <a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not. 4560 </p> 4561 4562 <pre class="ebnf"> 4563 ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] . 4564 InitStmt = SimpleStmt . 4565 PostStmt = SimpleStmt . 4566 </pre> 4567 4568 <pre> 4569 for i := 0; i < 10; i++ { 4570 f(i) 4571 } 4572 </pre> 4573 4574 <p> 4575 If non-empty, the init statement is executed once before evaluating the 4576 condition for the first iteration; 4577 the post statement is executed after each execution of the block (and 4578 only if the block was executed). 4579 Any element of the ForClause may be empty but the 4580 <a href="#Semicolons">semicolons</a> are 4581 required unless there is only a condition. 4582 If the condition is absent, it is equivalent to <code>true</code>. 4583 </p> 4584 4585 <pre> 4586 for cond { S() } is the same as for ; cond ; { S() } 4587 for { S() } is the same as for true { S() } 4588 </pre> 4589 4590 <p> 4591 A "for" statement with a "range" clause 4592 iterates through all entries of an array, slice, string or map, 4593 or values received on a channel. For each entry it assigns <i>iteration values</i> 4594 to corresponding <i>iteration variables</i> and then executes the block. 4595 </p> 4596 4597 <pre class="ebnf"> 4598 RangeClause = ( ExpressionList "=" | IdentifierList ":=" ) "range" Expression . 4599 </pre> 4600 4601 <p> 4602 The expression on the right in the "range" clause is called the <i>range expression</i>, 4603 which may be an array, pointer to an array, slice, string, map, or channel permitting 4604 <a href="#Receive_operator">receive operations</a>. 4605 As with an assignment, the operands on the left must be 4606 <a href="#Address_operators">addressable</a> or map index expressions; they 4607 denote the iteration variables. If the range expression is a channel, only 4608 one iteration variable is permitted, otherwise there may be one or two. In the latter case, 4609 if the second iteration variable is the <a href="#Blank_identifier">blank identifier</a>, 4610 the range clause is equivalent to the same clause with only the first variable present. 4611 </p> 4612 4613 <p> 4614 The range expression is evaluated once before beginning the loop, 4615 with one exception. If the range expression is an array or a pointer to an array 4616 and only the first iteration value is present, only the range expression's 4617 length is evaluated; if that length is constant 4618 <a href="#Length_and_capacity">by definition</a>, 4619 the range expression itself will not be evaluated. 4620 </p> 4621 4622 <p> 4623 Function calls on the left are evaluated once per iteration. 4624 For each iteration, iteration values are produced as follows: 4625 </p> 4626 4627 <pre class="grammar"> 4628 Range expression 1st value 2nd value (if 2nd variable is present) 4629 4630 array or slice a [n]E, *[n]E, or []E index i int a[i] E 4631 string s string type index i int see below rune 4632 map m map[K]V key k K m[k] V 4633 channel c chan E, <-chan E element e E 4634 </pre> 4635 4636 <ol> 4637 <li> 4638 For an array, pointer to array, or slice value <code>a</code>, the index iteration 4639 values are produced in increasing order, starting at element index 0. 4640 If only the first iteration variable is present, the range loop produces 4641 iteration values from 0 up to <code>len(a)-1</code> and does not index into the array 4642 or slice itself. For a <code>nil</code> slice, the number of iterations is 0. 4643 </li> 4644 4645 <li> 4646 For a string value, the "range" clause iterates over the Unicode code points 4647 in the string starting at byte index 0. On successive iterations, the index value will be the 4648 index of the first byte of successive UTF-8-encoded code points in the string, 4649 and the second value, of type <code>rune</code>, will be the value of 4650 the corresponding code point. If the iteration encounters an invalid 4651 UTF-8 sequence, the second value will be <code>0xFFFD</code>, 4652 the Unicode replacement character, and the next iteration will advance 4653 a single byte in the string. 4654 </li> 4655 4656 <li> 4657 The iteration order over maps is not specified 4658 and is not guaranteed to be the same from one iteration to the next. 4659 If map entries that have not yet been reached are removed during iteration, 4660 the corresponding iteration values will not be produced. If map entries are 4661 created during iteration, that entry may be produced during the iteration or 4662 may be skipped. The choice may vary for each entry created and from one 4663 iteration to the next. 4664 If the map is <code>nil</code>, the number of iterations is 0. 4665 </li> 4666 4667 <li> 4668 For channels, the iteration values produced are the successive values sent on 4669 the channel until the channel is <a href="#Close">closed</a>. If the channel 4670 is <code>nil</code>, the range expression blocks forever. 4671 </li> 4672 </ol> 4673 4674 <p> 4675 The iteration values are assigned to the respective 4676 iteration variables as in an <a href="#Assignments">assignment statement</a>. 4677 </p> 4678 4679 <p> 4680 The iteration variables may be declared by the "range" clause using a form of 4681 <a href="#Short_variable_declarations">short variable declaration</a> 4682 (<code>:=</code>). 4683 In this case their types are set to the types of the respective iteration values 4684 and their <a href="#Declarations_and_scope">scope</a> ends at the end of the "for" 4685 statement; they are re-used in each iteration. 4686 If the iteration variables are declared outside the "for" statement, 4687 after execution their values will be those of the last iteration. 4688 </p> 4689 4690 <pre> 4691 var testdata *struct { 4692 a *[7]int 4693 } 4694 for i, _ := range testdata.a { 4695 // testdata.a is never evaluated; len(testdata.a) is constant 4696 // i ranges from 0 to 6 4697 f(i) 4698 } 4699 4700 var a [10]string 4701 for i, s := range a { 4702 // type of i is int 4703 // type of s is string 4704 // s == a[i] 4705 g(i, s) 4706 } 4707 4708 var key string 4709 var val interface {} // value type of m is assignable to val 4710 m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6} 4711 for key, val = range m { 4712 h(key, val) 4713 } 4714 // key == last map key encountered in iteration 4715 // val == map[key] 4716 4717 var ch chan Work = producer() 4718 for w := range ch { 4719 doWork(w) 4720 } 4721 </pre> 4722 4723 4724 <h3 id="Go_statements">Go statements</h3> 4725 4726 <p> 4727 A "go" statement starts the execution of a function call 4728 as an independent concurrent thread of control, or <i>goroutine</i>, 4729 within the same address space. 4730 </p> 4731 4732 <pre class="ebnf"> 4733 GoStmt = "go" Expression . 4734 </pre> 4735 4736 <p> 4737 The expression must be a function or method call; it cannot be parenthesized. 4738 Calls of built-in functions are restricted as for 4739 <a href="#Expression_statements">expression statements</a>. 4740 </p> 4741 4742 <p> 4743 The function value and parameters are 4744 <a href="#Calls">evaluated as usual</a> 4745 in the calling goroutine, but 4746 unlike with a regular call, program execution does not wait 4747 for the invoked function to complete. 4748 Instead, the function begins executing independently 4749 in a new goroutine. 4750 When the function terminates, its goroutine also terminates. 4751 If the function has any return values, they are discarded when the 4752 function completes. 4753 </p> 4754 4755 <pre> 4756 go Server() 4757 go func(ch chan<- bool) { for { sleep(10); ch <- true; }} (c) 4758 </pre> 4759 4760 4761 <h3 id="Select_statements">Select statements</h3> 4762 4763 <p> 4764 A "select" statement chooses which of a set of possible communications 4765 will proceed. It looks similar to a "switch" statement but with the 4766 cases all referring to communication operations. 4767 </p> 4768 4769 <pre class="ebnf"> 4770 SelectStmt = "select" "{" { CommClause } "}" . 4771 CommClause = CommCase ":" StatementList . 4772 CommCase = "case" ( SendStmt | RecvStmt ) | "default" . 4773 RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr . 4774 RecvExpr = Expression . 4775 </pre> 4776 4777 <p> 4778 RecvExpr must be a <a href="#Receive_operator">receive operation</a>. 4779 For all the cases in the "select" 4780 statement, the channel expressions are evaluated in top-to-bottom order, along with 4781 any expressions that appear on the right hand side of send statements. 4782 A channel may be <code>nil</code>, 4783 which is equivalent to that case not 4784 being present in the select statement 4785 except, if a send, its expression is still evaluated. 4786 If any of the resulting operations can proceed, one of those is 4787 chosen and the corresponding communication and statements are 4788 evaluated. Otherwise, if there is a default case, that executes; 4789 if there is no default case, the statement blocks until one of the communications can 4790 complete. There can be at most one default case and it may appear anywhere in the 4791 "select" statement. 4792 If there are no cases with non-<code>nil</code> channels, 4793 the statement blocks forever. 4794 Even if the statement blocks, 4795 the channel and send expressions are evaluated only once, 4796 upon entering the select statement. 4797 </p> 4798 <p> 4799 Since all the channels and send expressions are evaluated, any side 4800 effects in that evaluation will occur for all the communications 4801 in the "select" statement. 4802 </p> 4803 <p> 4804 If multiple cases can proceed, a uniform pseudo-random choice is made to decide 4805 which single communication will execute. 4806 <p> 4807 The receive case may declare one or two new variables using a 4808 <a href="#Short_variable_declarations">short variable declaration</a>. 4809 </p> 4810 4811 <pre> 4812 var c, c1, c2, c3 chan int 4813 var i1, i2 int 4814 select { 4815 case i1 = <-c1: 4816 print("received ", i1, " from c1\n") 4817 case c2 <- i2: 4818 print("sent ", i2, " to c2\n") 4819 case i3, ok := (<-c3): // same as: i3, ok := <-c3 4820 if ok { 4821 print("received ", i3, " from c3\n") 4822 } else { 4823 print("c3 is closed\n") 4824 } 4825 default: 4826 print("no communication\n") 4827 } 4828 4829 for { // send random sequence of bits to c 4830 select { 4831 case c <- 0: // note: no statement, no fallthrough, no folding of cases 4832 case c <- 1: 4833 } 4834 } 4835 4836 select {} // block forever 4837 </pre> 4838 4839 4840 <h3 id="Return_statements">Return statements</h3> 4841 4842 <p> 4843 A "return" statement in a function <code>F</code> terminates the execution 4844 of <code>F</code>, and optionally provides one or more result values. 4845 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code> 4846 are executed before <code>F</code> returns to its caller. 4847 </p> 4848 4849 <pre class="ebnf"> 4850 ReturnStmt = "return" [ ExpressionList ] . 4851 </pre> 4852 4853 <p> 4854 In a function without a result type, a "return" statement must not 4855 specify any result values. 4856 </p> 4857 <pre> 4858 func noResult() { 4859 return 4860 } 4861 </pre> 4862 4863 <p> 4864 There are three ways to return values from a function with a result 4865 type: 4866 </p> 4867 4868 <ol> 4869 <li>The return value or values may be explicitly listed 4870 in the "return" statement. Each expression must be single-valued 4871 and <a href="#Assignability">assignable</a> 4872 to the corresponding element of the function's result type. 4873 <pre> 4874 func simpleF() int { 4875 return 2 4876 } 4877 4878 func complexF1() (re float64, im float64) { 4879 return -7.0, -4.0 4880 } 4881 </pre> 4882 </li> 4883 <li>The expression list in the "return" statement may be a single 4884 call to a multi-valued function. The effect is as if each value 4885 returned from that function were assigned to a temporary 4886 variable with the type of the respective value, followed by a 4887 "return" statement listing these variables, at which point the 4888 rules of the previous case apply. 4889 <pre> 4890 func complexF2() (re float64, im float64) { 4891 return complexF1() 4892 } 4893 </pre> 4894 </li> 4895 <li>The expression list may be empty if the function's result 4896 type specifies names for its <a href="#Function_types">result parameters</a>. 4897 The result parameters act as ordinary local variables 4898 and the function may assign values to them as necessary. 4899 The "return" statement returns the values of these variables. 4900 <pre> 4901 func complexF3() (re float64, im float64) { 4902 re = 7.0 4903 im = 4.0 4904 return 4905 } 4906 4907 func (devnull) Write(p []byte) (n int, _ error) { 4908 n = len(p) 4909 return 4910 } 4911 </pre> 4912 </li> 4913 </ol> 4914 4915 <p> 4916 Regardless of how they are declared, all the result values are initialized to 4917 the <a href="#The_zero_value">zero values</a> for their type upon entry to the 4918 function. A "return" statement that specifies results sets the result parameters before 4919 any deferred functions are executed. 4920 </p> 4921 4922 4923 <h3 id="Break_statements">Break statements</h3> 4924 4925 <p> 4926 A "break" statement terminates execution of the innermost 4927 <a href="#For_statements">"for"</a>, 4928 <a href="#Switch_statements">"switch"</a>, or 4929 <a href="#Select_statements">"select"</a> statement. 4930 </p> 4931 4932 <pre class="ebnf"> 4933 BreakStmt = "break" [ Label ] . 4934 </pre> 4935 4936 <p> 4937 If there is a label, it must be that of an enclosing 4938 "for", "switch", or "select" statement, 4939 and that is the one whose execution terminates. 4940 </p> 4941 4942 <pre> 4943 L: 4944 for i < n { 4945 switch i { 4946 case 5: 4947 break L 4948 } 4949 } 4950 </pre> 4951 4952 <h3 id="Continue_statements">Continue statements</h3> 4953 4954 <p> 4955 A "continue" statement begins the next iteration of the 4956 innermost <a href="#For_statements">"for" loop</a> at its post statement. 4957 </p> 4958 4959 <pre class="ebnf"> 4960 ContinueStmt = "continue" [ Label ] . 4961 </pre> 4962 4963 <p> 4964 If there is a label, it must be that of an enclosing 4965 "for" statement, and that is the one whose execution 4966 advances. 4967 </p> 4968 4969 <h3 id="Goto_statements">Goto statements</h3> 4970 4971 <p> 4972 A "goto" statement transfers control to the statement with the corresponding label. 4973 </p> 4974 4975 <pre class="ebnf"> 4976 GotoStmt = "goto" Label . 4977 </pre> 4978 4979 <pre> 4980 goto Error 4981 </pre> 4982 4983 <p> 4984 Executing the "goto" statement must not cause any variables to come into 4985 <a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto. 4986 For instance, this example: 4987 </p> 4988 4989 <pre> 4990 goto L // BAD 4991 v := 3 4992 L: 4993 </pre> 4994 4995 <p> 4996 is erroneous because the jump to label <code>L</code> skips 4997 the creation of <code>v</code>. 4998 </p> 4999 5000 <p> 5001 A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block. 5002 For instance, this example: 5003 </p> 5004 5005 <pre> 5006 if n%2 == 1 { 5007 goto L1 5008 } 5009 for n > 0 { 5010 f() 5011 n-- 5012 L1: 5013 f() 5014 n-- 5015 } 5016 </pre> 5017 5018 <p> 5019 is erroneous because the label <code>L1</code> is inside 5020 the "for" statement's block but the <code>goto</code> is not. 5021 </p> 5022 5023 <h3 id="Fallthrough_statements">Fallthrough statements</h3> 5024 5025 <p> 5026 A "fallthrough" statement transfers control to the first statement of the 5027 next case clause in a <a href="#Expression_switches">expression "switch" statement</a>. 5028 It may be used only as the final non-empty statement in such a clause. 5029 </p> 5030 5031 <pre class="ebnf"> 5032 FallthroughStmt = "fallthrough" . 5033 </pre> 5034 5035 5036 <h3 id="Defer_statements">Defer statements</h3> 5037 5038 <p> 5039 A "defer" statement invokes a function whose execution is deferred 5040 to the moment the surrounding function returns, either because the 5041 surrounding function executed a <a href="#Return_statements">return statement</a>, 5042 reached the end of its <a href="#Function_declarations">function body</a>, 5043 or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>. 5044 </p> 5045 5046 <pre class="ebnf"> 5047 DeferStmt = "defer" Expression . 5048 </pre> 5049 5050 <p> 5051 The expression must be a function or method call; it cannot be parenthesized. 5052 Calls of built-in functions are restricted as for 5053 <a href="#Expression_statements">expression statements</a>. 5054 </p> 5055 5056 <p> 5057 Each time the "defer" statement 5058 executes, the function value and parameters to the call are 5059 <a href="#Calls">evaluated as usual</a> 5060 and saved anew but the actual function body is not executed. 5061 Instead, deferred functions are executed immediately before 5062 the surrounding function returns, in the reverse order 5063 they were deferred. 5064 </p> 5065 5066 <p> 5067 For instance, if the deferred function is 5068 a <a href="#Function_literals">function literal</a> and the surrounding 5069 function has <a href="#Function_types">named result parameters</a> that 5070 are in scope within the literal, the deferred function may access and modify 5071 the result parameters before they are returned. 5072 If the deferred function has any return values, they are discarded when 5073 the function completes. 5074 (See also the section on <a href="#Handling_panics">handling panics</a>.) 5075 </p> 5076 5077 <pre> 5078 lock(l) 5079 defer unlock(l) // unlocking happens before surrounding function returns 5080 5081 // prints 3 2 1 0 before surrounding function returns 5082 for i := 0; i <= 3; i++ { 5083 defer fmt.Print(i) 5084 } 5085 5086 // f returns 1 5087 func f() (result int) { 5088 defer func() { 5089 result++ 5090 }() 5091 return 0 5092 } 5093 </pre> 5094 5095 <h2 id="Built-in_functions">Built-in functions</h2> 5096 5097 <p> 5098 Built-in functions are 5099 <a href="#Predeclared_identifiers">predeclared</a>. 5100 They are called like any other function but some of them 5101 accept a type instead of an expression as the first argument. 5102 </p> 5103 5104 <p> 5105 The built-in functions do not have standard Go types, 5106 so they can only appear in <a href="#Calls">call expressions</a>; 5107 they cannot be used as function values. 5108 </p> 5109 5110 <pre class="ebnf"> 5111 BuiltinCall = identifier "(" [ BuiltinArgs [ "," ] ] ")" . 5112 BuiltinArgs = Type [ "," ArgumentList ] | ArgumentList . 5113 </pre> 5114 5115 <h3 id="Close">Close</h3> 5116 5117 <p> 5118 For a channel <code>c</code>, the built-in function <code>close(c)</code> 5119 records that no more values will be sent on the channel. 5120 It is an error if <code>c</code> is a receive-only channel. 5121 Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>. 5122 Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>. 5123 After calling <code>close</code>, and after any previously 5124 sent values have been received, receive operations will return 5125 the zero value for the channel's type without blocking. 5126 The multi-valued <a href="#Receive_operator">receive operation</a> 5127 returns a received value along with an indication of whether the channel is closed. 5128 </p> 5129 5130 5131 <h3 id="Length_and_capacity">Length and capacity</h3> 5132 5133 <p> 5134 The built-in functions <code>len</code> and <code>cap</code> take arguments 5135 of various types and return a result of type <code>int</code>. 5136 The implementation guarantees that the result always fits into an <code>int</code>. 5137 </p> 5138 5139 <pre class="grammar"> 5140 Call Argument type Result 5141 5142 len(s) string type string length in bytes 5143 [n]T, *[n]T array length (== n) 5144 []T slice length 5145 map[K]T map length (number of defined keys) 5146 chan T number of elements queued in channel buffer 5147 5148 cap(s) [n]T, *[n]T array length (== n) 5149 []T slice capacity 5150 chan T channel buffer capacity 5151 </pre> 5152 5153 <p> 5154 The capacity of a slice is the number of elements for which there is 5155 space allocated in the underlying array. 5156 At any time the following relationship holds: 5157 </p> 5158 5159 <pre> 5160 0 <= len(s) <= cap(s) 5161 </pre> 5162 5163 <p> 5164 The length of a <code>nil</code> slice, map or channel is 0. 5165 The capacity of a <code>nil</code> slice and channel is 0. 5166 </p> 5167 5168 <p> 5169 The expression <code>len(s)</code> is <a href="#Constants">constant</a> if 5170 <code>s</code> is a string constant. The expressions <code>len(s)</code> and 5171 <code>cap(s)</code> are constants if the type of <code>s</code> is an array 5172 or pointer to an array and the expression <code>s</code> does not contain 5173 <a href="#Receive_operator">channel receives</a> or 5174 <a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated. 5175 Otherwise, invocations of <code>len</code> and <code>cap</code> are not 5176 constant and <code>s</code> is evaluated. 5177 </p> 5178 5179 5180 <h3 id="Allocation">Allocation</h3> 5181 5182 <p> 5183 The built-in function <code>new</code> takes a type <code>T</code> and 5184 returns a value of type <code>*T</code>. 5185 The memory is initialized as described in the section on 5186 <a href="#The_zero_value">initial values</a>. 5187 </p> 5188 5189 <pre class="grammar"> 5190 new(T) 5191 </pre> 5192 5193 <p> 5194 For instance 5195 </p> 5196 5197 <pre> 5198 type S struct { a int; b float64 } 5199 new(S) 5200 </pre> 5201 5202 <p> 5203 dynamically allocates memory for a variable of type <code>S</code>, 5204 initializes it (<code>a=0</code>, <code>b=0.0</code>), 5205 and returns a value of type <code>*S</code> containing the address 5206 of the memory. 5207 </p> 5208 5209 <h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3> 5210 5211 <p> 5212 The built-in function <code>make</code> takes a type <code>T</code>, 5213 which must be a slice, map or channel type, 5214 optionally followed by a type-specific list of expressions. 5215 It returns a value of type <code>T</code> (not <code>*T</code>). 5216 The memory is initialized as described in the section on 5217 <a href="#The_zero_value">initial values</a>. 5218 </p> 5219 5220 <pre class="grammar"> 5221 Call Type T Result 5222 5223 make(T, n) slice slice of type T with length n and capacity n 5224 make(T, n, m) slice slice of type T with length n and capacity m 5225 5226 make(T) map map of type T 5227 make(T, n) map map of type T with initial space for n elements 5228 5229 make(T) channel synchronous channel of type T 5230 make(T, n) channel asynchronous channel of type T, buffer size n 5231 </pre> 5232 5233 5234 <p> 5235 The size arguments <code>n</code> and <code>m</code> must be of integer type or untyped. 5236 A <a href="#Constants">constant</a> size argument must be non-negative and 5237 representable by a value of type <code>int</code>. 5238 If both <code>n</code> and <code>m</code> are provided and are constant, then 5239 <code>n</code> must be no larger than <code>m</code>. 5240 If <code>n</code> is negative or larger than <code>m</code> at run time, 5241 a <a href="#Run_time_panics">run-time panic</a> occurs. 5242 </p> 5243 5244 <pre> 5245 s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100 5246 s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000 5247 s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type int 5248 s := make([]int, 10, 0) // illegal: len(s) > cap(s) 5249 c := make(chan int, 10) // channel with a buffer size of 10 5250 m := make(map[string]int, 100) // map with initial space for 100 elements 5251 </pre> 5252 5253 5254 <h3 id="Appending_and_copying_slices">Appending to and copying slices</h3> 5255 5256 <p> 5257 The built-in functions <code>append</code> and <code>copy</code> assist in 5258 common slice operations. 5259 For both functions, the result is independent of whether the memory referenced 5260 by the arguments overlaps. 5261 </p> 5262 5263 <p> 5264 The <a href="#Function_types">variadic</a> function <code>append</code> 5265 appends zero or more values <code>x</code> 5266 to <code>s</code> of type <code>S</code>, which must be a slice type, and 5267 returns the resulting slice, also of type <code>S</code>. 5268 The values <code>x</code> are passed to a parameter of type <code>...T</code> 5269 where <code>T</code> is the <a href="#Slice_types">element type</a> of 5270 <code>S</code> and the respective 5271 <a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply. 5272 As a special case, <code>append</code> also accepts a first argument 5273 assignable to type <code>[]byte</code> with a second argument of 5274 string type followed by <code>...</code>. This form appends the 5275 bytes of the string. 5276 </p> 5277 5278 <pre class="grammar"> 5279 append(s S, x ...T) S // T is the element type of S 5280 </pre> 5281 5282 <p> 5283 If the capacity of <code>s</code> is not large enough to fit the additional 5284 values, <code>append</code> allocates a new, sufficiently large slice that fits 5285 both the existing slice elements and the additional values. Thus, the returned 5286 slice may refer to a different underlying array. 5287 </p> 5288 5289 <pre> 5290 s0 := []int{0, 0} 5291 s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2} 5292 s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7} 5293 s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0} 5294 s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0} 5295 5296 var t []interface{} 5297 t = append(t, 42, 3.1415, "foo") t == []interface{}{42, 3.1415, "foo"} 5298 5299 var b []byte 5300 b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' } 5301 </pre> 5302 5303 <p> 5304 The function <code>copy</code> copies slice elements from 5305 a source <code>src</code> to a destination <code>dst</code> and returns the 5306 number of elements copied. 5307 Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be 5308 <a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>. 5309 The number of elements copied is the minimum of 5310 <code>len(src)</code> and <code>len(dst)</code>. 5311 As a special case, <code>copy</code> also accepts a destination argument assignable 5312 to type <code>[]byte</code> with a source argument of a string type. 5313 This form copies the bytes from the string into the byte slice. 5314 </p> 5315 5316 <pre class="grammar"> 5317 copy(dst, src []T) int 5318 copy(dst []byte, src string) int 5319 </pre> 5320 5321 <p> 5322 Examples: 5323 </p> 5324 5325 <pre> 5326 var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7} 5327 var s = make([]int, 6) 5328 var b = make([]byte, 5) 5329 n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5} 5330 n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5} 5331 n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello") 5332 </pre> 5333 5334 5335 <h3 id="Deletion_of_map_elements">Deletion of map elements</h3> 5336 5337 <p> 5338 The built-in function <code>delete</code> removes the element with key 5339 <code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The 5340 type of <code>k</code> must be <a href="#Assignability">assignable</a> 5341 to the key type of <code>m</code>. 5342 </p> 5343 5344 <pre class="grammar"> 5345 delete(m, k) // remove element m[k] from map m 5346 </pre> 5347 5348 <p> 5349 If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code> 5350 does not exist, <code>delete</code> is a no-op. 5351 </p> 5352 5353 5354 <h3 id="Complex_numbers">Manipulating complex numbers</h3> 5355 5356 <p> 5357 Three functions assemble and disassemble complex numbers. 5358 The built-in function <code>complex</code> constructs a complex 5359 value from a floating-point real and imaginary part, while 5360 <code>real</code> and <code>imag</code> 5361 extract the real and imaginary parts of a complex value. 5362 </p> 5363 5364 <pre class="grammar"> 5365 complex(realPart, imaginaryPart floatT) complexT 5366 real(complexT) floatT 5367 imag(complexT) floatT 5368 </pre> 5369 5370 <p> 5371 The type of the arguments and return value correspond. 5372 For <code>complex</code>, the two arguments must be of the same 5373 floating-point type and the return type is the complex type 5374 with the corresponding floating-point constituents: 5375 <code>complex64</code> for <code>float32</code>, 5376 <code>complex128</code> for <code>float64</code>. 5377 The <code>real</code> and <code>imag</code> functions 5378 together form the inverse, so for a complex value <code>z</code>, 5379 <code>z</code> <code>==</code> <code>complex(real(z),</code> <code>imag(z))</code>. 5380 </p> 5381 5382 <p> 5383 If the operands of these functions are all constants, the return 5384 value is a constant. 5385 </p> 5386 5387 <pre> 5388 var a = complex(2, -2) // complex128 5389 var b = complex(1.0, -1.4) // complex128 5390 x := float32(math.Cos(math.Pi/2)) // float32 5391 var c64 = complex(5, -x) // complex64 5392 var im = imag(b) // float64 5393 var rl = real(c64) // float32 5394 </pre> 5395 5396 <h3 id="Handling_panics">Handling panics</h3> 5397 5398 <p> Two built-in functions, <code>panic</code> and <code>recover</code>, 5399 assist in reporting and handling <a href="#Run_time_panics">run-time panics</a> 5400 and program-defined error conditions. 5401 </p> 5402 5403 <pre class="grammar"> 5404 func panic(interface{}) 5405 func recover() interface{} 5406 </pre> 5407 5408 <p> 5409 While executing a function <code>F</code>, 5410 an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a> 5411 terminates the execution of <code>F</code>. 5412 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code> 5413 are then executed as usual. 5414 Next, any deferred functions run by <code>F's</code> caller are run, 5415 and so on up to any deferred by the top-level function in the executing goroutine. 5416 At that point, the program is terminated and the error 5417 condition is reported, including the value of the argument to <code>panic</code>. 5418 This termination sequence is called <i>panicking</i>. 5419 </p> 5420 5421 <pre> 5422 panic(42) 5423 panic("unreachable") 5424 panic(Error("cannot parse")) 5425 </pre> 5426 5427 <p> 5428 The <code>recover</code> function allows a program to manage behavior 5429 of a panicking goroutine. 5430 Suppose a function <code>G</code> defers a function <code>D</code> that calls 5431 <code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code> 5432 is executing. 5433 When the running of deferred functions reaches <code>D</code>, 5434 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>. 5435 If <code>D</code> returns normally, without starting a new 5436 <code>panic</code>, the panicking sequence stops. In that case, 5437 the state of functions called between <code>G</code> and the call to <code>panic</code> 5438 is discarded, and normal execution resumes. 5439 Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s 5440 execution terminates by returning to its caller. 5441 </p> 5442 5443 <p> 5444 The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds: 5445 </p> 5446 <ul> 5447 <li> 5448 <code>panic</code>'s argument was <code>nil</code>; 5449 </li> 5450 <li> 5451 the goroutine is not panicking; 5452 </li> 5453 <li> 5454 <code>recover</code> was not called directly by a deferred function. 5455 </li> 5456 </ul> 5457 5458 <p> 5459 The <code>protect</code> function in the example below invokes 5460 the function argument <code>g</code> and protects callers from 5461 run-time panics raised by <code>g</code>. 5462 </p> 5463 5464 <pre> 5465 func protect(g func()) { 5466 defer func() { 5467 log.Println("done") // Println executes normally even if there is a panic 5468 if x := recover(); x != nil { 5469 log.Printf("run time panic: %v", x) 5470 } 5471 }() 5472 log.Println("start") 5473 g() 5474 } 5475 </pre> 5476 5477 5478 <h3 id="Bootstrapping">Bootstrapping</h3> 5479 5480 <p> 5481 Current implementations provide several built-in functions useful during 5482 bootstrapping. These functions are documented for completeness but are not 5483 guaranteed to stay in the language. They do not return a result. 5484 </p> 5485 5486 <pre class="grammar"> 5487 Function Behavior 5488 5489 print prints all arguments; formatting of arguments is implementation-specific 5490 println like print but prints spaces between arguments and a newline at the end 5491 </pre> 5492 5493 5494 <h2 id="Packages">Packages</h2> 5495 5496 <p> 5497 Go programs are constructed by linking together <i>packages</i>. 5498 A package in turn is constructed from one or more source files 5499 that together declare constants, types, variables and functions 5500 belonging to the package and which are accessible in all files 5501 of the same package. Those elements may be 5502 <a href="#Exported_identifiers">exported</a> and used in another package. 5503 </p> 5504 5505 <h3 id="Source_file_organization">Source file organization</h3> 5506 5507 <p> 5508 Each source file consists of a package clause defining the package 5509 to which it belongs, followed by a possibly empty set of import 5510 declarations that declare packages whose contents it wishes to use, 5511 followed by a possibly empty set of declarations of functions, 5512 types, variables, and constants. 5513 </p> 5514 5515 <pre class="ebnf"> 5516 SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } . 5517 </pre> 5518 5519 <h3 id="Package_clause">Package clause</h3> 5520 5521 <p> 5522 A package clause begins each source file and defines the package 5523 to which the file belongs. 5524 </p> 5525 5526 <pre class="ebnf"> 5527 PackageClause = "package" PackageName . 5528 PackageName = identifier . 5529 </pre> 5530 5531 <p> 5532 The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>. 5533 </p> 5534 5535 <pre> 5536 package math 5537 </pre> 5538 5539 <p> 5540 A set of files sharing the same PackageName form the implementation of a package. 5541 An implementation may require that all source files for a package inhabit the same directory. 5542 </p> 5543 5544 <h3 id="Import_declarations">Import declarations</h3> 5545 5546 <p> 5547 An import declaration states that the source file containing the declaration 5548 depends on functionality of the <i>imported</i> package 5549 (<a href="#Program_initialization_and_execution">§Program initialization and execution</a>) 5550 and enables access to <a href="#Exported_identifiers">exported</a> identifiers 5551 of that package. 5552 The import names an identifier (PackageName) to be used for access and an ImportPath 5553 that specifies the package to be imported. 5554 </p> 5555 5556 <pre class="ebnf"> 5557 ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) . 5558 ImportSpec = [ "." | PackageName ] ImportPath . 5559 ImportPath = string_lit . 5560 </pre> 5561 5562 <p> 5563 The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a> 5564 to access exported identifiers of the package within the importing source file. 5565 It is declared in the <a href="#Blocks">file block</a>. 5566 If the PackageName is omitted, it defaults to the identifier specified in the 5567 <a href="#Package_clause">package clause</a> of the imported package. 5568 If an explicit period (<code>.</code>) appears instead of a name, all the 5569 package's exported identifiers declared in that package's 5570 <a href="#Blocks">package block</a> will be declared in the importing source 5571 file's file block and can be accessed without a qualifier. 5572 </p> 5573 5574 <p> 5575 The interpretation of the ImportPath is implementation-dependent but 5576 it is typically a substring of the full file name of the compiled 5577 package and may be relative to a repository of installed packages. 5578 </p> 5579 5580 <p> 5581 Implementation restriction: A compiler may restrict ImportPaths to 5582 non-empty strings using only characters belonging to 5583 <a href="http://www.unicode.org/versions/Unicode6.2.0/">Unicode's</a> 5584 L, M, N, P, and S general categories (the Graphic characters without 5585 spaces) and may also exclude the characters 5586 <code>!"#$%&'()*,:;<=>?[\]^`{|}</code> 5587 and the Unicode replacement character U+FFFD. 5588 </p> 5589 5590 <p> 5591 Assume we have compiled a package containing the package clause 5592 <code>package math</code>, which exports function <code>Sin</code>, and 5593 installed the compiled package in the file identified by 5594 <code>"lib/math"</code>. 5595 This table illustrates how <code>Sin</code> may be accessed in files 5596 that import the package after the 5597 various types of import declaration. 5598 </p> 5599 5600 <pre class="grammar"> 5601 Import declaration Local name of Sin 5602 5603 import "lib/math" math.Sin 5604 import m "lib/math" m.Sin 5605 import . "lib/math" Sin 5606 </pre> 5607 5608 <p> 5609 An import declaration declares a dependency relation between 5610 the importing and imported package. 5611 It is illegal for a package to import itself, directly or indirectly, 5612 or to directly import a package without 5613 referring to any of its exported identifiers. To import a package solely for 5614 its side-effects (initialization), use the <a href="#Blank_identifier">blank</a> 5615 identifier as explicit package name: 5616 </p> 5617 5618 <pre> 5619 import _ "lib/math" 5620 </pre> 5621 5622 5623 <h3 id="An_example_package">An example package</h3> 5624 5625 <p> 5626 Here is a complete Go package that implements a concurrent prime sieve. 5627 </p> 5628 5629 <pre> 5630 package main 5631 5632 import "fmt" 5633 5634 // Send the sequence 2, 3, 4, … to channel 'ch'. 5635 func generate(ch chan<- int) { 5636 for i := 2; ; i++ { 5637 ch <- i // Send 'i' to channel 'ch'. 5638 } 5639 } 5640 5641 // Copy the values from channel 'src' to channel 'dst', 5642 // removing those divisible by 'prime'. 5643 func filter(src <-chan int, dst chan<- int, prime int) { 5644 for i := range src { // Loop over values received from 'src'. 5645 if i%prime != 0 { 5646 dst <- i // Send 'i' to channel 'dst'. 5647 } 5648 } 5649 } 5650 5651 // The prime sieve: Daisy-chain filter processes together. 5652 func sieve() { 5653 ch := make(chan int) // Create a new channel. 5654 go generate(ch) // Start generate() as a subprocess. 5655 for { 5656 prime := <-ch 5657 fmt.Print(prime, "\n") 5658 ch1 := make(chan int) 5659 go filter(ch, ch1, prime) 5660 ch = ch1 5661 } 5662 } 5663 5664 func main() { 5665 sieve() 5666 } 5667 </pre> 5668 5669 <h2 id="Program_initialization_and_execution">Program initialization and execution</h2> 5670 5671 <h3 id="The_zero_value">The zero value</h3> 5672 <p> 5673 When memory is allocated to store a value, either through a declaration 5674 or a call of <code>make</code> or <code>new</code>, 5675 and no explicit initialization is provided, the memory is 5676 given a default initialization. Each element of such a value is 5677 set to the <i>zero value</i> for its type: <code>false</code> for booleans, 5678 <code>0</code> for integers, <code>0.0</code> for floats, <code>""</code> 5679 for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps. 5680 This initialization is done recursively, so for instance each element of an 5681 array of structs will have its fields zeroed if no value is specified. 5682 </p> 5683 <p> 5684 These two simple declarations are equivalent: 5685 </p> 5686 5687 <pre> 5688 var i int 5689 var i int = 0 5690 </pre> 5691 5692 <p> 5693 After 5694 </p> 5695 5696 <pre> 5697 type T struct { i int; f float64; next *T } 5698 t := new(T) 5699 </pre> 5700 5701 <p> 5702 the following holds: 5703 </p> 5704 5705 <pre> 5706 t.i == 0 5707 t.f == 0.0 5708 t.next == nil 5709 </pre> 5710 5711 <p> 5712 The same would also be true after 5713 </p> 5714 5715 <pre> 5716 var t T 5717 </pre> 5718 5719 <h3 id="Program_execution">Program execution</h3> 5720 <p> 5721 A package with no imports is initialized by assigning initial values to 5722 all its package-level variables 5723 and then calling any 5724 package-level function with the name and signature of 5725 </p> 5726 <pre> 5727 func init() 5728 </pre> 5729 <p> 5730 defined in its source. 5731 A package-scope or file-scope identifier 5732 with name <code>init</code> may only be 5733 declared to be a function with this signature. 5734 Multiple such functions may be defined, even 5735 within a single source file; they execute 5736 in unspecified order. 5737 </p> 5738 <p> 5739 Within a package, package-level variables are initialized, 5740 and constant values are determined, according to 5741 order of reference: if the initializer of <code>A</code> 5742 depends on <code>B</code>, <code>A</code> 5743 will be set after <code>B</code>. 5744 Dependency analysis does not depend on the actual values 5745 of the items being initialized, only on their appearance 5746 in the source. 5747 <code>A</code> 5748 depends on <code>B</code> if the value of <code>A</code> 5749 contains a mention of <code>B</code>, contains a value 5750 whose initializer 5751 mentions <code>B</code>, or mentions a function that 5752 mentions <code>B</code>, recursively. 5753 It is an error if such dependencies form a cycle. 5754 If two items are not interdependent, they will be initialized 5755 in the order they appear in the source, possibly in multiple files, 5756 as presented to the compiler. 5757 Since the dependency analysis is done per package, it can produce 5758 unspecified results if <code>A</code>'s initializer calls a function defined 5759 in another package that refers to <code>B</code>. 5760 </p> 5761 <p> 5762 An <code>init</code> function cannot be referred to from anywhere 5763 in a program. In particular, <code>init</code> cannot be called explicitly, 5764 nor can a pointer to <code>init</code> be assigned to a function variable. 5765 </p> 5766 <p> 5767 If a package has imports, the imported packages are initialized 5768 before initializing the package itself. If multiple packages import 5769 a package <code>P</code>, <code>P</code> will be initialized only once. 5770 </p> 5771 <p> 5772 The importing of packages, by construction, guarantees that there can 5773 be no cyclic dependencies in initialization. 5774 </p> 5775 <p> 5776 A complete program is created by linking a single, unimported package 5777 called the <i>main package</i> with all the packages it imports, transitively. 5778 The main package must 5779 have package name <code>main</code> and 5780 declare a function <code>main</code> that takes no 5781 arguments and returns no value. 5782 </p> 5783 5784 <pre> 5785 func main() { … } 5786 </pre> 5787 5788 <p> 5789 Program execution begins by initializing the main package and then 5790 invoking the function <code>main</code>. 5791 When the function <code>main</code> returns, the program exits. 5792 It does not wait for other (non-<code>main</code>) goroutines to complete. 5793 </p> 5794 5795 <p> 5796 Package initialization—variable initialization and the invocation of 5797 <code>init</code> functions—happens in a single goroutine, 5798 sequentially, one package at a time. 5799 An <code>init</code> function may launch other goroutines, which can run 5800 concurrently with the initialization code. However, initialization 5801 always sequences 5802 the <code>init</code> functions: it will not start the next 5803 <code>init</code> until 5804 the previous one has returned. 5805 </p> 5806 5807 <h2 id="Errors">Errors</h2> 5808 5809 <p> 5810 The predeclared type <code>error</code> is defined as 5811 </p> 5812 5813 <pre> 5814 type error interface { 5815 Error() string 5816 } 5817 </pre> 5818 5819 <p> 5820 It is the conventional interface for representing an error condition, 5821 with the nil value representing no error. 5822 For instance, a function to read data from a file might be defined: 5823 </p> 5824 5825 <pre> 5826 func Read(f *File, b []byte) (n int, err error) 5827 </pre> 5828 5829 <h2 id="Run_time_panics">Run-time panics</h2> 5830 5831 <p> 5832 Execution errors such as attempting to index an array out 5833 of bounds trigger a <i>run-time panic</i> equivalent to a call of 5834 the built-in function <a href="#Handling_panics"><code>panic</code></a> 5835 with a value of the implementation-defined interface type <code>runtime.Error</code>. 5836 That type satisfies the predeclared interface type 5837 <a href="#Errors"><code>error</code></a>. 5838 The exact error values that 5839 represent distinct run-time error conditions are unspecified. 5840 </p> 5841 5842 <pre> 5843 package runtime 5844 5845 type Error interface { 5846 error 5847 // and perhaps other methods 5848 } 5849 </pre> 5850 5851 <h2 id="System_considerations">System considerations</h2> 5852 5853 <h3 id="Package_unsafe">Package <code>unsafe</code></h3> 5854 5855 <p> 5856 The built-in package <code>unsafe</code>, known to the compiler, 5857 provides facilities for low-level programming including operations 5858 that violate the type system. A package using <code>unsafe</code> 5859 must be vetted manually for type safety. The package provides the 5860 following interface: 5861 </p> 5862 5863 <pre class="grammar"> 5864 package unsafe 5865 5866 type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type 5867 type Pointer *ArbitraryType 5868 5869 func Alignof(variable ArbitraryType) uintptr 5870 func Offsetof(selector ArbitraryType) uintptr 5871 func Sizeof(variable ArbitraryType) uintptr 5872 </pre> 5873 5874 <p> 5875 Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to 5876 a <code>Pointer</code> type and vice versa. 5877 </p> 5878 5879 <pre> 5880 var f float64 5881 bits = *(*uint64)(unsafe.Pointer(&f)) 5882 5883 type ptr unsafe.Pointer 5884 bits = *(*uint64)(ptr(&f)) 5885 </pre> 5886 5887 <p> 5888 The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code> 5889 of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code> 5890 as if <code>v</code> was declared via <code>var v = x</code>. 5891 </p> 5892 <p> 5893 The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a> 5894 <code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code> 5895 or <code>*s</code>, and returns the field offset in bytes relative to the struct's address. 5896 If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable 5897 without pointer indirections through fields of the struct. 5898 For a struct <code>s</code> with field <code>f</code>: 5899 </p> 5900 5901 <pre> 5902 uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&s.f)) 5903 </pre> 5904 5905 <p> 5906 Computer architectures may require memory addresses to be <i>aligned</i>; 5907 that is, for addresses of a variable to be a multiple of a factor, 5908 the variable's type's <i>alignment</i>. The function <code>Alignof</code> 5909 takes an expression denoting a variable of any type and returns the 5910 alignment of the (type of the) variable in bytes. For a variable 5911 <code>x</code>: 5912 </p> 5913 5914 <pre> 5915 uintptr(unsafe.Pointer(&x)) % unsafe.Alignof(x) == 0 5916 </pre> 5917 5918 <p> 5919 Calls to <code>Alignof</code>, <code>Offsetof</code>, and 5920 <code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>. 5921 </p> 5922 5923 <h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3> 5924 5925 <p> 5926 For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed: 5927 </p> 5928 5929 <pre class="grammar"> 5930 type size in bytes 5931 5932 byte, uint8, int8 1 5933 uint16, int16 2 5934 uint32, int32, float32 4 5935 uint64, int64, float64, complex64 8 5936 complex128 16 5937 </pre> 5938 5939 <p> 5940 The following minimal alignment properties are guaranteed: 5941 </p> 5942 <ol> 5943 <li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1. 5944 </li> 5945 5946 <li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of 5947 all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1. 5948 </li> 5949 5950 <li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as 5951 <code>unsafe.Alignof(x[0])</code>, but at least 1. 5952 </li> 5953 </ol> 5954 5955 <p> 5956 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. 5957 </p>