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