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