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