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