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