1 <!--{ 2 "Title": "The Go Programming Language Specification", 3 "Subtitle": "Version of November 18, 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 <pre class="ebnf"> 1730 ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) . 1731 ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] . 1732 1733 IdentifierList = identifier { "," identifier } . 1734 ExpressionList = Expression { "," Expression } . 1735 </pre> 1736 1737 <p> 1738 If the type is present, all constants take the type specified, and 1739 the expressions must be <a href="#Assignability">assignable</a> to that type. 1740 If the type is omitted, the constants take the 1741 individual types of the corresponding expressions. 1742 If the expression values are untyped <a href="#Constants">constants</a>, 1743 the declared constants remain untyped and the constant identifiers 1744 denote the constant values. For instance, if the expression is a 1745 floating-point literal, the constant identifier denotes a floating-point 1746 constant, even if the literal's fractional part is zero. 1747 </p> 1748 1749 <pre> 1750 const Pi float64 = 3.14159265358979323846 1751 const zero = 0.0 // untyped floating-point constant 1752 const ( 1753 size int64 = 1024 1754 eof = -1 // untyped integer constant 1755 ) 1756 const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants 1757 const u, v float32 = 0, 3 // u = 0.0, v = 3.0 1758 </pre> 1759 1760 <p> 1761 Within a parenthesized <code>const</code> declaration list the 1762 expression list may be omitted from any but the first declaration. 1763 Such an empty list is equivalent to the textual substitution of the 1764 first preceding non-empty expression list and its type if any. 1765 Omitting the list of expressions is therefore equivalent to 1766 repeating the previous list. The number of identifiers must be equal 1767 to the number of expressions in the previous list. 1768 Together with the <a href="#Iota"><code>iota</code> constant generator</a> 1769 this mechanism permits light-weight declaration of sequential values: 1770 </p> 1771 1772 <pre> 1773 const ( 1774 Sunday = iota 1775 Monday 1776 Tuesday 1777 Wednesday 1778 Thursday 1779 Friday 1780 Partyday 1781 numberOfDays // this constant is not exported 1782 ) 1783 </pre> 1784 1785 1786 <h3 id="Iota">Iota</h3> 1787 1788 <p> 1789 Within a <a href="#Constant_declarations">constant declaration</a>, the predeclared identifier 1790 <code>iota</code> represents successive untyped integer <a href="#Constants"> 1791 constants</a>. It is reset to 0 whenever the reserved word <code>const</code> 1792 appears in the source and increments after each <a href="#ConstSpec">ConstSpec</a>. 1793 It can be used to construct a set of related constants: 1794 </p> 1795 1796 <pre> 1797 const ( // iota is reset to 0 1798 c0 = iota // c0 == 0 1799 c1 = iota // c1 == 1 1800 c2 = iota // c2 == 2 1801 ) 1802 1803 const ( // iota is reset to 0 1804 a = 1 << iota // a == 1 1805 b = 1 << iota // b == 2 1806 c = 3 // c == 3 (iota is not used but still incremented) 1807 d = 1 << iota // d == 8 1808 ) 1809 1810 const ( // iota is reset to 0 1811 u = iota * 42 // u == 0 (untyped integer constant) 1812 v float64 = iota * 42 // v == 42.0 (float64 constant) 1813 w = iota * 42 // w == 84 (untyped integer constant) 1814 ) 1815 1816 const x = iota // x == 0 (iota has been reset) 1817 const y = iota // y == 0 (iota has been reset) 1818 </pre> 1819 1820 <p> 1821 Within an ExpressionList, the value of each <code>iota</code> is the same because 1822 it is only incremented after each ConstSpec: 1823 </p> 1824 1825 <pre> 1826 const ( 1827 bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 1828 bit1, mask1 // bit1 == 2, mask1 == 1 1829 _, _ // skips iota == 2 1830 bit3, mask3 // bit3 == 8, mask3 == 7 1831 ) 1832 </pre> 1833 1834 <p> 1835 This last example exploits the implicit repetition of the 1836 last non-empty expression list. 1837 </p> 1838 1839 1840 <h3 id="Type_declarations">Type declarations</h3> 1841 1842 <p> 1843 A type declaration binds an identifier, the <i>type name</i>, to a new type 1844 that has the same <a href="#Types">underlying type</a> as an existing type, 1845 and operations defined for the existing type are also defined for the new type. 1846 The new type is <a href="#Type_identity">different</a> from the existing type. 1847 </p> 1848 1849 <pre class="ebnf"> 1850 TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) . 1851 TypeSpec = identifier Type . 1852 </pre> 1853 1854 <pre> 1855 type IntArray [16]int 1856 1857 type ( 1858 Point struct{ x, y float64 } 1859 Polar Point 1860 ) 1861 1862 type TreeNode struct { 1863 left, right *TreeNode 1864 value *Comparable 1865 } 1866 1867 type Block interface { 1868 BlockSize() int 1869 Encrypt(src, dst []byte) 1870 Decrypt(src, dst []byte) 1871 } 1872 </pre> 1873 1874 <p> 1875 The declared type does not inherit any <a href="#Method_declarations">methods</a> 1876 bound to the existing type, but the <a href="#Method_sets">method set</a> 1877 of an interface type or of elements of a composite type remains unchanged: 1878 </p> 1879 1880 <pre> 1881 // A Mutex is a data type with two methods, Lock and Unlock. 1882 type Mutex struct { /* Mutex fields */ } 1883 func (m *Mutex) Lock() { /* Lock implementation */ } 1884 func (m *Mutex) Unlock() { /* Unlock implementation */ } 1885 1886 // NewMutex has the same composition as Mutex but its method set is empty. 1887 type NewMutex Mutex 1888 1889 // The method set of the <a href="#Pointer_types">base type</a> of PtrMutex remains unchanged, 1890 // but the method set of PtrMutex is empty. 1891 type PtrMutex *Mutex 1892 1893 // The method set of *PrintableMutex contains the methods 1894 // Lock and Unlock bound to its anonymous field Mutex. 1895 type PrintableMutex struct { 1896 Mutex 1897 } 1898 1899 // MyBlock is an interface type that has the same method set as Block. 1900 type MyBlock Block 1901 </pre> 1902 1903 <p> 1904 A type declaration may be used to define a different boolean, numeric, or string 1905 type and attach methods to it: 1906 </p> 1907 1908 <pre> 1909 type TimeZone int 1910 1911 const ( 1912 EST TimeZone = -(5 + iota) 1913 CST 1914 MST 1915 PST 1916 ) 1917 1918 func (tz TimeZone) String() string { 1919 return fmt.Sprintf("GMT%+dh", tz) 1920 } 1921 </pre> 1922 1923 1924 <h3 id="Variable_declarations">Variable declarations</h3> 1925 1926 <p> 1927 A variable declaration creates one or more variables, binds corresponding 1928 identifiers to them, and gives each a type and an initial value. 1929 </p> 1930 1931 <pre class="ebnf"> 1932 VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) . 1933 VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) . 1934 </pre> 1935 1936 <pre> 1937 var i int 1938 var U, V, W float64 1939 var k = 0 1940 var x, y float32 = -1, -2 1941 var ( 1942 i int 1943 u, v, s = 2.0, 3.0, "bar" 1944 ) 1945 var re, im = complexSqrt(-1) 1946 var _, found = entries[name] // map lookup; only interested in "found" 1947 </pre> 1948 1949 <p> 1950 If a list of expressions is given, the variables are initialized 1951 with the expressions following the rules for <a href="#Assignments">assignments</a>. 1952 Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>. 1953 </p> 1954 1955 <p> 1956 If a type is present, each variable is given that type. 1957 Otherwise, each variable is given the type of the corresponding 1958 initialization value in the assignment. 1959 If that value is an untyped constant, it is first 1960 <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>; 1961 if it is an untyped boolean value, it is first converted to type <code>bool</code>. 1962 The predeclared value <code>nil</code> cannot be used to initialize a variable 1963 with no explicit type. 1964 </p> 1965 1966 <pre> 1967 var d = math.Sin(0.5) // d is float64 1968 var i = 42 // i is int 1969 var t, ok = x.(T) // t is T, ok is bool 1970 var n = nil // illegal 1971 </pre> 1972 1973 <p> 1974 Implementation restriction: A compiler may make it illegal to declare a variable 1975 inside a <a href="#Function_declarations">function body</a> if the variable is 1976 never used. 1977 </p> 1978 1979 <h3 id="Short_variable_declarations">Short variable declarations</h3> 1980 1981 <p> 1982 A <i>short variable declaration</i> uses the syntax: 1983 </p> 1984 1985 <pre class="ebnf"> 1986 ShortVarDecl = IdentifierList ":=" ExpressionList . 1987 </pre> 1988 1989 <p> 1990 It is shorthand for a regular <a href="#Variable_declarations">variable declaration</a> 1991 with initializer expressions but no types: 1992 </p> 1993 1994 <pre class="grammar"> 1995 "var" IdentifierList = ExpressionList . 1996 </pre> 1997 1998 <pre> 1999 i, j := 0, 10 2000 f := func() int { return 7 } 2001 ch := make(chan int) 2002 r, w := os.Pipe(fd) // os.Pipe() returns two values 2003 _, y, _ := coord(p) // coord() returns three values; only interested in y coordinate 2004 </pre> 2005 2006 <p> 2007 Unlike regular variable declarations, a short variable declaration may <i>redeclare</i> 2008 variables provided they were originally declared earlier in the same block 2009 (or the parameter lists if the block is the function body) with the same type, 2010 and at least one of the non-<a href="#Blank_identifier">blank</a> variables is new. 2011 As a consequence, redeclaration can only appear in a multi-variable short declaration. 2012 Redeclaration does not introduce a new variable; it just assigns a new value to the original. 2013 </p> 2014 2015 <pre> 2016 field1, offset := nextField(str, 0) 2017 field2, offset := nextField(str, offset) // redeclares offset 2018 a, a := 1, 2 // illegal: double declaration of a or no new variable if a was declared elsewhere 2019 </pre> 2020 2021 <p> 2022 Short variable declarations may appear only inside functions. 2023 In some contexts such as the initializers for 2024 <a href="#If_statements">"if"</a>, 2025 <a href="#For_statements">"for"</a>, or 2026 <a href="#Switch_statements">"switch"</a> statements, 2027 they can be used to declare local temporary variables. 2028 </p> 2029 2030 <h3 id="Function_declarations">Function declarations</h3> 2031 2032 <p> 2033 A function declaration binds an identifier, the <i>function name</i>, 2034 to a function. 2035 </p> 2036 2037 <pre class="ebnf"> 2038 FunctionDecl = "func" FunctionName ( Function | Signature ) . 2039 FunctionName = identifier . 2040 Function = Signature FunctionBody . 2041 FunctionBody = Block . 2042 </pre> 2043 2044 <p> 2045 If the function's <a href="#Function_types">signature</a> declares 2046 result parameters, the function body's statement list must end in 2047 a <a href="#Terminating_statements">terminating statement</a>. 2048 </p> 2049 2050 <pre> 2051 func IndexRune(s string, r rune) int { 2052 for i, c := range s { 2053 if c == r { 2054 return i 2055 } 2056 } 2057 // invalid: missing return statement 2058 } 2059 </pre> 2060 2061 <p> 2062 A function declaration may omit the body. Such a declaration provides the 2063 signature for a function implemented outside Go, such as an assembly routine. 2064 </p> 2065 2066 <pre> 2067 func min(x int, y int) int { 2068 if x < y { 2069 return x 2070 } 2071 return y 2072 } 2073 2074 func flushICache(begin, end uintptr) // implemented externally 2075 </pre> 2076 2077 <h3 id="Method_declarations">Method declarations</h3> 2078 2079 <p> 2080 A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>. 2081 A method declaration binds an identifier, the <i>method name</i>, to a method, 2082 and associates the method with the receiver's <i>base type</i>. 2083 </p> 2084 2085 <pre class="ebnf"> 2086 MethodDecl = "func" Receiver MethodName ( Function | Signature ) . 2087 Receiver = Parameters . 2088 </pre> 2089 2090 <p> 2091 The receiver is specified via an extra parameter section preceding the method 2092 name. That parameter section must declare a single non-variadic parameter, the receiver. 2093 Its type must be of the form <code>T</code> or <code>*T</code> (possibly using 2094 parentheses) where <code>T</code> is a type name. The type denoted by <code>T</code> is called 2095 the receiver <i>base type</i>; it must not be a pointer or interface type and 2096 it must be declared in the same package as the method. 2097 The method is said to be <i>bound</i> to the base type and the method name 2098 is visible only within <a href="#Selectors">selectors</a> for type <code>T</code> 2099 or <code>*T</code>. 2100 </p> 2101 2102 <p> 2103 A non-<a href="#Blank_identifier">blank</a> receiver identifier must be 2104 <a href="#Uniqueness_of_identifiers">unique</a> in the method signature. 2105 If the receiver's value is not referenced inside the body of the method, 2106 its identifier may be omitted in the declaration. The same applies in 2107 general to parameters of functions and methods. 2108 </p> 2109 2110 <p> 2111 For a base type, the non-blank names of methods bound to it must be unique. 2112 If the base type is a <a href="#Struct_types">struct type</a>, 2113 the non-blank method and field names must be distinct. 2114 </p> 2115 2116 <p> 2117 Given type <code>Point</code>, the declarations 2118 </p> 2119 2120 <pre> 2121 func (p *Point) Length() float64 { 2122 return math.Sqrt(p.x * p.x + p.y * p.y) 2123 } 2124 2125 func (p *Point) Scale(factor float64) { 2126 p.x *= factor 2127 p.y *= factor 2128 } 2129 </pre> 2130 2131 <p> 2132 bind the methods <code>Length</code> and <code>Scale</code>, 2133 with receiver type <code>*Point</code>, 2134 to the base type <code>Point</code>. 2135 </p> 2136 2137 <p> 2138 The type of a method is the type of a function with the receiver as first 2139 argument. For instance, the method <code>Scale</code> has type 2140 </p> 2141 2142 <pre> 2143 func(p *Point, factor float64) 2144 </pre> 2145 2146 <p> 2147 However, a function declared this way is not a method. 2148 </p> 2149 2150 2151 <h2 id="Expressions">Expressions</h2> 2152 2153 <p> 2154 An expression specifies the computation of a value by applying 2155 operators and functions to operands. 2156 </p> 2157 2158 <h3 id="Operands">Operands</h3> 2159 2160 <p> 2161 Operands denote the elementary values in an expression. An operand may be a 2162 literal, a (possibly <a href="#Qualified_identifiers">qualified</a>) 2163 non-<a href="#Blank_identifier">blank</a> identifier denoting a 2164 <a href="#Constant_declarations">constant</a>, 2165 <a href="#Variable_declarations">variable</a>, or 2166 <a href="#Function_declarations">function</a>, 2167 a <a href="#Method_expressions">method expression</a> yielding a function, 2168 or a parenthesized expression. 2169 </p> 2170 2171 <p> 2172 The <a href="#Blank_identifier">blank identifier</a> may appear as an 2173 operand only on the left-hand side of an <a href="#Assignments">assignment</a>. 2174 </p> 2175 2176 <pre class="ebnf"> 2177 Operand = Literal | OperandName | MethodExpr | "(" Expression ")" . 2178 Literal = BasicLit | CompositeLit | FunctionLit . 2179 BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit . 2180 OperandName = identifier | QualifiedIdent. 2181 </pre> 2182 2183 <h3 id="Qualified_identifiers">Qualified identifiers</h3> 2184 2185 <p> 2186 A qualified identifier is an identifier qualified with a package name prefix. 2187 Both the package name and the identifier must not be 2188 <a href="#Blank_identifier">blank</a>. 2189 </p> 2190 2191 <pre class="ebnf"> 2192 QualifiedIdent = PackageName "." identifier . 2193 </pre> 2194 2195 <p> 2196 A qualified identifier accesses an identifier in a different package, which 2197 must be <a href="#Import_declarations">imported</a>. 2198 The identifier must be <a href="#Exported_identifiers">exported</a> and 2199 declared in the <a href="#Blocks">package block</a> of that package. 2200 </p> 2201 2202 <pre> 2203 math.Sin // denotes the Sin function in package math 2204 </pre> 2205 2206 <h3 id="Composite_literals">Composite literals</h3> 2207 2208 <p> 2209 Composite literals construct values for structs, arrays, slices, and maps 2210 and create a new value each time they are evaluated. 2211 They consist of the type of the literal followed by a brace-bound list of elements. 2212 Each element may optionally be preceded by a corresponding key. 2213 </p> 2214 2215 <pre class="ebnf"> 2216 CompositeLit = LiteralType LiteralValue . 2217 LiteralType = StructType | ArrayType | "[" "..." "]" ElementType | 2218 SliceType | MapType | TypeName . 2219 LiteralValue = "{" [ ElementList [ "," ] ] "}" . 2220 ElementList = KeyedElement { "," KeyedElement } . 2221 KeyedElement = [ Key ":" ] Element . 2222 Key = FieldName | Expression | LiteralValue . 2223 FieldName = identifier . 2224 Element = Expression | LiteralValue . 2225 </pre> 2226 2227 <p> 2228 The LiteralType's underlying type must be a struct, array, slice, or map type 2229 (the grammar enforces this constraint except when the type is given 2230 as a TypeName). 2231 The types of the elements and keys must be <a href="#Assignability">assignable</a> 2232 to the respective field, element, and key types of the literal type; 2233 there is no additional conversion. 2234 The key is interpreted as a field name for struct literals, 2235 an index for array and slice literals, and a key for map literals. 2236 For map literals, all elements must have a key. It is an error 2237 to specify multiple elements with the same field name or 2238 constant key value. 2239 </p> 2240 2241 <p> 2242 For struct literals the following rules apply: 2243 </p> 2244 <ul> 2245 <li>A key must be a field name declared in the struct type. 2246 </li> 2247 <li>An element list that does not contain any keys must 2248 list an element for each struct field in the 2249 order in which the fields are declared. 2250 </li> 2251 <li>If any element has a key, every element must have a key. 2252 </li> 2253 <li>An element list that contains keys does not need to 2254 have an element for each struct field. Omitted fields 2255 get the zero value for that field. 2256 </li> 2257 <li>A literal may omit the element list; such a literal evaluates 2258 to the zero value for its type. 2259 </li> 2260 <li>It is an error to specify an element for a non-exported 2261 field of a struct belonging to a different package. 2262 </li> 2263 </ul> 2264 2265 <p> 2266 Given the declarations 2267 </p> 2268 <pre> 2269 type Point3D struct { x, y, z float64 } 2270 type Line struct { p, q Point3D } 2271 </pre> 2272 2273 <p> 2274 one may write 2275 </p> 2276 2277 <pre> 2278 origin := Point3D{} // zero value for Point3D 2279 line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x 2280 </pre> 2281 2282 <p> 2283 For array and slice literals the following rules apply: 2284 </p> 2285 <ul> 2286 <li>Each element has an associated integer index marking 2287 its position in the array. 2288 </li> 2289 <li>An element with a key uses the key as its index. The 2290 key must be a non-negative constant representable by 2291 a value of type <code>int</code>; and if it is typed 2292 it must be of integer type. 2293 </li> 2294 <li>An element without a key uses the previous element's index plus one. 2295 If the first element has no key, its index is zero. 2296 </li> 2297 </ul> 2298 2299 <p> 2300 <a href="#Address_operators">Taking the address</a> of a composite literal 2301 generates a pointer to a unique <a href="#Variables">variable</a> initialized 2302 with the literal's value. 2303 </p> 2304 <pre> 2305 var pointer *Point3D = &Point3D{y: 1000} 2306 </pre> 2307 2308 <p> 2309 The length of an array literal is the length specified in the literal type. 2310 If fewer elements than the length are provided in the literal, the missing 2311 elements are set to the zero value for the array element type. 2312 It is an error to provide elements with index values outside the index range 2313 of the array. The notation <code>...</code> specifies an array length equal 2314 to the maximum element index plus one. 2315 </p> 2316 2317 <pre> 2318 buffer := [10]string{} // len(buffer) == 10 2319 intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6 2320 days := [...]string{"Sat", "Sun"} // len(days) == 2 2321 </pre> 2322 2323 <p> 2324 A slice literal describes the entire underlying array literal. 2325 Thus the length and capacity of a slice literal are the maximum 2326 element index plus one. A slice literal has the form 2327 </p> 2328 2329 <pre> 2330 []T{x1, x2, xn} 2331 </pre> 2332 2333 <p> 2334 and is shorthand for a slice operation applied to an array: 2335 </p> 2336 2337 <pre> 2338 tmp := [n]T{x1, x2, xn} 2339 tmp[0 : n] 2340 </pre> 2341 2342 <p> 2343 Within a composite literal of array, slice, or map type <code>T</code>, 2344 elements or map keys that are themselves composite literals may elide the respective 2345 literal type if it is identical to the element or key type of <code>T</code>. 2346 Similarly, elements or keys that are addresses of composite literals may elide 2347 the <code>&T</code> when the element or key type is <code>*T</code>. 2348 </p> 2349 2350 <pre> 2351 [...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}} 2352 [][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}} 2353 [][]Point{{{0, 1}, {1, 2}}} // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}} 2354 map[string]Point{"orig": {0, 0}} // same as map[string]Point{"orig": Point{0, 0}} 2355 map[Point]string{{0, 0}: "orig"} // same as map[Point]string{Point{0, 0}: "orig"} 2356 2357 type PPoint *Point 2358 [2]*Point{{1.5, -3.5}, {}} // same as [2]*Point{&Point{1.5, -3.5}, &Point{}} 2359 [2]PPoint{{1.5, -3.5}, {}} // same as [2]PPoint{PPoint(&Point{1.5, -3.5}), PPoint(&Point{})} 2360 </pre> 2361 2362 <p> 2363 A parsing ambiguity arises when a composite literal using the 2364 TypeName form of the LiteralType appears as an operand between the 2365 <a href="#Keywords">keyword</a> and the opening brace of the block 2366 of an "if", "for", or "switch" statement, and the composite literal 2367 is not enclosed in parentheses, square brackets, or curly braces. 2368 In this rare case, the opening brace of the literal is erroneously parsed 2369 as the one introducing the block of statements. To resolve the ambiguity, 2370 the composite literal must appear within parentheses. 2371 </p> 2372 2373 <pre> 2374 if x == (T{a,b,c}[i]) { } 2375 if (x == T{a,b,c}[i]) { } 2376 </pre> 2377 2378 <p> 2379 Examples of valid array, slice, and map literals: 2380 </p> 2381 2382 <pre> 2383 // list of prime numbers 2384 primes := []int{2, 3, 5, 7, 9, 2147483647} 2385 2386 // vowels[ch] is true if ch is a vowel 2387 vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true} 2388 2389 // the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1} 2390 filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1} 2391 2392 // frequencies in Hz for equal-tempered scale (A4 = 440Hz) 2393 noteFrequency := map[string]float32{ 2394 "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83, 2395 "G0": 24.50, "A0": 27.50, "B0": 30.87, 2396 } 2397 </pre> 2398 2399 2400 <h3 id="Function_literals">Function literals</h3> 2401 2402 <p> 2403 A function literal represents an anonymous <a href="#Function_declarations">function</a>. 2404 </p> 2405 2406 <pre class="ebnf"> 2407 FunctionLit = "func" Function . 2408 </pre> 2409 2410 <pre> 2411 func(a, b int, z float64) bool { return a*b < int(z) } 2412 </pre> 2413 2414 <p> 2415 A function literal can be assigned to a variable or invoked directly. 2416 </p> 2417 2418 <pre> 2419 f := func(x, y int) int { return x + y } 2420 func(ch chan int) { ch <- ACK }(replyChan) 2421 </pre> 2422 2423 <p> 2424 Function literals are <i>closures</i>: they may refer to variables 2425 defined in a surrounding function. Those variables are then shared between 2426 the surrounding function and the function literal, and they survive as long 2427 as they are accessible. 2428 </p> 2429 2430 2431 <h3 id="Primary_expressions">Primary expressions</h3> 2432 2433 <p> 2434 Primary expressions are the operands for unary and binary expressions. 2435 </p> 2436 2437 <pre class="ebnf"> 2438 PrimaryExpr = 2439 Operand | 2440 Conversion | 2441 PrimaryExpr Selector | 2442 PrimaryExpr Index | 2443 PrimaryExpr Slice | 2444 PrimaryExpr TypeAssertion | 2445 PrimaryExpr Arguments . 2446 2447 Selector = "." identifier . 2448 Index = "[" Expression "]" . 2449 Slice = "[" [ Expression ] ":" [ Expression ] "]" | 2450 "[" [ Expression ] ":" Expression ":" Expression "]" . 2451 TypeAssertion = "." "(" Type ")" . 2452 Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" . 2453 </pre> 2454 2455 2456 <pre> 2457 x 2458 2 2459 (s + ".txt") 2460 f(3.1415, true) 2461 Point{1, 2} 2462 m["foo"] 2463 s[i : j + 1] 2464 obj.color 2465 f.p[i].x() 2466 </pre> 2467 2468 2469 <h3 id="Selectors">Selectors</h3> 2470 2471 <p> 2472 For a <a href="#Primary_expressions">primary expression</a> <code>x</code> 2473 that is not a <a href="#Package_clause">package name</a>, the 2474 <i>selector expression</i> 2475 </p> 2476 2477 <pre> 2478 x.f 2479 </pre> 2480 2481 <p> 2482 denotes the field or method <code>f</code> of the value <code>x</code> 2483 (or sometimes <code>*x</code>; see below). 2484 The identifier <code>f</code> is called the (field or method) <i>selector</i>; 2485 it must not be the <a href="#Blank_identifier">blank identifier</a>. 2486 The type of the selector expression is the type of <code>f</code>. 2487 If <code>x</code> is a package name, see the section on 2488 <a href="#Qualified_identifiers">qualified identifiers</a>. 2489 </p> 2490 2491 <p> 2492 A selector <code>f</code> may denote a field or method <code>f</code> of 2493 a type <code>T</code>, or it may refer 2494 to a field or method <code>f</code> of a nested 2495 <a href="#Struct_types">anonymous field</a> of <code>T</code>. 2496 The number of anonymous fields traversed 2497 to reach <code>f</code> is called its <i>depth</i> in <code>T</code>. 2498 The depth of a field or method <code>f</code> 2499 declared in <code>T</code> is zero. 2500 The depth of a field or method <code>f</code> declared in 2501 an anonymous field <code>A</code> in <code>T</code> is the 2502 depth of <code>f</code> in <code>A</code> plus one. 2503 </p> 2504 2505 <p> 2506 The following rules apply to selectors: 2507 </p> 2508 2509 <ol> 2510 <li> 2511 For a value <code>x</code> of type <code>T</code> or <code>*T</code> 2512 where <code>T</code> is not a pointer or interface type, 2513 <code>x.f</code> denotes the field or method at the shallowest depth 2514 in <code>T</code> where there 2515 is such an <code>f</code>. 2516 If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a> 2517 with shallowest depth, the selector expression is illegal. 2518 </li> 2519 2520 <li> 2521 For a value <code>x</code> of type <code>I</code> where <code>I</code> 2522 is an interface type, <code>x.f</code> denotes the actual method with name 2523 <code>f</code> of the dynamic value of <code>x</code>. 2524 If there is no method with name <code>f</code> in the 2525 <a href="#Method_sets">method set</a> of <code>I</code>, the selector 2526 expression is illegal. 2527 </li> 2528 2529 <li> 2530 As an exception, if the type of <code>x</code> is a named pointer type 2531 and <code>(*x).f</code> is a valid selector expression denoting a field 2532 (but not a method), <code>x.f</code> is shorthand for <code>(*x).f</code>. 2533 </li> 2534 2535 <li> 2536 In all other cases, <code>x.f</code> is illegal. 2537 </li> 2538 2539 <li> 2540 If <code>x</code> is of pointer type and has the value 2541 <code>nil</code> and <code>x.f</code> denotes a struct field, 2542 assigning to or evaluating <code>x.f</code> 2543 causes a <a href="#Run_time_panics">run-time panic</a>. 2544 </li> 2545 2546 <li> 2547 If <code>x</code> is of interface type and has the value 2548 <code>nil</code>, <a href="#Calls">calling</a> or 2549 <a href="#Method_values">evaluating</a> the method <code>x.f</code> 2550 causes a <a href="#Run_time_panics">run-time panic</a>. 2551 </li> 2552 </ol> 2553 2554 <p> 2555 For example, given the declarations: 2556 </p> 2557 2558 <pre> 2559 type T0 struct { 2560 x int 2561 } 2562 2563 func (*T0) M0() 2564 2565 type T1 struct { 2566 y int 2567 } 2568 2569 func (T1) M1() 2570 2571 type T2 struct { 2572 z int 2573 T1 2574 *T0 2575 } 2576 2577 func (*T2) M2() 2578 2579 type Q *T2 2580 2581 var t T2 // with t.T0 != nil 2582 var p *T2 // with p != nil and (*p).T0 != nil 2583 var q Q = p 2584 </pre> 2585 2586 <p> 2587 one may write: 2588 </p> 2589 2590 <pre> 2591 t.z // t.z 2592 t.y // t.T1.y 2593 t.x // (*t.T0).x 2594 2595 p.z // (*p).z 2596 p.y // (*p).T1.y 2597 p.x // (*(*p).T0).x 2598 2599 q.x // (*(*q).T0).x (*q).x is a valid field selector 2600 2601 p.M0() // ((*p).T0).M0() M0 expects *T0 receiver 2602 p.M1() // ((*p).T1).M1() M1 expects T1 receiver 2603 p.M2() // p.M2() M2 expects *T2 receiver 2604 t.M2() // (&t).M2() M2 expects *T2 receiver, see section on Calls 2605 </pre> 2606 2607 <p> 2608 but the following is invalid: 2609 </p> 2610 2611 <pre> 2612 q.M0() // (*q).M0 is valid but not a field selector 2613 </pre> 2614 2615 2616 <h3 id="Method_expressions">Method expressions</h3> 2617 2618 <p> 2619 If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>, 2620 <code>T.M</code> is a function that is callable as a regular function 2621 with the same arguments as <code>M</code> prefixed by an additional 2622 argument that is the receiver of the method. 2623 </p> 2624 2625 <pre class="ebnf"> 2626 MethodExpr = ReceiverType "." MethodName . 2627 ReceiverType = TypeName | "(" "*" TypeName ")" | "(" ReceiverType ")" . 2628 </pre> 2629 2630 <p> 2631 Consider a struct type <code>T</code> with two methods, 2632 <code>Mv</code>, whose receiver is of type <code>T</code>, and 2633 <code>Mp</code>, whose receiver is of type <code>*T</code>. 2634 </p> 2635 2636 <pre> 2637 type T struct { 2638 a int 2639 } 2640 func (tv T) Mv(a int) int { return 0 } // value receiver 2641 func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver 2642 2643 var t T 2644 </pre> 2645 2646 <p> 2647 The expression 2648 </p> 2649 2650 <pre> 2651 T.Mv 2652 </pre> 2653 2654 <p> 2655 yields a function equivalent to <code>Mv</code> but 2656 with an explicit receiver as its first argument; it has signature 2657 </p> 2658 2659 <pre> 2660 func(tv T, a int) int 2661 </pre> 2662 2663 <p> 2664 That function may be called normally with an explicit receiver, so 2665 these five invocations are equivalent: 2666 </p> 2667 2668 <pre> 2669 t.Mv(7) 2670 T.Mv(t, 7) 2671 (T).Mv(t, 7) 2672 f1 := T.Mv; f1(t, 7) 2673 f2 := (T).Mv; f2(t, 7) 2674 </pre> 2675 2676 <p> 2677 Similarly, the expression 2678 </p> 2679 2680 <pre> 2681 (*T).Mp 2682 </pre> 2683 2684 <p> 2685 yields a function value representing <code>Mp</code> with signature 2686 </p> 2687 2688 <pre> 2689 func(tp *T, f float32) float32 2690 </pre> 2691 2692 <p> 2693 For a method with a value receiver, one can derive a function 2694 with an explicit pointer receiver, so 2695 </p> 2696 2697 <pre> 2698 (*T).Mv 2699 </pre> 2700 2701 <p> 2702 yields a function value representing <code>Mv</code> with signature 2703 </p> 2704 2705 <pre> 2706 func(tv *T, a int) int 2707 </pre> 2708 2709 <p> 2710 Such a function indirects through the receiver to create a value 2711 to pass as the receiver to the underlying method; 2712 the method does not overwrite the value whose address is passed in 2713 the function call. 2714 </p> 2715 2716 <p> 2717 The final case, a value-receiver function for a pointer-receiver method, 2718 is illegal because pointer-receiver methods are not in the method set 2719 of the value type. 2720 </p> 2721 2722 <p> 2723 Function values derived from methods are called with function call syntax; 2724 the receiver is provided as the first argument to the call. 2725 That is, given <code>f := T.Mv</code>, <code>f</code> is invoked 2726 as <code>f(t, 7)</code> not <code>t.f(7)</code>. 2727 To construct a function that binds the receiver, use a 2728 <a href="#Function_literals">function literal</a> or 2729 <a href="#Method_values">method value</a>. 2730 </p> 2731 2732 <p> 2733 It is legal to derive a function value from a method of an interface type. 2734 The resulting function takes an explicit receiver of that interface type. 2735 </p> 2736 2737 <h3 id="Method_values">Method values</h3> 2738 2739 <p> 2740 If the expression <code>x</code> has static type <code>T</code> and 2741 <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>, 2742 <code>x.M</code> is called a <i>method value</i>. 2743 The method value <code>x.M</code> is a function value that is callable 2744 with the same arguments as a method call of <code>x.M</code>. 2745 The expression <code>x</code> is evaluated and saved during the evaluation of the 2746 method value; the saved copy is then used as the receiver in any calls, 2747 which may be executed later. 2748 </p> 2749 2750 <p> 2751 The type <code>T</code> may be an interface or non-interface type. 2752 </p> 2753 2754 <p> 2755 As in the discussion of <a href="#Method_expressions">method expressions</a> above, 2756 consider a struct type <code>T</code> with two methods, 2757 <code>Mv</code>, whose receiver is of type <code>T</code>, and 2758 <code>Mp</code>, whose receiver is of type <code>*T</code>. 2759 </p> 2760 2761 <pre> 2762 type T struct { 2763 a int 2764 } 2765 func (tv T) Mv(a int) int { return 0 } // value receiver 2766 func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver 2767 2768 var t T 2769 var pt *T 2770 func makeT() T 2771 </pre> 2772 2773 <p> 2774 The expression 2775 </p> 2776 2777 <pre> 2778 t.Mv 2779 </pre> 2780 2781 <p> 2782 yields a function value of type 2783 </p> 2784 2785 <pre> 2786 func(int) int 2787 </pre> 2788 2789 <p> 2790 These two invocations are equivalent: 2791 </p> 2792 2793 <pre> 2794 t.Mv(7) 2795 f := t.Mv; f(7) 2796 </pre> 2797 2798 <p> 2799 Similarly, the expression 2800 </p> 2801 2802 <pre> 2803 pt.Mp 2804 </pre> 2805 2806 <p> 2807 yields a function value of type 2808 </p> 2809 2810 <pre> 2811 func(float32) float32 2812 </pre> 2813 2814 <p> 2815 As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver 2816 using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>. 2817 </p> 2818 2819 <p> 2820 As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver 2821 using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&t).Mp</code>. 2822 </p> 2823 2824 <pre> 2825 f := t.Mv; f(7) // like t.Mv(7) 2826 f := pt.Mp; f(7) // like pt.Mp(7) 2827 f := pt.Mv; f(7) // like (*pt).Mv(7) 2828 f := t.Mp; f(7) // like (&t).Mp(7) 2829 f := makeT().Mp // invalid: result of makeT() is not addressable 2830 </pre> 2831 2832 <p> 2833 Although the examples above use non-interface types, it is also legal to create a method value 2834 from a value of interface type. 2835 </p> 2836 2837 <pre> 2838 var i interface { M(int) } = myVal 2839 f := i.M; f(7) // like i.M(7) 2840 </pre> 2841 2842 2843 <h3 id="Index_expressions">Index expressions</h3> 2844 2845 <p> 2846 A primary expression of the form 2847 </p> 2848 2849 <pre> 2850 a[x] 2851 </pre> 2852 2853 <p> 2854 denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>. 2855 The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively. 2856 The following rules apply: 2857 </p> 2858 2859 <p> 2860 If <code>a</code> is not a map: 2861 </p> 2862 <ul> 2863 <li>the index <code>x</code> must be of integer type or untyped; 2864 it is <i>in range</i> if <code>0 <= x < len(a)</code>, 2865 otherwise it is <i>out of range</i></li> 2866 <li>a <a href="#Constants">constant</a> index must be non-negative 2867 and representable by a value of type <code>int</code> 2868 </ul> 2869 2870 <p> 2871 For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>: 2872 </p> 2873 <ul> 2874 <li>a <a href="#Constants">constant</a> index must be in range</li> 2875 <li>if <code>x</code> is out of range at run time, 2876 a <a href="#Run_time_panics">run-time panic</a> occurs</li> 2877 <li><code>a[x]</code> is the array element at index <code>x</code> and the type of 2878 <code>a[x]</code> is the element type of <code>A</code></li> 2879 </ul> 2880 2881 <p> 2882 For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type: 2883 </p> 2884 <ul> 2885 <li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li> 2886 </ul> 2887 2888 <p> 2889 For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>: 2890 </p> 2891 <ul> 2892 <li>if <code>x</code> is out of range at run time, 2893 a <a href="#Run_time_panics">run-time panic</a> occurs</li> 2894 <li><code>a[x]</code> is the slice element at index <code>x</code> and the type of 2895 <code>a[x]</code> is the element type of <code>S</code></li> 2896 </ul> 2897 2898 <p> 2899 For <code>a</code> of <a href="#String_types">string type</a>: 2900 </p> 2901 <ul> 2902 <li>a <a href="#Constants">constant</a> index must be in range 2903 if the string <code>a</code> is also constant</li> 2904 <li>if <code>x</code> is out of range at run time, 2905 a <a href="#Run_time_panics">run-time panic</a> occurs</li> 2906 <li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of 2907 <code>a[x]</code> is <code>byte</code></li> 2908 <li><code>a[x]</code> may not be assigned to</li> 2909 </ul> 2910 2911 <p> 2912 For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>: 2913 </p> 2914 <ul> 2915 <li><code>x</code>'s type must be 2916 <a href="#Assignability">assignable</a> 2917 to the key type of <code>M</code></li> 2918 <li>if the map contains an entry with key <code>x</code>, 2919 <code>a[x]</code> is the map value with key <code>x</code> 2920 and the type of <code>a[x]</code> is the value type of <code>M</code></li> 2921 <li>if the map is <code>nil</code> or does not contain such an entry, 2922 <code>a[x]</code> is the <a href="#The_zero_value">zero value</a> 2923 for the value type of <code>M</code></li> 2924 </ul> 2925 2926 <p> 2927 Otherwise <code>a[x]</code> is illegal. 2928 </p> 2929 2930 <p> 2931 An index expression on a map <code>a</code> of type <code>map[K]V</code> 2932 used in an <a href="#Assignments">assignment</a> or initialization of the special form 2933 </p> 2934 2935 <pre> 2936 v, ok = a[x] 2937 v, ok := a[x] 2938 var v, ok = a[x] 2939 var v, ok T = a[x] 2940 </pre> 2941 2942 <p> 2943 yields an additional untyped boolean value. The value of <code>ok</code> is 2944 <code>true</code> if the key <code>x</code> is present in the map, and 2945 <code>false</code> otherwise. 2946 </p> 2947 2948 <p> 2949 Assigning to an element of a <code>nil</code> map causes a 2950 <a href="#Run_time_panics">run-time panic</a>. 2951 </p> 2952 2953 2954 <h3 id="Slice_expressions">Slice expressions</h3> 2955 2956 <p> 2957 Slice expressions construct a substring or slice from a string, array, pointer 2958 to array, or slice. There are two variants: a simple form that specifies a low 2959 and high bound, and a full form that also specifies a bound on the capacity. 2960 </p> 2961 2962 <h4>Simple slice expressions</h4> 2963 2964 <p> 2965 For a string, array, pointer to array, or slice <code>a</code>, the primary expression 2966 </p> 2967 2968 <pre> 2969 a[low : high] 2970 </pre> 2971 2972 <p> 2973 constructs a substring or slice. The <i>indices</i> <code>low</code> and 2974 <code>high</code> select which elements of operand <code>a</code> appear 2975 in the result. The result has indices starting at 0 and length equal to 2976 <code>high</code> - <code>low</code>. 2977 After slicing the array <code>a</code> 2978 </p> 2979 2980 <pre> 2981 a := [5]int{1, 2, 3, 4, 5} 2982 s := a[1:4] 2983 </pre> 2984 2985 <p> 2986 the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements 2987 </p> 2988 2989 <pre> 2990 s[0] == 2 2991 s[1] == 3 2992 s[2] == 4 2993 </pre> 2994 2995 <p> 2996 For convenience, any of the indices may be omitted. A missing <code>low</code> 2997 index defaults to zero; a missing <code>high</code> index defaults to the length of the 2998 sliced operand: 2999 </p> 3000 3001 <pre> 3002 a[2:] // same as a[2 : len(a)] 3003 a[:3] // same as a[0 : 3] 3004 a[:] // same as a[0 : len(a)] 3005 </pre> 3006 3007 <p> 3008 If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for 3009 <code>(*a)[low : high]</code>. 3010 </p> 3011 3012 <p> 3013 For arrays or strings, the indices are <i>in range</i> if 3014 <code>0</code> <= <code>low</code> <= <code>high</code> <= <code>len(a)</code>, 3015 otherwise they are <i>out of range</i>. 3016 For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length. 3017 A <a href="#Constants">constant</a> index must be non-negative and representable by a value of type 3018 <code>int</code>; for arrays or constant strings, constant indices must also be in range. 3019 If both indices are constant, they must satisfy <code>low <= high</code>. 3020 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. 3021 </p> 3022 3023 <p> 3024 Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice, 3025 the result of the slice operation is a non-constant value of the same type as the operand. 3026 For untyped string operands the result is a non-constant value of type <code>string</code>. 3027 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a> 3028 and the result of the slice operation is a slice with the same element type as the array. 3029 </p> 3030 3031 <p> 3032 If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result 3033 is a <code>nil</code> slice. Otherwise, the result shares its underlying array with the 3034 operand. 3035 </p> 3036 3037 <h4>Full slice expressions</h4> 3038 3039 <p> 3040 For an array, pointer to array, or slice <code>a</code> (but not a string), the primary expression 3041 </p> 3042 3043 <pre> 3044 a[low : high : max] 3045 </pre> 3046 3047 <p> 3048 constructs a slice of the same type, and with the same length and elements as the simple slice 3049 expression <code>a[low : high]</code>. Additionally, it controls the resulting slice's capacity 3050 by setting it to <code>max - low</code>. Only the first index may be omitted; it defaults to 0. 3051 After slicing the array <code>a</code> 3052 </p> 3053 3054 <pre> 3055 a := [5]int{1, 2, 3, 4, 5} 3056 t := a[1:3:5] 3057 </pre> 3058 3059 <p> 3060 the slice <code>t</code> has type <code>[]int</code>, length 2, capacity 4, and elements 3061 </p> 3062 3063 <pre> 3064 t[0] == 2 3065 t[1] == 3 3066 </pre> 3067 3068 <p> 3069 As for simple slice expressions, if <code>a</code> is a pointer to an array, 3070 <code>a[low : high : max]</code> is shorthand for <code>(*a)[low : high : max]</code>. 3071 If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>. 3072 </p> 3073 3074 <p> 3075 The indices are <i>in range</i> if <code>0 <= low <= high <= max <= cap(a)</code>, 3076 otherwise they are <i>out of range</i>. 3077 A <a href="#Constants">constant</a> index must be non-negative and representable by a value of type 3078 <code>int</code>; for arrays, constant indices must also be in range. 3079 If multiple indices are constant, the constants that are present must be in range relative to each 3080 other. 3081 If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. 3082 </p> 3083 3084 <h3 id="Type_assertions">Type assertions</h3> 3085 3086 <p> 3087 For an expression <code>x</code> of <a href="#Interface_types">interface type</a> 3088 and a type <code>T</code>, the primary expression 3089 </p> 3090 3091 <pre> 3092 x.(T) 3093 </pre> 3094 3095 <p> 3096 asserts that <code>x</code> is not <code>nil</code> 3097 and that the value stored in <code>x</code> is of type <code>T</code>. 3098 The notation <code>x.(T)</code> is called a <i>type assertion</i>. 3099 </p> 3100 <p> 3101 More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts 3102 that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a> 3103 to the type <code>T</code>. 3104 In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>; 3105 otherwise the type assertion is invalid since it is not possible for <code>x</code> 3106 to store a value of type <code>T</code>. 3107 If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type 3108 of <code>x</code> implements the interface <code>T</code>. 3109 </p> 3110 <p> 3111 If the type assertion holds, the value of the expression is the value 3112 stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false, 3113 a <a href="#Run_time_panics">run-time panic</a> occurs. 3114 In other words, even though the dynamic type of <code>x</code> 3115 is known only at run time, the type of <code>x.(T)</code> is 3116 known to be <code>T</code> in a correct program. 3117 </p> 3118 3119 <pre> 3120 var x interface{} = 7 // x has dynamic type int and value 7 3121 i := x.(int) // i has type int and value 7 3122 3123 type I interface { m() } 3124 3125 func f(y I) { 3126 s := y.(string) // illegal: string does not implement I (missing method m) 3127 r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader 3128 3129 } 3130 </pre> 3131 3132 <p> 3133 A type assertion used in an <a href="#Assignments">assignment</a> or initialization of the special form 3134 </p> 3135 3136 <pre> 3137 v, ok = x.(T) 3138 v, ok := x.(T) 3139 var v, ok = x.(T) 3140 var v, ok T1 = x.(T) 3141 </pre> 3142 3143 <p> 3144 yields an additional untyped boolean value. The value of <code>ok</code> is <code>true</code> 3145 if the assertion holds. Otherwise it is <code>false</code> and the value of <code>v</code> is 3146 the <a href="#The_zero_value">zero value</a> for type <code>T</code>. 3147 No run-time panic occurs in this case. 3148 </p> 3149 3150 3151 <h3 id="Calls">Calls</h3> 3152 3153 <p> 3154 Given an expression <code>f</code> of function type 3155 <code>F</code>, 3156 </p> 3157 3158 <pre> 3159 f(a1, a2, an) 3160 </pre> 3161 3162 <p> 3163 calls <code>f</code> with arguments <code>a1, a2, an</code>. 3164 Except for one special case, arguments must be single-valued expressions 3165 <a href="#Assignability">assignable</a> to the parameter types of 3166 <code>F</code> and are evaluated before the function is called. 3167 The type of the expression is the result type 3168 of <code>F</code>. 3169 A method invocation is similar but the method itself 3170 is specified as a selector upon a value of the receiver type for 3171 the method. 3172 </p> 3173 3174 <pre> 3175 math.Atan2(x, y) // function call 3176 var pt *Point 3177 pt.Scale(3.5) // method call with receiver pt 3178 </pre> 3179 3180 <p> 3181 In a function call, the function value and arguments are evaluated in 3182 <a href="#Order_of_evaluation">the usual order</a>. 3183 After they are evaluated, the parameters of the call are passed by value to the function 3184 and the called function begins execution. 3185 The return parameters of the function are passed by value 3186 back to the calling function when the function returns. 3187 </p> 3188 3189 <p> 3190 Calling a <code>nil</code> function value 3191 causes a <a href="#Run_time_panics">run-time panic</a>. 3192 </p> 3193 3194 <p> 3195 As a special case, if the return values of a function or method 3196 <code>g</code> are equal in number and individually 3197 assignable to the parameters of another function or method 3198 <code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code> 3199 will invoke <code>f</code> after binding the return values of 3200 <code>g</code> to the parameters of <code>f</code> in order. The call 3201 of <code>f</code> must contain no parameters other than the call of <code>g</code>, 3202 and <code>g</code> must have at least one return value. 3203 If <code>f</code> has a final <code>...</code> parameter, it is 3204 assigned the return values of <code>g</code> that remain after 3205 assignment of regular parameters. 3206 </p> 3207 3208 <pre> 3209 func Split(s string, pos int) (string, string) { 3210 return s[0:pos], s[pos:] 3211 } 3212 3213 func Join(s, t string) string { 3214 return s + t 3215 } 3216 3217 if Join(Split(value, len(value)/2)) != value { 3218 log.Panic("test fails") 3219 } 3220 </pre> 3221 3222 <p> 3223 A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a> 3224 of (the type of) <code>x</code> contains <code>m</code> and the 3225 argument list can be assigned to the parameter list of <code>m</code>. 3226 If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&x</code>'s method 3227 set contains <code>m</code>, <code>x.m()</code> is shorthand 3228 for <code>(&x).m()</code>: 3229 </p> 3230 3231 <pre> 3232 var p Point 3233 p.Scale(3.5) 3234 </pre> 3235 3236 <p> 3237 There is no distinct method type and there are no method literals. 3238 </p> 3239 3240 <h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3> 3241 3242 <p> 3243 If <code>f</code> is <a href="#Function_types">variadic</a> with a final 3244 parameter <code>p</code> of type <code>...T</code>, then within <code>f</code> 3245 the type of <code>p</code> is equivalent to type <code>[]T</code>. 3246 If <code>f</code> is invoked with no actual arguments for <code>p</code>, 3247 the value passed to <code>p</code> is <code>nil</code>. 3248 Otherwise, the value passed is a new slice 3249 of type <code>[]T</code> with a new underlying array whose successive elements 3250 are the actual arguments, which all must be <a href="#Assignability">assignable</a> 3251 to <code>T</code>. The length and capacity of the slice is therefore 3252 the number of arguments bound to <code>p</code> and may differ for each 3253 call site. 3254 </p> 3255 3256 <p> 3257 Given the function and calls 3258 </p> 3259 <pre> 3260 func Greeting(prefix string, who ...string) 3261 Greeting("nobody") 3262 Greeting("hello:", "Joe", "Anna", "Eileen") 3263 </pre> 3264 3265 <p> 3266 within <code>Greeting</code>, <code>who</code> will have the value 3267 <code>nil</code> in the first call, and 3268 <code>[]string{"Joe", "Anna", "Eileen"}</code> in the second. 3269 </p> 3270 3271 <p> 3272 If the final argument is assignable to a slice type <code>[]T</code>, it may be 3273 passed unchanged as the value for a <code>...T</code> parameter if the argument 3274 is followed by <code>...</code>. In this case no new slice is created. 3275 </p> 3276 3277 <p> 3278 Given the slice <code>s</code> and call 3279 </p> 3280 3281 <pre> 3282 s := []string{"James", "Jasmine"} 3283 Greeting("goodbye:", s...) 3284 </pre> 3285 3286 <p> 3287 within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code> 3288 with the same underlying array. 3289 </p> 3290 3291 3292 <h3 id="Operators">Operators</h3> 3293 3294 <p> 3295 Operators combine operands into expressions. 3296 </p> 3297 3298 <pre class="ebnf"> 3299 Expression = UnaryExpr | Expression binary_op Expression . 3300 UnaryExpr = PrimaryExpr | unary_op UnaryExpr . 3301 3302 binary_op = "||" | "&&" | rel_op | add_op | mul_op . 3303 rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" . 3304 add_op = "+" | "-" | "|" | "^" . 3305 mul_op = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" . 3306 3307 unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-" . 3308 </pre> 3309 3310 <p> 3311 Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>. 3312 For other binary operators, the operand types must be <a href="#Type_identity">identical</a> 3313 unless the operation involves shifts or untyped <a href="#Constants">constants</a>. 3314 For operations involving constants only, see the section on 3315 <a href="#Constant_expressions">constant expressions</a>. 3316 </p> 3317 3318 <p> 3319 Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a> 3320 and the other operand is not, the constant is <a href="#Conversions">converted</a> 3321 to the type of the other operand. 3322 </p> 3323 3324 <p> 3325 The right operand in a shift expression must have unsigned integer type 3326 or be an untyped constant that can be converted to unsigned integer type. 3327 If the left operand of a non-constant shift expression is an untyped constant, 3328 it is first converted to the type it would assume if the shift expression were 3329 replaced by its left operand alone. 3330 </p> 3331 3332 <pre> 3333 var s uint = 33 3334 var i = 1<<s // 1 has type int 3335 var j int32 = 1<<s // 1 has type int32; j == 0 3336 var k = uint64(1<<s) // 1 has type uint64; k == 1<<33 3337 var m int = 1.0<<s // 1.0 has type int; m == 0 if ints are 32bits in size 3338 var n = 1.0<<s == j // 1.0 has type int32; n == true 3339 var o = 1<<s == 2<<s // 1 and 2 have type int; o == true if ints are 32bits in size 3340 var p = 1<<s == 1<<33 // illegal if ints are 32bits in size: 1 has type int, but 1<<33 overflows int 3341 var u = 1.0<<s // illegal: 1.0 has type float64, cannot shift 3342 var u1 = 1.0<<s != 0 // illegal: 1.0 has type float64, cannot shift 3343 var u2 = 1<<s != 1.0 // illegal: 1 has type float64, cannot shift 3344 var v float32 = 1<<s // illegal: 1 has type float32, cannot shift 3345 var w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression 3346 </pre> 3347 3348 3349 <h4 id="Operator_precedence">Operator precedence</h4> 3350 <p> 3351 Unary operators have the highest precedence. 3352 As the <code>++</code> and <code>--</code> operators form 3353 statements, not expressions, they fall 3354 outside the operator hierarchy. 3355 As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>. 3356 <p> 3357 There are five precedence levels for binary operators. 3358 Multiplication operators bind strongest, followed by addition 3359 operators, comparison operators, <code>&&</code> (logical AND), 3360 and finally <code>||</code> (logical OR): 3361 </p> 3362 3363 <pre class="grammar"> 3364 Precedence Operator 3365 5 * / % << >> & &^ 3366 4 + - | ^ 3367 3 == != < <= > >= 3368 2 && 3369 1 || 3370 </pre> 3371 3372 <p> 3373 Binary operators of the same precedence associate from left to right. 3374 For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>. 3375 </p> 3376 3377 <pre> 3378 +x 3379 23 + 3*x[i] 3380 x <= f() 3381 ^a >> b 3382 f() || g() 3383 x == y+1 && <-chanPtr > 0 3384 </pre> 3385 3386 3387 <h3 id="Arithmetic_operators">Arithmetic operators</h3> 3388 <p> 3389 Arithmetic operators apply to numeric values and yield a result of the same 3390 type as the first operand. The four standard arithmetic operators (<code>+</code>, 3391 <code>-</code>, <code>*</code>, <code>/</code>) apply to integer, 3392 floating-point, and complex types; <code>+</code> also applies to strings. 3393 The bitwise logical and shift operators apply to integers only. 3394 </p> 3395 3396 <pre class="grammar"> 3397 + sum integers, floats, complex values, strings 3398 - difference integers, floats, complex values 3399 * product integers, floats, complex values 3400 / quotient integers, floats, complex values 3401 % remainder integers 3402 3403 & bitwise AND integers 3404 | bitwise OR integers 3405 ^ bitwise XOR integers 3406 &^ bit clear (AND NOT) integers 3407 3408 << left shift integer << unsigned integer 3409 >> right shift integer >> unsigned integer 3410 </pre> 3411 3412 3413 <h4 id="Integer_operators">Integer operators</h4> 3414 3415 <p> 3416 For two integer values <code>x</code> and <code>y</code>, the integer quotient 3417 <code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following 3418 relationships: 3419 </p> 3420 3421 <pre> 3422 x = q*y + r and |r| < |y| 3423 </pre> 3424 3425 <p> 3426 with <code>x / y</code> truncated towards zero 3427 (<a href="http://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>). 3428 </p> 3429 3430 <pre> 3431 x y x / y x % y 3432 5 3 1 2 3433 -5 3 -1 -2 3434 5 -3 -1 2 3435 -5 -3 1 -2 3436 </pre> 3437 3438 <p> 3439 As an exception to this rule, if the dividend <code>x</code> is the most 3440 negative value for the int type of <code>x</code>, the quotient 3441 <code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>). 3442 </p> 3443 3444 <pre> 3445 x, q 3446 int8 -128 3447 int16 -32768 3448 int32 -2147483648 3449 int64 -9223372036854775808 3450 </pre> 3451 3452 <p> 3453 If the divisor is a <a href="#Constants">constant</a>, it must not be zero. 3454 If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs. 3455 If the dividend is non-negative and the divisor is a constant power of 2, 3456 the division may be replaced by a right shift, and computing the remainder may 3457 be replaced by a bitwise AND operation: 3458 </p> 3459 3460 <pre> 3461 x x / 4 x % 4 x >> 2 x & 3 3462 11 2 3 2 3 3463 -11 -2 -3 -3 1 3464 </pre> 3465 3466 <p> 3467 The shift operators shift the left operand by the shift count specified by the 3468 right operand. They implement arithmetic shifts if the left operand is a signed 3469 integer and logical shifts if it is an unsigned integer. 3470 There is no upper limit on the shift count. Shifts behave 3471 as if the left operand is shifted <code>n</code> times by 1 for a shift 3472 count of <code>n</code>. 3473 As a result, <code>x << 1</code> is the same as <code>x*2</code> 3474 and <code>x >> 1</code> is the same as 3475 <code>x/2</code> but truncated towards negative infinity. 3476 </p> 3477 3478 <p> 3479 For integer operands, the unary operators 3480 <code>+</code>, <code>-</code>, and <code>^</code> are defined as 3481 follows: 3482 </p> 3483 3484 <pre class="grammar"> 3485 +x is 0 + x 3486 -x negation is 0 - x 3487 ^x bitwise complement is m ^ x with m = "all bits set to 1" for unsigned x 3488 and m = -1 for signed x 3489 </pre> 3490 3491 3492 <h4 id="Integer_overflow">Integer overflow</h4> 3493 3494 <p> 3495 For unsigned integer values, the operations <code>+</code>, 3496 <code>-</code>, <code>*</code>, and <code><<</code> are 3497 computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of 3498 the <a href="#Numeric_types">unsigned integer</a>'s type. 3499 Loosely speaking, these unsigned integer operations 3500 discard high bits upon overflow, and programs may rely on ``wrap around''. 3501 </p> 3502 <p> 3503 For signed integers, the operations <code>+</code>, 3504 <code>-</code>, <code>*</code>, and <code><<</code> may legally 3505 overflow and the resulting value exists and is deterministically defined 3506 by the signed integer representation, the operation, and its operands. 3507 No exception is raised as a result of overflow. A 3508 compiler may not optimize code under the assumption that overflow does 3509 not occur. For instance, it may not assume that <code>x < x + 1</code> is always true. 3510 </p> 3511 3512 3513 <h4 id="Floating_point_operators">Floating-point operators</h4> 3514 3515 <p> 3516 For floating-point and complex numbers, 3517 <code>+x</code> is the same as <code>x</code>, 3518 while <code>-x</code> is the negation of <code>x</code>. 3519 The result of a floating-point or complex division by zero is not specified beyond the 3520 IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a> 3521 occurs is implementation-specific. 3522 </p> 3523 3524 3525 <h4 id="String_concatenation">String concatenation</h4> 3526 3527 <p> 3528 Strings can be concatenated using the <code>+</code> operator 3529 or the <code>+=</code> assignment operator: 3530 </p> 3531 3532 <pre> 3533 s := "hi" + string(c) 3534 s += " and good bye" 3535 </pre> 3536 3537 <p> 3538 String addition creates a new string by concatenating the operands. 3539 </p> 3540 3541 3542 <h3 id="Comparison_operators">Comparison operators</h3> 3543 3544 <p> 3545 Comparison operators compare two operands and yield an untyped boolean value. 3546 </p> 3547 3548 <pre class="grammar"> 3549 == equal 3550 != not equal 3551 < less 3552 <= less or equal 3553 > greater 3554 >= greater or equal 3555 </pre> 3556 3557 <p> 3558 In any comparison, the first operand 3559 must be <a href="#Assignability">assignable</a> 3560 to the type of the second operand, or vice versa. 3561 </p> 3562 <p> 3563 The equality operators <code>==</code> and <code>!=</code> apply 3564 to operands that are <i>comparable</i>. 3565 The ordering operators <code><</code>, <code><=</code>, <code>></code>, and <code>>=</code> 3566 apply to operands that are <i>ordered</i>. 3567 These terms and the result of the comparisons are defined as follows: 3568 </p> 3569 3570 <ul> 3571 <li> 3572 Boolean values are comparable. 3573 Two boolean values are equal if they are either both 3574 <code>true</code> or both <code>false</code>. 3575 </li> 3576 3577 <li> 3578 Integer values are comparable and ordered, in the usual way. 3579 </li> 3580 3581 <li> 3582 Floating point values are comparable and ordered, 3583 as defined by the IEEE-754 standard. 3584 </li> 3585 3586 <li> 3587 Complex values are comparable. 3588 Two complex values <code>u</code> and <code>v</code> are 3589 equal if both <code>real(u) == real(v)</code> and 3590 <code>imag(u) == imag(v)</code>. 3591 </li> 3592 3593 <li> 3594 String values are comparable and ordered, lexically byte-wise. 3595 </li> 3596 3597 <li> 3598 Pointer values are comparable. 3599 Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>. 3600 Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal. 3601 </li> 3602 3603 <li> 3604 Channel values are comparable. 3605 Two channel values are equal if they were created by the same call to 3606 <a href="#Making_slices_maps_and_channels"><code>make</code></a> 3607 or if both have value <code>nil</code>. 3608 </li> 3609 3610 <li> 3611 Interface values are comparable. 3612 Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types 3613 and equal dynamic values or if both have value <code>nil</code>. 3614 </li> 3615 3616 <li> 3617 A value <code>x</code> of non-interface type <code>X</code> and 3618 a value <code>t</code> of interface type <code>T</code> are comparable when values 3619 of type <code>X</code> are comparable and 3620 <code>X</code> implements <code>T</code>. 3621 They are equal if <code>t</code>'s dynamic type is identical to <code>X</code> 3622 and <code>t</code>'s dynamic value is equal to <code>x</code>. 3623 </li> 3624 3625 <li> 3626 Struct values are comparable if all their fields are comparable. 3627 Two struct values are equal if their corresponding 3628 non-<a href="#Blank_identifier">blank</a> fields are equal. 3629 </li> 3630 3631 <li> 3632 Array values are comparable if values of the array element type are comparable. 3633 Two array values are equal if their corresponding elements are equal. 3634 </li> 3635 </ul> 3636 3637 <p> 3638 A comparison of two interface values with identical dynamic types 3639 causes a <a href="#Run_time_panics">run-time panic</a> if values 3640 of that type are not comparable. This behavior applies not only to direct interface 3641 value comparisons but also when comparing arrays of interface values 3642 or structs with interface-valued fields. 3643 </p> 3644 3645 <p> 3646 Slice, map, and function values are not comparable. 3647 However, as a special case, a slice, map, or function value may 3648 be compared to the predeclared identifier <code>nil</code>. 3649 Comparison of pointer, channel, and interface values to <code>nil</code> 3650 is also allowed and follows from the general rules above. 3651 </p> 3652 3653 <pre> 3654 const c = 3 < 4 // c is the untyped boolean constant true 3655 3656 type MyBool bool 3657 var x, y int 3658 var ( 3659 // The result of a comparison is an untyped boolean. 3660 // The usual assignment rules apply. 3661 b3 = x == y // b3 has type bool 3662 b4 bool = x == y // b4 has type bool 3663 b5 MyBool = x == y // b5 has type MyBool 3664 ) 3665 </pre> 3666 3667 <h3 id="Logical_operators">Logical operators</h3> 3668 3669 <p> 3670 Logical operators apply to <a href="#Boolean_types">boolean</a> values 3671 and yield a result of the same type as the operands. 3672 The right operand is evaluated conditionally. 3673 </p> 3674 3675 <pre class="grammar"> 3676 && conditional AND p && q is "if p then q else false" 3677 || conditional OR p || q is "if p then true else q" 3678 ! NOT !p is "not p" 3679 </pre> 3680 3681 3682 <h3 id="Address_operators">Address operators</h3> 3683 3684 <p> 3685 For an operand <code>x</code> of type <code>T</code>, the address operation 3686 <code>&x</code> generates a pointer of type <code>*T</code> to <code>x</code>. 3687 The operand must be <i>addressable</i>, 3688 that is, either a variable, pointer indirection, or slice indexing 3689 operation; or a field selector of an addressable struct operand; 3690 or an array indexing operation of an addressable array. 3691 As an exception to the addressability requirement, <code>x</code> may also be a 3692 (possibly parenthesized) 3693 <a href="#Composite_literals">composite literal</a>. 3694 If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>, 3695 then the evaluation of <code>&x</code> does too. 3696 </p> 3697 3698 <p> 3699 For an operand <code>x</code> of pointer type <code>*T</code>, the pointer 3700 indirection <code>*x</code> denotes the <a href="#Variables">variable</a> of type <code>T</code> pointed 3701 to by <code>x</code>. 3702 If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code> 3703 will cause a <a href="#Run_time_panics">run-time panic</a>. 3704 </p> 3705 3706 <pre> 3707 &x 3708 &a[f(2)] 3709 &Point{2, 3} 3710 *p 3711 *pf(x) 3712 3713 var x *int = nil 3714 *x // causes a run-time panic 3715 &*x // causes a run-time panic 3716 </pre> 3717 3718 3719 <h3 id="Receive_operator">Receive operator</h3> 3720 3721 <p> 3722 For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>, 3723 the value of the receive operation <code><-ch</code> is the value received 3724 from the channel <code>ch</code>. The channel direction must permit receive operations, 3725 and the type of the receive operation is the element type of the channel. 3726 The expression blocks until a value is available. 3727 Receiving from a <code>nil</code> channel blocks forever. 3728 A receive operation on a <a href="#Close">closed</a> channel can always proceed 3729 immediately, yielding the element type's <a href="#The_zero_value">zero value</a> 3730 after any previously sent values have been received. 3731 </p> 3732 3733 <pre> 3734 v1 := <-ch 3735 v2 = <-ch 3736 f(<-ch) 3737 <-strobe // wait until clock pulse and discard received value 3738 </pre> 3739 3740 <p> 3741 A receive expression used in an <a href="#Assignments">assignment</a> or initialization of the special form 3742 </p> 3743 3744 <pre> 3745 x, ok = <-ch 3746 x, ok := <-ch 3747 var x, ok = <-ch 3748 var x, ok T = <-ch 3749 </pre> 3750 3751 <p> 3752 yields an additional untyped boolean result reporting whether the 3753 communication succeeded. The value of <code>ok</code> is <code>true</code> 3754 if the value received was delivered by a successful send operation to the 3755 channel, or <code>false</code> if it is a zero value generated because the 3756 channel is closed and empty. 3757 </p> 3758 3759 3760 <h3 id="Conversions">Conversions</h3> 3761 3762 <p> 3763 Conversions are expressions of the form <code>T(x)</code> 3764 where <code>T</code> is a type and <code>x</code> is an expression 3765 that can be converted to type <code>T</code>. 3766 </p> 3767 3768 <pre class="ebnf"> 3769 Conversion = Type "(" Expression [ "," ] ")" . 3770 </pre> 3771 3772 <p> 3773 If the type starts with the operator <code>*</code> or <code><-</code>, 3774 or if the type starts with the keyword <code>func</code> 3775 and has no result list, it must be parenthesized when 3776 necessary to avoid ambiguity: 3777 </p> 3778 3779 <pre> 3780 *Point(p) // same as *(Point(p)) 3781 (*Point)(p) // p is converted to *Point 3782 <-chan int(c) // same as <-(chan int(c)) 3783 (<-chan int)(c) // c is converted to <-chan int 3784 func()(x) // function signature func() x 3785 (func())(x) // x is converted to func() 3786 (func() int)(x) // x is converted to func() int 3787 func() int(x) // x is converted to func() int (unambiguous) 3788 </pre> 3789 3790 <p> 3791 A <a href="#Constants">constant</a> value <code>x</code> can be converted to 3792 type <code>T</code> in any of these cases: 3793 </p> 3794 3795 <ul> 3796 <li> 3797 <code>x</code> is representable by a value of type <code>T</code>. 3798 </li> 3799 <li> 3800 <code>x</code> is a floating-point constant, 3801 <code>T</code> is a floating-point type, 3802 and <code>x</code> is representable by a value 3803 of type <code>T</code> after rounding using 3804 IEEE 754 round-to-even rules, but with an IEEE <code>-0.0</code> 3805 further rounded to an unsigned <code>0.0</code>. 3806 The constant <code>T(x)</code> is the rounded value. 3807 </li> 3808 <li> 3809 <code>x</code> is an integer constant and <code>T</code> is a 3810 <a href="#String_types">string type</a>. 3811 The <a href="#Conversions_to_and_from_a_string_type">same rule</a> 3812 as for non-constant <code>x</code> applies in this case. 3813 </li> 3814 </ul> 3815 3816 <p> 3817 Converting a constant yields a typed constant as result. 3818 </p> 3819 3820 <pre> 3821 uint(iota) // iota value of type uint 3822 float32(2.718281828) // 2.718281828 of type float32 3823 complex128(1) // 1.0 + 0.0i of type complex128 3824 float32(0.49999999) // 0.5 of type float32 3825 float64(-1e-1000) // 0.0 of type float64 3826 string('x') // "x" of type string 3827 string(0x266c) // "" of type string 3828 MyString("foo" + "bar") // "foobar" of type MyString 3829 string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant 3830 (*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type 3831 int(1.2) // illegal: 1.2 cannot be represented as an int 3832 string(65.0) // illegal: 65.0 is not an integer constant 3833 </pre> 3834 3835 <p> 3836 A non-constant value <code>x</code> can be converted to type <code>T</code> 3837 in any of these cases: 3838 </p> 3839 3840 <ul> 3841 <li> 3842 <code>x</code> is <a href="#Assignability">assignable</a> 3843 to <code>T</code>. 3844 </li> 3845 <li> 3846 ignoring struct tags (see below), 3847 <code>x</code>'s type and <code>T</code> have <a href="#Type_identity">identical</a> 3848 <a href="#Types">underlying types</a>. 3849 </li> 3850 <li> 3851 ignoring struct tags (see below), 3852 <code>x</code>'s type and <code>T</code> are unnamed pointer types 3853 and their pointer base types have identical underlying types. 3854 </li> 3855 <li> 3856 <code>x</code>'s type and <code>T</code> are both integer or floating 3857 point types. 3858 </li> 3859 <li> 3860 <code>x</code>'s type and <code>T</code> are both complex types. 3861 </li> 3862 <li> 3863 <code>x</code> is an integer or a slice of bytes or runes 3864 and <code>T</code> is a string type. 3865 </li> 3866 <li> 3867 <code>x</code> is a string and <code>T</code> is a slice of bytes or runes. 3868 </li> 3869 </ul> 3870 3871 <p> 3872 <a href="#Struct_types">Struct tags</a> are ignored when comparing struct types 3873 for identity for the purpose of conversion: 3874 </p> 3875 3876 <pre> 3877 type Person struct { 3878 Name string 3879 Address *struct { 3880 Street string 3881 City string 3882 } 3883 } 3884 3885 var data *struct { 3886 Name string `json:"name"` 3887 Address *struct { 3888 Street string `json:"street"` 3889 City string `json:"city"` 3890 } `json:"address"` 3891 } 3892 3893 var person = (*Person)(data) // ignoring tags, the underlying types are identical 3894 </pre> 3895 3896 <p> 3897 Specific rules apply to (non-constant) conversions between numeric types or 3898 to and from a string type. 3899 These conversions may change the representation of <code>x</code> 3900 and incur a run-time cost. 3901 All other conversions only change the type but not the representation 3902 of <code>x</code>. 3903 </p> 3904 3905 <p> 3906 There is no linguistic mechanism to convert between pointers and integers. 3907 The package <a href="#Package_unsafe"><code>unsafe</code></a> 3908 implements this functionality under 3909 restricted circumstances. 3910 </p> 3911 3912 <h4>Conversions between numeric types</h4> 3913 3914 <p> 3915 For the conversion of non-constant numeric values, the following rules apply: 3916 </p> 3917 3918 <ol> 3919 <li> 3920 When converting between integer types, if the value is a signed integer, it is 3921 sign extended to implicit infinite precision; otherwise it is zero extended. 3922 It is then truncated to fit in the result type's size. 3923 For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>. 3924 The conversion always yields a valid value; there is no indication of overflow. 3925 </li> 3926 <li> 3927 When converting a floating-point number to an integer, the fraction is discarded 3928 (truncation towards zero). 3929 </li> 3930 <li> 3931 When converting an integer or floating-point number to a floating-point type, 3932 or a complex number to another complex type, the result value is rounded 3933 to the precision specified by the destination type. 3934 For instance, the value of a variable <code>x</code> of type <code>float32</code> 3935 may be stored using additional precision beyond that of an IEEE-754 32-bit number, 3936 but float32(x) represents the result of rounding <code>x</code>'s value to 3937 32-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits 3938 of precision, but <code>float32(x + 0.1)</code> does not. 3939 </li> 3940 </ol> 3941 3942 <p> 3943 In all non-constant conversions involving floating-point or complex values, 3944 if the result type cannot represent the value the conversion 3945 succeeds but the result value is implementation-dependent. 3946 </p> 3947 3948 <h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4> 3949 3950 <ol> 3951 <li> 3952 Converting a signed or unsigned integer value to a string type yields a 3953 string containing the UTF-8 representation of the integer. Values outside 3954 the range of valid Unicode code points are converted to <code>"\uFFFD"</code>. 3955 3956 <pre> 3957 string('a') // "a" 3958 string(-1) // "\ufffd" == "\xef\xbf\xbd" 3959 string(0xf8) // "\u00f8" == "" == "\xc3\xb8" 3960 type MyString string 3961 MyString(0x65e5) // "\u65e5" == "" == "\xe6\x97\xa5" 3962 </pre> 3963 </li> 3964 3965 <li> 3966 Converting a slice of bytes to a string type yields 3967 a string whose successive bytes are the elements of the slice. 3968 3969 <pre> 3970 string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hell" 3971 string([]byte{}) // "" 3972 string([]byte(nil)) // "" 3973 3974 type MyBytes []byte 3975 string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hell" 3976 </pre> 3977 </li> 3978 3979 <li> 3980 Converting a slice of runes to a string type yields 3981 a string that is the concatenation of the individual rune values 3982 converted to strings. 3983 3984 <pre> 3985 string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "" 3986 string([]rune{}) // "" 3987 string([]rune(nil)) // "" 3988 3989 type MyRunes []rune 3990 string(MyRunes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "" 3991 </pre> 3992 </li> 3993 3994 <li> 3995 Converting a value of a string type to a slice of bytes type 3996 yields a slice whose successive elements are the bytes of the string. 3997 3998 <pre> 3999 []byte("hell") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} 4000 []byte("") // []byte{} 4001 4002 MyBytes("hell") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} 4003 </pre> 4004 </li> 4005 4006 <li> 4007 Converting a value of a string type to a slice of runes type 4008 yields a slice containing the individual Unicode code points of the string. 4009 4010 <pre> 4011 []rune(MyString("")) // []rune{0x767d, 0x9d6c, 0x7fd4} 4012 []rune("") // []rune{} 4013 4014 MyRunes("") // []rune{0x767d, 0x9d6c, 0x7fd4} 4015 </pre> 4016 </li> 4017 </ol> 4018 4019 4020 <h3 id="Constant_expressions">Constant expressions</h3> 4021 4022 <p> 4023 Constant expressions may contain only <a href="#Constants">constant</a> 4024 operands and are evaluated at compile time. 4025 </p> 4026 4027 <p> 4028 Untyped boolean, numeric, and string constants may be used as operands 4029 wherever it is legal to use an operand of boolean, numeric, or string type, 4030 respectively. 4031 Except for shift operations, if the operands of a binary operation are 4032 different kinds of untyped constants, the operation and, for non-boolean operations, the result use 4033 the kind that appears later in this list: integer, rune, floating-point, complex. 4034 For example, an untyped integer constant divided by an 4035 untyped complex constant yields an untyped complex constant. 4036 </p> 4037 4038 <p> 4039 A constant <a href="#Comparison_operators">comparison</a> always yields 4040 an untyped boolean constant. If the left operand of a constant 4041 <a href="#Operators">shift expression</a> is an untyped constant, the 4042 result is an integer constant; otherwise it is a constant of the same 4043 type as the left operand, which must be of 4044 <a href="#Numeric_types">integer type</a>. 4045 Applying all other operators to untyped constants results in an untyped 4046 constant of the same kind (that is, a boolean, integer, floating-point, 4047 complex, or string constant). 4048 </p> 4049 4050 <pre> 4051 const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant) 4052 const b = 15 / 4 // b == 3 (untyped integer constant) 4053 const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant) 4054 const float64 = 3/2 // == 1.0 (type float64, 3/2 is integer division) 4055 const float64 = 3/2. // == 1.5 (type float64, 3/2. is float division) 4056 const d = 1 << 3.0 // d == 8 (untyped integer constant) 4057 const e = 1.0 << 3 // e == 8 (untyped integer constant) 4058 const f = int32(1) << 33 // illegal (constant 8589934592 overflows int32) 4059 const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant) 4060 const h = "foo" > "bar" // h == true (untyped boolean constant) 4061 const j = true // j == true (untyped boolean constant) 4062 const k = 'w' + 1 // k == 'x' (untyped rune constant) 4063 const l = "hi" // l == "hi" (untyped string constant) 4064 const m = string(k) // m == "x" (type string) 4065 const = 1 - 0.707i // (untyped complex constant) 4066 const = + 2.0e-4 // (untyped complex constant) 4067 const = iota*1i - 1/1i // (untyped complex constant) 4068 </pre> 4069 4070 <p> 4071 Applying the built-in function <code>complex</code> to untyped 4072 integer, rune, or floating-point constants yields 4073 an untyped complex constant. 4074 </p> 4075 4076 <pre> 4077 const ic = complex(0, c) // ic == 3.75i (untyped complex constant) 4078 const i = complex(0, ) // i == 1i (type complex128) 4079 </pre> 4080 4081 <p> 4082 Constant expressions are always evaluated exactly; intermediate values and the 4083 constants themselves may require precision significantly larger than supported 4084 by any predeclared type in the language. The following are legal declarations: 4085 </p> 4086 4087 <pre> 4088 const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (untyped integer constant) 4089 const Four int8 = Huge >> 98 // Four == 4 (type int8) 4090 </pre> 4091 4092 <p> 4093 The divisor of a constant division or remainder operation must not be zero: 4094 </p> 4095 4096 <pre> 4097 3.14 / 0.0 // illegal: division by zero 4098 </pre> 4099 4100 <p> 4101 The values of <i>typed</i> constants must always be accurately representable as values 4102 of the constant type. The following constant expressions are illegal: 4103 </p> 4104 4105 <pre> 4106 uint(-1) // -1 cannot be represented as a uint 4107 int(3.14) // 3.14 cannot be represented as an int 4108 int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64 4109 Four * 300 // operand 300 cannot be represented as an int8 (type of Four) 4110 Four * 100 // product 400 cannot be represented as an int8 (type of Four) 4111 </pre> 4112 4113 <p> 4114 The mask used by the unary bitwise complement operator <code>^</code> matches 4115 the rule for non-constants: the mask is all 1s for unsigned constants 4116 and -1 for signed and untyped constants. 4117 </p> 4118 4119 <pre> 4120 ^1 // untyped integer constant, equal to -2 4121 uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8 4122 ^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE) 4123 int8(^1) // same as int8(-2) 4124 ^int8(1) // same as -1 ^ int8(1) = -2 4125 </pre> 4126 4127 <p> 4128 Implementation restriction: A compiler may use rounding while 4129 computing untyped floating-point or complex constant expressions; see 4130 the implementation restriction in the section 4131 on <a href="#Constants">constants</a>. This rounding may cause a 4132 floating-point constant expression to be invalid in an integer 4133 context, even if it would be integral when calculated using infinite 4134 precision, and vice versa. 4135 </p> 4136 4137 4138 <h3 id="Order_of_evaluation">Order of evaluation</h3> 4139 4140 <p> 4141 At package level, <a href="#Package_initialization">initialization dependencies</a> 4142 determine the evaluation order of individual initialization expressions in 4143 <a href="#Variable_declarations">variable declarations</a>. 4144 Otherwise, when evaluating the <a href="#Operands">operands</a> of an 4145 expression, assignment, or 4146 <a href="#Return_statements">return statement</a>, 4147 all function calls, method calls, and 4148 communication operations are evaluated in lexical left-to-right 4149 order. 4150 </p> 4151 4152 <p> 4153 For example, in the (function-local) assignment 4154 </p> 4155 <pre> 4156 y[f()], ok = g(h(), i()+x[j()], <-c), k() 4157 </pre> 4158 <p> 4159 the function calls and communication happen in the order 4160 <code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>, 4161 <code><-c</code>, <code>g()</code>, and <code>k()</code>. 4162 However, the order of those events compared to the evaluation 4163 and indexing of <code>x</code> and the evaluation 4164 of <code>y</code> is not specified. 4165 </p> 4166 4167 <pre> 4168 a := 1 4169 f := func() int { a++; return a } 4170 x := []int{a, f()} // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified 4171 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 4172 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 4173 </pre> 4174 4175 <p> 4176 At package level, initialization dependencies override the left-to-right rule 4177 for individual initialization expressions, but not for operands within each 4178 expression: 4179 </p> 4180 4181 <pre> 4182 var a, b, c = f() + v(), g(), sqr(u()) + v() 4183 4184 func f() int { return c } 4185 func g() int { return a } 4186 func sqr(x int) int { return x*x } 4187 4188 // functions u and v are independent of all other variables and functions 4189 </pre> 4190 4191 <p> 4192 The function calls happen in the order 4193 <code>u()</code>, <code>sqr()</code>, <code>v()</code>, 4194 <code>f()</code>, <code>v()</code>, and <code>g()</code>. 4195 </p> 4196 4197 <p> 4198 Floating-point operations within a single expression are evaluated according to 4199 the associativity of the operators. Explicit parentheses affect the evaluation 4200 by overriding the default associativity. 4201 In the expression <code>x + (y + z)</code> the addition <code>y + z</code> 4202 is performed before adding <code>x</code>. 4203 </p> 4204 4205 <h2 id="Statements">Statements</h2> 4206 4207 <p> 4208 Statements control execution. 4209 </p> 4210 4211 <pre class="ebnf"> 4212 Statement = 4213 Declaration | LabeledStmt | SimpleStmt | 4214 GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt | 4215 FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt | 4216 DeferStmt . 4217 4218 SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl . 4219 </pre> 4220 4221 <h3 id="Terminating_statements">Terminating statements</h3> 4222 4223 <p> 4224 A terminating statement is one of the following: 4225 </p> 4226 4227 <ol> 4228 <li> 4229 A <a href="#Return_statements">"return"</a> or 4230 <a href="#Goto_statements">"goto"</a> statement. 4231 <!-- ul below only for regular layout --> 4232 <ul> </ul> 4233 </li> 4234 4235 <li> 4236 A call to the built-in function 4237 <a href="#Handling_panics"><code>panic</code></a>. 4238 <!-- ul below only for regular layout --> 4239 <ul> </ul> 4240 </li> 4241 4242 <li> 4243 A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement. 4244 <!-- ul below only for regular layout --> 4245 <ul> </ul> 4246 </li> 4247 4248 <li> 4249 An <a href="#If_statements">"if" statement</a> in which: 4250 <ul> 4251 <li>the "else" branch is present, and</li> 4252 <li>both branches are terminating statements.</li> 4253 </ul> 4254 </li> 4255 4256 <li> 4257 A <a href="#For_statements">"for" statement</a> in which: 4258 <ul> 4259 <li>there are no "break" statements referring to the "for" statement, and</li> 4260 <li>the loop condition is absent.</li> 4261 </ul> 4262 </li> 4263 4264 <li> 4265 A <a href="#Switch_statements">"switch" statement</a> in which: 4266 <ul> 4267 <li>there are no "break" statements referring to the "switch" statement,</li> 4268 <li>there is a default case, and</li> 4269 <li>the statement lists in each case, including the default, end in a terminating 4270 statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough" 4271 statement</a>.</li> 4272 </ul> 4273 </li> 4274 4275 <li> 4276 A <a href="#Select_statements">"select" statement</a> in which: 4277 <ul> 4278 <li>there are no "break" statements referring to the "select" statement, and</li> 4279 <li>the statement lists in each case, including the default if present, 4280 end in a terminating statement.</li> 4281 </ul> 4282 </li> 4283 4284 <li> 4285 A <a href="#Labeled_statements">labeled statement</a> labeling 4286 a terminating statement. 4287 </li> 4288 </ol> 4289 4290 <p> 4291 All other statements are not terminating. 4292 </p> 4293 4294 <p> 4295 A <a href="#Blocks">statement list</a> ends in a terminating statement if the list 4296 is not empty and its final non-empty statement is terminating. 4297 </p> 4298 4299 4300 <h3 id="Empty_statements">Empty statements</h3> 4301 4302 <p> 4303 The empty statement does nothing. 4304 </p> 4305 4306 <pre class="ebnf"> 4307 EmptyStmt = . 4308 </pre> 4309 4310 4311 <h3 id="Labeled_statements">Labeled statements</h3> 4312 4313 <p> 4314 A labeled statement may be the target of a <code>goto</code>, 4315 <code>break</code> or <code>continue</code> statement. 4316 </p> 4317 4318 <pre class="ebnf"> 4319 LabeledStmt = Label ":" Statement . 4320 Label = identifier . 4321 </pre> 4322 4323 <pre> 4324 Error: log.Panic("error encountered") 4325 </pre> 4326 4327 4328 <h3 id="Expression_statements">Expression statements</h3> 4329 4330 <p> 4331 With the exception of specific built-in functions, 4332 function and method <a href="#Calls">calls</a> and 4333 <a href="#Receive_operator">receive operations</a> 4334 can appear in statement context. Such statements may be parenthesized. 4335 </p> 4336 4337 <pre class="ebnf"> 4338 ExpressionStmt = Expression . 4339 </pre> 4340 4341 <p> 4342 The following built-in functions are not permitted in statement context: 4343 </p> 4344 4345 <pre> 4346 append cap complex imag len make new real 4347 unsafe.Alignof unsafe.Offsetof unsafe.Sizeof 4348 </pre> 4349 4350 <pre> 4351 h(x+y) 4352 f.Close() 4353 <-ch 4354 (<-ch) 4355 len("foo") // illegal if len is the built-in function 4356 </pre> 4357 4358 4359 <h3 id="Send_statements">Send statements</h3> 4360 4361 <p> 4362 A send statement sends a value on a channel. 4363 The channel expression must be of <a href="#Channel_types">channel type</a>, 4364 the channel direction must permit send operations, 4365 and the type of the value to be sent must be <a href="#Assignability">assignable</a> 4366 to the channel's element type. 4367 </p> 4368 4369 <pre class="ebnf"> 4370 SendStmt = Channel "<-" Expression . 4371 Channel = Expression . 4372 </pre> 4373 4374 <p> 4375 Both the channel and the value expression are evaluated before communication 4376 begins. Communication blocks until the send can proceed. 4377 A send on an unbuffered channel can proceed if a receiver is ready. 4378 A send on a buffered channel can proceed if there is room in the buffer. 4379 A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>. 4380 A send on a <code>nil</code> channel blocks forever. 4381 </p> 4382 4383 <pre> 4384 ch <- 3 // send value 3 to channel ch 4385 </pre> 4386 4387 4388 <h3 id="IncDec_statements">IncDec statements</h3> 4389 4390 <p> 4391 The "++" and "--" statements increment or decrement their operands 4392 by the untyped <a href="#Constants">constant</a> <code>1</code>. 4393 As with an assignment, the operand must be <a href="#Address_operators">addressable</a> 4394 or a map index expression. 4395 </p> 4396 4397 <pre class="ebnf"> 4398 IncDecStmt = Expression ( "++" | "--" ) . 4399 </pre> 4400 4401 <p> 4402 The following <a href="#Assignments">assignment statements</a> are semantically 4403 equivalent: 4404 </p> 4405 4406 <pre class="grammar"> 4407 IncDec statement Assignment 4408 x++ x += 1 4409 x-- x -= 1 4410 </pre> 4411 4412 4413 <h3 id="Assignments">Assignments</h3> 4414 4415 <pre class="ebnf"> 4416 Assignment = ExpressionList assign_op ExpressionList . 4417 4418 assign_op = [ add_op | mul_op ] "=" . 4419 </pre> 4420 4421 <p> 4422 Each left-hand side operand must be <a href="#Address_operators">addressable</a>, 4423 a map index expression, or (for <code>=</code> assignments only) the 4424 <a href="#Blank_identifier">blank identifier</a>. 4425 Operands may be parenthesized. 4426 </p> 4427 4428 <pre> 4429 x = 1 4430 *p = f() 4431 a[i] = 23 4432 (k) = <-ch // same as: k = <-ch 4433 </pre> 4434 4435 <p> 4436 An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code> 4437 <code>y</code> where <i>op</i> is a binary arithmetic operation is equivalent 4438 to <code>x</code> <code>=</code> <code>x</code> <i>op</i> 4439 <code>(y)</code> but evaluates <code>x</code> 4440 only once. The <i>op</i><code>=</code> construct is a single token. 4441 In assignment operations, both the left- and right-hand expression lists 4442 must contain exactly one single-valued expression, and the left-hand 4443 expression must not be the blank identifier. 4444 </p> 4445 4446 <pre> 4447 a[i] <<= 2 4448 i &^= 1<<n 4449 </pre> 4450 4451 <p> 4452 A tuple assignment assigns the individual elements of a multi-valued 4453 operation to a list of variables. There are two forms. In the 4454 first, the right hand operand is a single multi-valued expression 4455 such as a function call, a <a href="#Channel_types">channel</a> or 4456 <a href="#Map_types">map</a> operation, or a <a href="#Type_assertions">type assertion</a>. 4457 The number of operands on the left 4458 hand side must match the number of values. For instance, if 4459 <code>f</code> is a function returning two values, 4460 </p> 4461 4462 <pre> 4463 x, y = f() 4464 </pre> 4465 4466 <p> 4467 assigns the first value to <code>x</code> and the second to <code>y</code>. 4468 In the second form, the number of operands on the left must equal the number 4469 of expressions on the right, each of which must be single-valued, and the 4470 <i>n</i>th expression on the right is assigned to the <i>n</i>th 4471 operand on the left: 4472 </p> 4473 4474 <pre> 4475 one, two, three = '', '', '' 4476 </pre> 4477 4478 <p> 4479 The <a href="#Blank_identifier">blank identifier</a> provides a way to 4480 ignore right-hand side values in an assignment: 4481 </p> 4482 4483 <pre> 4484 _ = x // evaluate x but ignore it 4485 x, _ = f() // evaluate f() but ignore second result value 4486 </pre> 4487 4488 <p> 4489 The assignment proceeds in two phases. 4490 First, the operands of <a href="#Index_expressions">index expressions</a> 4491 and <a href="#Address_operators">pointer indirections</a> 4492 (including implicit pointer indirections in <a href="#Selectors">selectors</a>) 4493 on the left and the expressions on the right are all 4494 <a href="#Order_of_evaluation">evaluated in the usual order</a>. 4495 Second, the assignments are carried out in left-to-right order. 4496 </p> 4497 4498 <pre> 4499 a, b = b, a // exchange a and b 4500 4501 x := []int{1, 2, 3} 4502 i := 0 4503 i, x[i] = 1, 2 // set i = 1, x[0] = 2 4504 4505 i = 0 4506 x[i], i = 2, 1 // set x[0] = 2, i = 1 4507 4508 x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end) 4509 4510 x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5. 4511 4512 type Point struct { x, y int } 4513 var p *Point 4514 x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7 4515 4516 i = 2 4517 x = []int{3, 5, 7} 4518 for i, x[i] = range x { // set i, x[2] = 0, x[0] 4519 break 4520 } 4521 // after this loop, i == 0 and x == []int{3, 5, 3} 4522 </pre> 4523 4524 <p> 4525 In assignments, each value must be <a href="#Assignability">assignable</a> 4526 to the type of the operand to which it is assigned, with the following special cases: 4527 </p> 4528 4529 <ol> 4530 <li> 4531 Any typed value may be assigned to the blank identifier. 4532 </li> 4533 4534 <li> 4535 If an untyped constant 4536 is assigned to a variable of interface type or the blank identifier, 4537 the constant is first <a href="#Conversions">converted</a> to its 4538 <a href="#Constants">default type</a>. 4539 </li> 4540 4541 <li> 4542 If an untyped boolean value is assigned to a variable of interface type or 4543 the blank identifier, it is first converted to type <code>bool</code>. 4544 </li> 4545 </ol> 4546 4547 <h3 id="If_statements">If statements</h3> 4548 4549 <p> 4550 "If" statements specify the conditional execution of two branches 4551 according to the value of a boolean expression. If the expression 4552 evaluates to true, the "if" branch is executed, otherwise, if 4553 present, the "else" branch is executed. 4554 </p> 4555 4556 <pre class="ebnf"> 4557 IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] . 4558 </pre> 4559 4560 <pre> 4561 if x > max { 4562 x = max 4563 } 4564 </pre> 4565 4566 <p> 4567 The expression may be preceded by a simple statement, which 4568 executes before the expression is evaluated. 4569 </p> 4570 4571 <pre> 4572 if x := f(); x < y { 4573 return x 4574 } else if x > z { 4575 return z 4576 } else { 4577 return y 4578 } 4579 </pre> 4580 4581 4582 <h3 id="Switch_statements">Switch statements</h3> 4583 4584 <p> 4585 "Switch" statements provide multi-way execution. 4586 An expression or type specifier is compared to the "cases" 4587 inside the "switch" to determine which branch 4588 to execute. 4589 </p> 4590 4591 <pre class="ebnf"> 4592 SwitchStmt = ExprSwitchStmt | TypeSwitchStmt . 4593 </pre> 4594 4595 <p> 4596 There are two forms: expression switches and type switches. 4597 In an expression switch, the cases contain expressions that are compared 4598 against the value of the switch expression. 4599 In a type switch, the cases contain types that are compared against the 4600 type of a specially annotated switch expression. 4601 The switch expression is evaluated exactly once in a switch statement. 4602 </p> 4603 4604 <h4 id="Expression_switches">Expression switches</h4> 4605 4606 <p> 4607 In an expression switch, 4608 the switch expression is evaluated and 4609 the case expressions, which need not be constants, 4610 are evaluated left-to-right and top-to-bottom; the first one that equals the 4611 switch expression 4612 triggers execution of the statements of the associated case; 4613 the other cases are skipped. 4614 If no case matches and there is a "default" case, 4615 its statements are executed. 4616 There can be at most one default case and it may appear anywhere in the 4617 "switch" statement. 4618 A missing switch expression is equivalent to the boolean value 4619 <code>true</code>. 4620 </p> 4621 4622 <pre class="ebnf"> 4623 ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" . 4624 ExprCaseClause = ExprSwitchCase ":" StatementList . 4625 ExprSwitchCase = "case" ExpressionList | "default" . 4626 </pre> 4627 4628 <p> 4629 If the switch expression evaluates to an untyped constant, it is first 4630 <a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>; 4631 if it is an untyped boolean value, it is first converted to type <code>bool</code>. 4632 The predeclared untyped value <code>nil</code> cannot be used as a switch expression. 4633 </p> 4634 4635 <p> 4636 If a case expression is untyped, it is first <a href="#Conversions">converted</a> 4637 to the type of the switch expression. 4638 For each (possibly converted) case expression <code>x</code> and the value <code>t</code> 4639 of the switch expression, <code>x == t</code> must be a valid <a href="#Comparison_operators">comparison</a>. 4640 </p> 4641 4642 <p> 4643 In other words, the switch expression is treated as if it were used to declare and 4644 initialize a temporary variable <code>t</code> without explicit type; it is that 4645 value of <code>t</code> against which each case expression <code>x</code> is tested 4646 for equality. 4647 </p> 4648 4649 <p> 4650 In a case or default clause, the last non-empty statement 4651 may be a (possibly <a href="#Labeled_statements">labeled</a>) 4652 <a href="#Fallthrough_statements">"fallthrough" statement</a> to 4653 indicate that control should flow from the end of this clause to 4654 the first statement of the next clause. 4655 Otherwise control flows to the end of the "switch" statement. 4656 A "fallthrough" statement may appear as the last statement of all 4657 but the last clause of an expression switch. 4658 </p> 4659 4660 <p> 4661 The switch expression may be preceded by a simple statement, which 4662 executes before the expression is evaluated. 4663 </p> 4664 4665 <pre> 4666 switch tag { 4667 default: s3() 4668 case 0, 1, 2, 3: s1() 4669 case 4, 5, 6, 7: s2() 4670 } 4671 4672 switch x := f(); { // missing switch expression means "true" 4673 case x < 0: return -x 4674 default: return x 4675 } 4676 4677 switch { 4678 case x < y: f1() 4679 case x < z: f2() 4680 case x == 4: f3() 4681 } 4682 </pre> 4683 4684 <p> 4685 Implementation restriction: A compiler may disallow multiple case 4686 expressions evaluating to the same constant. 4687 For instance, the current compilers disallow duplicate integer, 4688 floating point, or string constants in case expressions. 4689 </p> 4690 4691 <h4 id="Type_switches">Type switches</h4> 4692 4693 <p> 4694 A type switch compares types rather than values. It is otherwise similar 4695 to an expression switch. It is marked by a special switch expression that 4696 has the form of a <a href="#Type_assertions">type assertion</a> 4697 using the reserved word <code>type</code> rather than an actual type: 4698 </p> 4699 4700 <pre> 4701 switch x.(type) { 4702 // cases 4703 } 4704 </pre> 4705 4706 <p> 4707 Cases then match actual types <code>T</code> against the dynamic type of the 4708 expression <code>x</code>. As with type assertions, <code>x</code> must be of 4709 <a href="#Interface_types">interface type</a>, and each non-interface type 4710 <code>T</code> listed in a case must implement the type of <code>x</code>. 4711 The types listed in the cases of a type switch must all be 4712 <a href="#Type_identity">different</a>. 4713 </p> 4714 4715 <pre class="ebnf"> 4716 TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" . 4717 TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" . 4718 TypeCaseClause = TypeSwitchCase ":" StatementList . 4719 TypeSwitchCase = "case" TypeList | "default" . 4720 TypeList = Type { "," Type } . 4721 </pre> 4722 4723 <p> 4724 The TypeSwitchGuard may include a 4725 <a href="#Short_variable_declarations">short variable declaration</a>. 4726 When that form is used, the variable is declared at the end of the 4727 TypeSwitchCase in the <a href="#Blocks">implicit block</a> of each clause. 4728 In clauses with a case listing exactly one type, the variable 4729 has that type; otherwise, the variable has the type of the expression 4730 in the TypeSwitchGuard. 4731 </p> 4732 4733 <p> 4734 The type in a case may be <a href="#Predeclared_identifiers"><code>nil</code></a>; 4735 that case is used when the expression in the TypeSwitchGuard 4736 is a <code>nil</code> interface value. 4737 There may be at most one <code>nil</code> case. 4738 </p> 4739 4740 <p> 4741 Given an expression <code>x</code> of type <code>interface{}</code>, 4742 the following type switch: 4743 </p> 4744 4745 <pre> 4746 switch i := x.(type) { 4747 case nil: 4748 printString("x is nil") // type of i is type of x (interface{}) 4749 case int: 4750 printInt(i) // type of i is int 4751 case float64: 4752 printFloat64(i) // type of i is float64 4753 case func(int) float64: 4754 printFunction(i) // type of i is func(int) float64 4755 case bool, string: 4756 printString("type is bool or string") // type of i is type of x (interface{}) 4757 default: 4758 printString("don't know the type") // type of i is type of x (interface{}) 4759 } 4760 </pre> 4761 4762 <p> 4763 could be rewritten: 4764 </p> 4765 4766 <pre> 4767 v := x // x is evaluated exactly once 4768 if v == nil { 4769 i := v // type of i is type of x (interface{}) 4770 printString("x is nil") 4771 } else if i, isInt := v.(int); isInt { 4772 printInt(i) // type of i is int 4773 } else if i, isFloat64 := v.(float64); isFloat64 { 4774 printFloat64(i) // type of i is float64 4775 } else if i, isFunc := v.(func(int) float64); isFunc { 4776 printFunction(i) // type of i is func(int) float64 4777 } else { 4778 _, isBool := v.(bool) 4779 _, isString := v.(string) 4780 if isBool || isString { 4781 i := v // type of i is type of x (interface{}) 4782 printString("type is bool or string") 4783 } else { 4784 i := v // type of i is type of x (interface{}) 4785 printString("don't know the type") 4786 } 4787 } 4788 </pre> 4789 4790 <p> 4791 The type switch guard may be preceded by a simple statement, which 4792 executes before the guard is evaluated. 4793 </p> 4794 4795 <p> 4796 The "fallthrough" statement is not permitted in a type switch. 4797 </p> 4798 4799 <h3 id="For_statements">For statements</h3> 4800 4801 <p> 4802 A "for" statement specifies repeated execution of a block. There are three forms: 4803 The iteration may be controlled by a single condition, a "for" clause, or a "range" clause. 4804 </p> 4805 4806 <pre class="ebnf"> 4807 ForStmt = "for" [ Condition | ForClause | RangeClause ] Block . 4808 Condition = Expression . 4809 </pre> 4810 4811 <h4 id="For_condition">For statements with single condition</h4> 4812 4813 <p> 4814 In its simplest form, a "for" statement specifies the repeated execution of 4815 a block as long as a boolean condition evaluates to true. 4816 The condition is evaluated before each iteration. 4817 If the condition is absent, it is equivalent to the boolean value 4818 <code>true</code>. 4819 </p> 4820 4821 <pre> 4822 for a < b { 4823 a *= 2 4824 } 4825 </pre> 4826 4827 <h4 id="For_clause">For statements with <code>for</code> clause</h4> 4828 4829 <p> 4830 A "for" statement with a ForClause is also controlled by its condition, but 4831 additionally it may specify an <i>init</i> 4832 and a <i>post</i> statement, such as an assignment, 4833 an increment or decrement statement. The init statement may be a 4834 <a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not. 4835 Variables declared by the init statement are re-used in each iteration. 4836 </p> 4837 4838 <pre class="ebnf"> 4839 ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] . 4840 InitStmt = SimpleStmt . 4841 PostStmt = SimpleStmt . 4842 </pre> 4843 4844 <pre> 4845 for i := 0; i < 10; i++ { 4846 f(i) 4847 } 4848 </pre> 4849 4850 <p> 4851 If non-empty, the init statement is executed once before evaluating the 4852 condition for the first iteration; 4853 the post statement is executed after each execution of the block (and 4854 only if the block was executed). 4855 Any element of the ForClause may be empty but the 4856 <a href="#Semicolons">semicolons</a> are 4857 required unless there is only a condition. 4858 If the condition is absent, it is equivalent to the boolean value 4859 <code>true</code>. 4860 </p> 4861 4862 <pre> 4863 for cond { S() } is the same as for ; cond ; { S() } 4864 for { S() } is the same as for true { S() } 4865 </pre> 4866 4867 <h4 id="For_range">For statements with <code>range</code> clause</h4> 4868 4869 <p> 4870 A "for" statement with a "range" clause 4871 iterates through all entries of an array, slice, string or map, 4872 or values received on a channel. For each entry it assigns <i>iteration values</i> 4873 to corresponding <i>iteration variables</i> if present and then executes the block. 4874 </p> 4875 4876 <pre class="ebnf"> 4877 RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression . 4878 </pre> 4879 4880 <p> 4881 The expression on the right in the "range" clause is called the <i>range expression</i>, 4882 which may be an array, pointer to an array, slice, string, map, or channel permitting 4883 <a href="#Receive_operator">receive operations</a>. 4884 As with an assignment, if present the operands on the left must be 4885 <a href="#Address_operators">addressable</a> or map index expressions; they 4886 denote the iteration variables. If the range expression is a channel, at most 4887 one iteration variable is permitted, otherwise there may be up to two. 4888 If the last iteration variable is the <a href="#Blank_identifier">blank identifier</a>, 4889 the range clause is equivalent to the same clause without that identifier. 4890 </p> 4891 4892 <p> 4893 The range expression is evaluated once before beginning the loop, 4894 with one exception: if the range expression is an array or a pointer to an array 4895 and at most one iteration variable is present, only the range expression's 4896 length is evaluated; if that length is constant, 4897 <a href="#Length_and_capacity">by definition</a> 4898 the range expression itself will not be evaluated. 4899 </p> 4900 4901 <p> 4902 Function calls on the left are evaluated once per iteration. 4903 For each iteration, iteration values are produced as follows 4904 if the respective iteration variables are present: 4905 </p> 4906 4907 <pre class="grammar"> 4908 Range expression 1st value 2nd value 4909 4910 array or slice a [n]E, *[n]E, or []E index i int a[i] E 4911 string s string type index i int see below rune 4912 map m map[K]V key k K m[k] V 4913 channel c chan E, <-chan E element e E 4914 </pre> 4915 4916 <ol> 4917 <li> 4918 For an array, pointer to array, or slice value <code>a</code>, the index iteration 4919 values are produced in increasing order, starting at element index 0. 4920 If at most one iteration variable is present, the range loop produces 4921 iteration values from 0 up to <code>len(a)-1</code> and does not index into the array 4922 or slice itself. For a <code>nil</code> slice, the number of iterations is 0. 4923 </li> 4924 4925 <li> 4926 For a string value, the "range" clause iterates over the Unicode code points 4927 in the string starting at byte index 0. On successive iterations, the index value will be the 4928 index of the first byte of successive UTF-8-encoded code points in the string, 4929 and the second value, of type <code>rune</code>, will be the value of 4930 the corresponding code point. If the iteration encounters an invalid 4931 UTF-8 sequence, the second value will be <code>0xFFFD</code>, 4932 the Unicode replacement character, and the next iteration will advance 4933 a single byte in the string. 4934 </li> 4935 4936 <li> 4937 The iteration order over maps is not specified 4938 and is not guaranteed to be the same from one iteration to the next. 4939 If map entries that have not yet been reached are removed during iteration, 4940 the corresponding iteration values will not be produced. If map entries are 4941 created during iteration, that entry may be produced during the iteration or 4942 may be skipped. The choice may vary for each entry created and from one 4943 iteration to the next. 4944 If the map is <code>nil</code>, the number of iterations is 0. 4945 </li> 4946 4947 <li> 4948 For channels, the iteration values produced are the successive values sent on 4949 the channel until the channel is <a href="#Close">closed</a>. If the channel 4950 is <code>nil</code>, the range expression blocks forever. 4951 </li> 4952 </ol> 4953 4954 <p> 4955 The iteration values are assigned to the respective 4956 iteration variables as in an <a href="#Assignments">assignment statement</a>. 4957 </p> 4958 4959 <p> 4960 The iteration variables may be declared by the "range" clause using a form of 4961 <a href="#Short_variable_declarations">short variable declaration</a> 4962 (<code>:=</code>). 4963 In this case their types are set to the types of the respective iteration values 4964 and their <a href="#Declarations_and_scope">scope</a> is the block of the "for" 4965 statement; they are re-used in each iteration. 4966 If the iteration variables are declared outside the "for" statement, 4967 after execution their values will be those of the last iteration. 4968 </p> 4969 4970 <pre> 4971 var testdata *struct { 4972 a *[7]int 4973 } 4974 for i, _ := range testdata.a { 4975 // testdata.a is never evaluated; len(testdata.a) is constant 4976 // i ranges from 0 to 6 4977 f(i) 4978 } 4979 4980 var a [10]string 4981 for i, s := range a { 4982 // type of i is int 4983 // type of s is string 4984 // s == a[i] 4985 g(i, s) 4986 } 4987 4988 var key string 4989 var val interface {} // value type of m is assignable to val 4990 m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6} 4991 for key, val = range m { 4992 h(key, val) 4993 } 4994 // key == last map key encountered in iteration 4995 // val == map[key] 4996 4997 var ch chan Work = producer() 4998 for w := range ch { 4999 doWork(w) 5000 } 5001 5002 // empty a channel 5003 for range ch {} 5004 </pre> 5005 5006 5007 <h3 id="Go_statements">Go statements</h3> 5008 5009 <p> 5010 A "go" statement starts the execution of a function call 5011 as an independent concurrent thread of control, or <i>goroutine</i>, 5012 within the same address space. 5013 </p> 5014 5015 <pre class="ebnf"> 5016 GoStmt = "go" Expression . 5017 </pre> 5018 5019 <p> 5020 The expression must be a function or method call; it cannot be parenthesized. 5021 Calls of built-in functions are restricted as for 5022 <a href="#Expression_statements">expression statements</a>. 5023 </p> 5024 5025 <p> 5026 The function value and parameters are 5027 <a href="#Calls">evaluated as usual</a> 5028 in the calling goroutine, but 5029 unlike with a regular call, program execution does not wait 5030 for the invoked function to complete. 5031 Instead, the function begins executing independently 5032 in a new goroutine. 5033 When the function terminates, its goroutine also terminates. 5034 If the function has any return values, they are discarded when the 5035 function completes. 5036 </p> 5037 5038 <pre> 5039 go Server() 5040 go func(ch chan<- bool) { for { sleep(10); ch <- true; }} (c) 5041 </pre> 5042 5043 5044 <h3 id="Select_statements">Select statements</h3> 5045 5046 <p> 5047 A "select" statement chooses which of a set of possible 5048 <a href="#Send_statements">send</a> or 5049 <a href="#Receive_operator">receive</a> 5050 operations will proceed. 5051 It looks similar to a 5052 <a href="#Switch_statements">"switch"</a> statement but with the 5053 cases all referring to communication operations. 5054 </p> 5055 5056 <pre class="ebnf"> 5057 SelectStmt = "select" "{" { CommClause } "}" . 5058 CommClause = CommCase ":" StatementList . 5059 CommCase = "case" ( SendStmt | RecvStmt ) | "default" . 5060 RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr . 5061 RecvExpr = Expression . 5062 </pre> 5063 5064 <p> 5065 A case with a RecvStmt may assign the result of a RecvExpr to one or 5066 two variables, which may be declared using a 5067 <a href="#Short_variable_declarations">short variable declaration</a>. 5068 The RecvExpr must be a (possibly parenthesized) receive operation. 5069 There can be at most one default case and it may appear anywhere 5070 in the list of cases. 5071 </p> 5072 5073 <p> 5074 Execution of a "select" statement proceeds in several steps: 5075 </p> 5076 5077 <ol> 5078 <li> 5079 For all the cases in the statement, the channel operands of receive operations 5080 and the channel and right-hand-side expressions of send statements are 5081 evaluated exactly once, in source order, upon entering the "select" statement. 5082 The result is a set of channels to receive from or send to, 5083 and the corresponding values to send. 5084 Any side effects in that evaluation will occur irrespective of which (if any) 5085 communication operation is selected to proceed. 5086 Expressions on the left-hand side of a RecvStmt with a short variable declaration 5087 or assignment are not yet evaluated. 5088 </li> 5089 5090 <li> 5091 If one or more of the communications can proceed, 5092 a single one that can proceed is chosen via a uniform pseudo-random selection. 5093 Otherwise, if there is a default case, that case is chosen. 5094 If there is no default case, the "select" statement blocks until 5095 at least one of the communications can proceed. 5096 </li> 5097 5098 <li> 5099 Unless the selected case is the default case, the respective communication 5100 operation is executed. 5101 </li> 5102 5103 <li> 5104 If the selected case is a RecvStmt with a short variable declaration or 5105 an assignment, the left-hand side expressions are evaluated and the 5106 received value (or values) are assigned. 5107 </li> 5108 5109 <li> 5110 The statement list of the selected case is executed. 5111 </li> 5112 </ol> 5113 5114 <p> 5115 Since communication on <code>nil</code> channels can never proceed, 5116 a select with only <code>nil</code> channels and no default case blocks forever. 5117 </p> 5118 5119 <pre> 5120 var a []int 5121 var c, c1, c2, c3, c4 chan int 5122 var i1, i2 int 5123 select { 5124 case i1 = <-c1: 5125 print("received ", i1, " from c1\n") 5126 case c2 <- i2: 5127 print("sent ", i2, " to c2\n") 5128 case i3, ok := (<-c3): // same as: i3, ok := <-c3 5129 if ok { 5130 print("received ", i3, " from c3\n") 5131 } else { 5132 print("c3 is closed\n") 5133 } 5134 case a[f()] = <-c4: 5135 // same as: 5136 // case t := <-c4 5137 // a[f()] = t 5138 default: 5139 print("no communication\n") 5140 } 5141 5142 for { // send random sequence of bits to c 5143 select { 5144 case c <- 0: // note: no statement, no fallthrough, no folding of cases 5145 case c <- 1: 5146 } 5147 } 5148 5149 select {} // block forever 5150 </pre> 5151 5152 5153 <h3 id="Return_statements">Return statements</h3> 5154 5155 <p> 5156 A "return" statement in a function <code>F</code> terminates the execution 5157 of <code>F</code>, and optionally provides one or more result values. 5158 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code> 5159 are executed before <code>F</code> returns to its caller. 5160 </p> 5161 5162 <pre class="ebnf"> 5163 ReturnStmt = "return" [ ExpressionList ] . 5164 </pre> 5165 5166 <p> 5167 In a function without a result type, a "return" statement must not 5168 specify any result values. 5169 </p> 5170 <pre> 5171 func noResult() { 5172 return 5173 } 5174 </pre> 5175 5176 <p> 5177 There are three ways to return values from a function with a result 5178 type: 5179 </p> 5180 5181 <ol> 5182 <li>The return value or values may be explicitly listed 5183 in the "return" statement. Each expression must be single-valued 5184 and <a href="#Assignability">assignable</a> 5185 to the corresponding element of the function's result type. 5186 <pre> 5187 func simpleF() int { 5188 return 2 5189 } 5190 5191 func complexF1() (re float64, im float64) { 5192 return -7.0, -4.0 5193 } 5194 </pre> 5195 </li> 5196 <li>The expression list in the "return" statement may be a single 5197 call to a multi-valued function. The effect is as if each value 5198 returned from that function were assigned to a temporary 5199 variable with the type of the respective value, followed by a 5200 "return" statement listing these variables, at which point the 5201 rules of the previous case apply. 5202 <pre> 5203 func complexF2() (re float64, im float64) { 5204 return complexF1() 5205 } 5206 </pre> 5207 </li> 5208 <li>The expression list may be empty if the function's result 5209 type specifies names for its <a href="#Function_types">result parameters</a>. 5210 The result parameters act as ordinary local variables 5211 and the function may assign values to them as necessary. 5212 The "return" statement returns the values of these variables. 5213 <pre> 5214 func complexF3() (re float64, im float64) { 5215 re = 7.0 5216 im = 4.0 5217 return 5218 } 5219 5220 func (devnull) Write(p []byte) (n int, _ error) { 5221 n = len(p) 5222 return 5223 } 5224 </pre> 5225 </li> 5226 </ol> 5227 5228 <p> 5229 Regardless of how they are declared, all the result values are initialized to 5230 the <a href="#The_zero_value">zero values</a> for their type upon entry to the 5231 function. A "return" statement that specifies results sets the result parameters before 5232 any deferred functions are executed. 5233 </p> 5234 5235 <p> 5236 Implementation restriction: A compiler may disallow an empty expression list 5237 in a "return" statement if a different entity (constant, type, or variable) 5238 with the same name as a result parameter is in 5239 <a href="#Declarations_and_scope">scope</a> at the place of the return. 5240 </p> 5241 5242 <pre> 5243 func f(n int) (res int, err error) { 5244 if _, err := f(n-1); err != nil { 5245 return // invalid return statement: err is shadowed 5246 } 5247 return 5248 } 5249 </pre> 5250 5251 <h3 id="Break_statements">Break statements</h3> 5252 5253 <p> 5254 A "break" statement terminates execution of the innermost 5255 <a href="#For_statements">"for"</a>, 5256 <a href="#Switch_statements">"switch"</a>, or 5257 <a href="#Select_statements">"select"</a> statement 5258 within the same function. 5259 </p> 5260 5261 <pre class="ebnf"> 5262 BreakStmt = "break" [ Label ] . 5263 </pre> 5264 5265 <p> 5266 If there is a label, it must be that of an enclosing 5267 "for", "switch", or "select" statement, 5268 and that is the one whose execution terminates. 5269 </p> 5270 5271 <pre> 5272 OuterLoop: 5273 for i = 0; i < n; i++ { 5274 for j = 0; j < m; j++ { 5275 switch a[i][j] { 5276 case nil: 5277 state = Error 5278 break OuterLoop 5279 case item: 5280 state = Found 5281 break OuterLoop 5282 } 5283 } 5284 } 5285 </pre> 5286 5287 <h3 id="Continue_statements">Continue statements</h3> 5288 5289 <p> 5290 A "continue" statement begins the next iteration of the 5291 innermost <a href="#For_statements">"for" loop</a> at its post statement. 5292 The "for" loop must be within the same function. 5293 </p> 5294 5295 <pre class="ebnf"> 5296 ContinueStmt = "continue" [ Label ] . 5297 </pre> 5298 5299 <p> 5300 If there is a label, it must be that of an enclosing 5301 "for" statement, and that is the one whose execution 5302 advances. 5303 </p> 5304 5305 <pre> 5306 RowLoop: 5307 for y, row := range rows { 5308 for x, data := range row { 5309 if data == endOfRow { 5310 continue RowLoop 5311 } 5312 row[x] = data + bias(x, y) 5313 } 5314 } 5315 </pre> 5316 5317 <h3 id="Goto_statements">Goto statements</h3> 5318 5319 <p> 5320 A "goto" statement transfers control to the statement with the corresponding label 5321 within the same function. 5322 </p> 5323 5324 <pre class="ebnf"> 5325 GotoStmt = "goto" Label . 5326 </pre> 5327 5328 <pre> 5329 goto Error 5330 </pre> 5331 5332 <p> 5333 Executing the "goto" statement must not cause any variables to come into 5334 <a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto. 5335 For instance, this example: 5336 </p> 5337 5338 <pre> 5339 goto L // BAD 5340 v := 3 5341 L: 5342 </pre> 5343 5344 <p> 5345 is erroneous because the jump to label <code>L</code> skips 5346 the creation of <code>v</code>. 5347 </p> 5348 5349 <p> 5350 A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block. 5351 For instance, this example: 5352 </p> 5353 5354 <pre> 5355 if n%2 == 1 { 5356 goto L1 5357 } 5358 for n > 0 { 5359 f() 5360 n-- 5361 L1: 5362 f() 5363 n-- 5364 } 5365 </pre> 5366 5367 <p> 5368 is erroneous because the label <code>L1</code> is inside 5369 the "for" statement's block but the <code>goto</code> is not. 5370 </p> 5371 5372 <h3 id="Fallthrough_statements">Fallthrough statements</h3> 5373 5374 <p> 5375 A "fallthrough" statement transfers control to the first statement of the 5376 next case clause in an <a href="#Expression_switches">expression "switch" statement</a>. 5377 It may be used only as the final non-empty statement in such a clause. 5378 </p> 5379 5380 <pre class="ebnf"> 5381 FallthroughStmt = "fallthrough" . 5382 </pre> 5383 5384 5385 <h3 id="Defer_statements">Defer statements</h3> 5386 5387 <p> 5388 A "defer" statement invokes a function whose execution is deferred 5389 to the moment the surrounding function returns, either because the 5390 surrounding function executed a <a href="#Return_statements">return statement</a>, 5391 reached the end of its <a href="#Function_declarations">function body</a>, 5392 or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>. 5393 </p> 5394 5395 <pre class="ebnf"> 5396 DeferStmt = "defer" Expression . 5397 </pre> 5398 5399 <p> 5400 The expression must be a function or method call; it cannot be parenthesized. 5401 Calls of built-in functions are restricted as for 5402 <a href="#Expression_statements">expression statements</a>. 5403 </p> 5404 5405 <p> 5406 Each time a "defer" statement 5407 executes, the function value and parameters to the call are 5408 <a href="#Calls">evaluated as usual</a> 5409 and saved anew but the actual function is not invoked. 5410 Instead, deferred functions are invoked immediately before 5411 the surrounding function returns, in the reverse order 5412 they were deferred. 5413 If a deferred function value evaluates 5414 to <code>nil</code>, execution <a href="#Handling_panics">panics</a> 5415 when the function is invoked, not when the "defer" statement is executed. 5416 </p> 5417 5418 <p> 5419 For instance, if the deferred function is 5420 a <a href="#Function_literals">function literal</a> and the surrounding 5421 function has <a href="#Function_types">named result parameters</a> that 5422 are in scope within the literal, the deferred function may access and modify 5423 the result parameters before they are returned. 5424 If the deferred function has any return values, they are discarded when 5425 the function completes. 5426 (See also the section on <a href="#Handling_panics">handling panics</a>.) 5427 </p> 5428 5429 <pre> 5430 lock(l) 5431 defer unlock(l) // unlocking happens before surrounding function returns 5432 5433 // prints 3 2 1 0 before surrounding function returns 5434 for i := 0; i <= 3; i++ { 5435 defer fmt.Print(i) 5436 } 5437 5438 // f returns 1 5439 func f() (result int) { 5440 defer func() { 5441 result++ 5442 }() 5443 return 0 5444 } 5445 </pre> 5446 5447 <h2 id="Built-in_functions">Built-in functions</h2> 5448 5449 <p> 5450 Built-in functions are 5451 <a href="#Predeclared_identifiers">predeclared</a>. 5452 They are called like any other function but some of them 5453 accept a type instead of an expression as the first argument. 5454 </p> 5455 5456 <p> 5457 The built-in functions do not have standard Go types, 5458 so they can only appear in <a href="#Calls">call expressions</a>; 5459 they cannot be used as function values. 5460 </p> 5461 5462 <h3 id="Close">Close</h3> 5463 5464 <p> 5465 For a channel <code>c</code>, the built-in function <code>close(c)</code> 5466 records that no more values will be sent on the channel. 5467 It is an error if <code>c</code> is a receive-only channel. 5468 Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>. 5469 Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>. 5470 After calling <code>close</code>, and after any previously 5471 sent values have been received, receive operations will return 5472 the zero value for the channel's type without blocking. 5473 The multi-valued <a href="#Receive_operator">receive operation</a> 5474 returns a received value along with an indication of whether the channel is closed. 5475 </p> 5476 5477 5478 <h3 id="Length_and_capacity">Length and capacity</h3> 5479 5480 <p> 5481 The built-in functions <code>len</code> and <code>cap</code> take arguments 5482 of various types and return a result of type <code>int</code>. 5483 The implementation guarantees that the result always fits into an <code>int</code>. 5484 </p> 5485 5486 <pre class="grammar"> 5487 Call Argument type Result 5488 5489 len(s) string type string length in bytes 5490 [n]T, *[n]T array length (== n) 5491 []T slice length 5492 map[K]T map length (number of defined keys) 5493 chan T number of elements queued in channel buffer 5494 5495 cap(s) [n]T, *[n]T array length (== n) 5496 []T slice capacity 5497 chan T channel buffer capacity 5498 </pre> 5499 5500 <p> 5501 The capacity of a slice is the number of elements for which there is 5502 space allocated in the underlying array. 5503 At any time the following relationship holds: 5504 </p> 5505 5506 <pre> 5507 0 <= len(s) <= cap(s) 5508 </pre> 5509 5510 <p> 5511 The length of a <code>nil</code> slice, map or channel is 0. 5512 The capacity of a <code>nil</code> slice or channel is 0. 5513 </p> 5514 5515 <p> 5516 The expression <code>len(s)</code> is <a href="#Constants">constant</a> if 5517 <code>s</code> is a string constant. The expressions <code>len(s)</code> and 5518 <code>cap(s)</code> are constants if the type of <code>s</code> is an array 5519 or pointer to an array and the expression <code>s</code> does not contain 5520 <a href="#Receive_operator">channel receives</a> or (non-constant) 5521 <a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated. 5522 Otherwise, invocations of <code>len</code> and <code>cap</code> are not 5523 constant and <code>s</code> is evaluated. 5524 </p> 5525 5526 <pre> 5527 const ( 5528 c1 = imag(2i) // imag(2i) = 2.0 is a constant 5529 c2 = len([10]float64{2}) // [10]float64{2} contains no function calls 5530 c3 = len([10]float64{c1}) // [10]float64{c1} contains no function calls 5531 c4 = len([10]float64{imag(2i)}) // imag(2i) is a constant and no function call is issued 5532 c5 = len([10]float64{imag(z)}) // invalid: imag(z) is a (non-constant) function call 5533 ) 5534 var z complex128 5535 </pre> 5536 5537 <h3 id="Allocation">Allocation</h3> 5538 5539 <p> 5540 The built-in function <code>new</code> takes a type <code>T</code>, 5541 allocates storage for a <a href="#Variables">variable</a> of that type 5542 at run time, and returns a value of type <code>*T</code> 5543 <a href="#Pointer_types">pointing</a> to it. 5544 The variable is initialized as described in the section on 5545 <a href="#The_zero_value">initial values</a>. 5546 </p> 5547 5548 <pre class="grammar"> 5549 new(T) 5550 </pre> 5551 5552 <p> 5553 For instance 5554 </p> 5555 5556 <pre> 5557 type S struct { a int; b float64 } 5558 new(S) 5559 </pre> 5560 5561 <p> 5562 allocates storage for a variable of type <code>S</code>, 5563 initializes it (<code>a=0</code>, <code>b=0.0</code>), 5564 and returns a value of type <code>*S</code> containing the address 5565 of the location. 5566 </p> 5567 5568 <h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3> 5569 5570 <p> 5571 The built-in function <code>make</code> takes a type <code>T</code>, 5572 which must be a slice, map or channel type, 5573 optionally followed by a type-specific list of expressions. 5574 It returns a value of type <code>T</code> (not <code>*T</code>). 5575 The memory is initialized as described in the section on 5576 <a href="#The_zero_value">initial values</a>. 5577 </p> 5578 5579 <pre class="grammar"> 5580 Call Type T Result 5581 5582 make(T, n) slice slice of type T with length n and capacity n 5583 make(T, n, m) slice slice of type T with length n and capacity m 5584 5585 make(T) map map of type T 5586 make(T, n) map map of type T with initial space for n elements 5587 5588 make(T) channel unbuffered channel of type T 5589 make(T, n) channel buffered channel of type T, buffer size n 5590 </pre> 5591 5592 5593 <p> 5594 The size arguments <code>n</code> and <code>m</code> must be of integer type or untyped. 5595 A <a href="#Constants">constant</a> size argument must be non-negative and 5596 representable by a value of type <code>int</code>. 5597 If both <code>n</code> and <code>m</code> are provided and are constant, then 5598 <code>n</code> must be no larger than <code>m</code>. 5599 If <code>n</code> is negative or larger than <code>m</code> at run time, 5600 a <a href="#Run_time_panics">run-time panic</a> occurs. 5601 </p> 5602 5603 <pre> 5604 s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100 5605 s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000 5606 s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type int 5607 s := make([]int, 10, 0) // illegal: len(s) > cap(s) 5608 c := make(chan int, 10) // channel with a buffer size of 10 5609 m := make(map[string]int, 100) // map with initial space for 100 elements 5610 </pre> 5611 5612 5613 <h3 id="Appending_and_copying_slices">Appending to and copying slices</h3> 5614 5615 <p> 5616 The built-in functions <code>append</code> and <code>copy</code> assist in 5617 common slice operations. 5618 For both functions, the result is independent of whether the memory referenced 5619 by the arguments overlaps. 5620 </p> 5621 5622 <p> 5623 The <a href="#Function_types">variadic</a> function <code>append</code> 5624 appends zero or more values <code>x</code> 5625 to <code>s</code> of type <code>S</code>, which must be a slice type, and 5626 returns the resulting slice, also of type <code>S</code>. 5627 The values <code>x</code> are passed to a parameter of type <code>...T</code> 5628 where <code>T</code> is the <a href="#Slice_types">element type</a> of 5629 <code>S</code> and the respective 5630 <a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply. 5631 As a special case, <code>append</code> also accepts a first argument 5632 assignable to type <code>[]byte</code> with a second argument of 5633 string type followed by <code>...</code>. This form appends the 5634 bytes of the string. 5635 </p> 5636 5637 <pre class="grammar"> 5638 append(s S, x ...T) S // T is the element type of S 5639 </pre> 5640 5641 <p> 5642 If the capacity of <code>s</code> is not large enough to fit the additional 5643 values, <code>append</code> allocates a new, sufficiently large underlying 5644 array that fits both the existing slice elements and the additional values. 5645 Otherwise, <code>append</code> re-uses the underlying array. 5646 </p> 5647 5648 <pre> 5649 s0 := []int{0, 0} 5650 s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2} 5651 s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7} 5652 s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0} 5653 s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0} 5654 5655 var t []interface{} 5656 t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"} 5657 5658 var b []byte 5659 b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' } 5660 </pre> 5661 5662 <p> 5663 The function <code>copy</code> copies slice elements from 5664 a source <code>src</code> to a destination <code>dst</code> and returns the 5665 number of elements copied. 5666 Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be 5667 <a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>. 5668 The number of elements copied is the minimum of 5669 <code>len(src)</code> and <code>len(dst)</code>. 5670 As a special case, <code>copy</code> also accepts a destination argument assignable 5671 to type <code>[]byte</code> with a source argument of a string type. 5672 This form copies the bytes from the string into the byte slice. 5673 </p> 5674 5675 <pre class="grammar"> 5676 copy(dst, src []T) int 5677 copy(dst []byte, src string) int 5678 </pre> 5679 5680 <p> 5681 Examples: 5682 </p> 5683 5684 <pre> 5685 var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7} 5686 var s = make([]int, 6) 5687 var b = make([]byte, 5) 5688 n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5} 5689 n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5} 5690 n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello") 5691 </pre> 5692 5693 5694 <h3 id="Deletion_of_map_elements">Deletion of map elements</h3> 5695 5696 <p> 5697 The built-in function <code>delete</code> removes the element with key 5698 <code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The 5699 type of <code>k</code> must be <a href="#Assignability">assignable</a> 5700 to the key type of <code>m</code>. 5701 </p> 5702 5703 <pre class="grammar"> 5704 delete(m, k) // remove element m[k] from map m 5705 </pre> 5706 5707 <p> 5708 If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code> 5709 does not exist, <code>delete</code> is a no-op. 5710 </p> 5711 5712 5713 <h3 id="Complex_numbers">Manipulating complex numbers</h3> 5714 5715 <p> 5716 Three functions assemble and disassemble complex numbers. 5717 The built-in function <code>complex</code> constructs a complex 5718 value from a floating-point real and imaginary part, while 5719 <code>real</code> and <code>imag</code> 5720 extract the real and imaginary parts of a complex value. 5721 </p> 5722 5723 <pre class="grammar"> 5724 complex(realPart, imaginaryPart floatT) complexT 5725 real(complexT) floatT 5726 imag(complexT) floatT 5727 </pre> 5728 5729 <p> 5730 The type of the arguments and return value correspond. 5731 For <code>complex</code>, the two arguments must be of the same 5732 floating-point type and the return type is the complex type 5733 with the corresponding floating-point constituents: 5734 <code>complex64</code> for <code>float32</code> arguments, and 5735 <code>complex128</code> for <code>float64</code> arguments. 5736 If one of the arguments evaluates to an untyped constant, it is first 5737 <a href="#Conversions">converted</a> to the type of the other argument. 5738 If both arguments evaluate to untyped constants, they must be non-complex 5739 numbers or their imaginary parts must be zero, and the return value of 5740 the function is an untyped complex constant. 5741 </p> 5742 5743 <p> 5744 For <code>real</code> and <code>imag</code>, the argument must be 5745 of complex type, and the return type is the corresponding floating-point 5746 type: <code>float32</code> for a <code>complex64</code> argument, and 5747 <code>float64</code> for a <code>complex128</code> argument. 5748 If the argument evaluates to an untyped constant, it must be a number, 5749 and the return value of the function is an untyped floating-point constant. 5750 </p> 5751 5752 <p> 5753 The <code>real</code> and <code>imag</code> functions together form the inverse of 5754 <code>complex</code>, so for a value <code>z</code> of a complex type <code>Z</code>, 5755 <code>z == Z(complex(real(z), imag(z)))</code>. 5756 </p> 5757 5758 <p> 5759 If the operands of these functions are all constants, the return 5760 value is a constant. 5761 </p> 5762 5763 <pre> 5764 var a = complex(2, -2) // complex128 5765 const b = complex(1.0, -1.4) // untyped complex constant 1 - 1.4i 5766 x := float32(math.Cos(math.Pi/2)) // float32 5767 var c64 = complex(5, -x) // complex64 5768 var s uint = complex(1, 0) // untyped complex constant 1 + 0i can be converted to uint 5769 _ = complex(1, 2<<s) // illegal: 2 assumes floating-point type, cannot shift 5770 var rl = real(c64) // float32 5771 var im = imag(a) // float64 5772 const c = imag(b) // untyped constant -1.4 5773 _ = imag(3 << s) // illegal: 3 assumes complex type, cannot shift 5774 </pre> 5775 5776 <h3 id="Handling_panics">Handling panics</h3> 5777 5778 <p> Two built-in functions, <code>panic</code> and <code>recover</code>, 5779 assist in reporting and handling <a href="#Run_time_panics">run-time panics</a> 5780 and program-defined error conditions. 5781 </p> 5782 5783 <pre class="grammar"> 5784 func panic(interface{}) 5785 func recover() interface{} 5786 </pre> 5787 5788 <p> 5789 While executing a function <code>F</code>, 5790 an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a> 5791 terminates the execution of <code>F</code>. 5792 Any functions <a href="#Defer_statements">deferred</a> by <code>F</code> 5793 are then executed as usual. 5794 Next, any deferred functions run by <code>F's</code> caller are run, 5795 and so on up to any deferred by the top-level function in the executing goroutine. 5796 At that point, the program is terminated and the error 5797 condition is reported, including the value of the argument to <code>panic</code>. 5798 This termination sequence is called <i>panicking</i>. 5799 </p> 5800 5801 <pre> 5802 panic(42) 5803 panic("unreachable") 5804 panic(Error("cannot parse")) 5805 </pre> 5806 5807 <p> 5808 The <code>recover</code> function allows a program to manage behavior 5809 of a panicking goroutine. 5810 Suppose a function <code>G</code> defers a function <code>D</code> that calls 5811 <code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code> 5812 is executing. 5813 When the running of deferred functions reaches <code>D</code>, 5814 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>. 5815 If <code>D</code> returns normally, without starting a new 5816 <code>panic</code>, the panicking sequence stops. In that case, 5817 the state of functions called between <code>G</code> and the call to <code>panic</code> 5818 is discarded, and normal execution resumes. 5819 Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s 5820 execution terminates by returning to its caller. 5821 </p> 5822 5823 <p> 5824 The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds: 5825 </p> 5826 <ul> 5827 <li> 5828 <code>panic</code>'s argument was <code>nil</code>; 5829 </li> 5830 <li> 5831 the goroutine is not panicking; 5832 </li> 5833 <li> 5834 <code>recover</code> was not called directly by a deferred function. 5835 </li> 5836 </ul> 5837 5838 <p> 5839 The <code>protect</code> function in the example below invokes 5840 the function argument <code>g</code> and protects callers from 5841 run-time panics raised by <code>g</code>. 5842 </p> 5843 5844 <pre> 5845 func protect(g func()) { 5846 defer func() { 5847 log.Println("done") // Println executes normally even if there is a panic 5848 if x := recover(); x != nil { 5849 log.Printf("run time panic: %v", x) 5850 } 5851 }() 5852 log.Println("start") 5853 g() 5854 } 5855 </pre> 5856 5857 5858 <h3 id="Bootstrapping">Bootstrapping</h3> 5859 5860 <p> 5861 Current implementations provide several built-in functions useful during 5862 bootstrapping. These functions are documented for completeness but are not 5863 guaranteed to stay in the language. They do not return a result. 5864 </p> 5865 5866 <pre class="grammar"> 5867 Function Behavior 5868 5869 print prints all arguments; formatting of arguments is implementation-specific 5870 println like print but prints spaces between arguments and a newline at the end 5871 </pre> 5872 5873 5874 <h2 id="Packages">Packages</h2> 5875 5876 <p> 5877 Go programs are constructed by linking together <i>packages</i>. 5878 A package in turn is constructed from one or more source files 5879 that together declare constants, types, variables and functions 5880 belonging to the package and which are accessible in all files 5881 of the same package. Those elements may be 5882 <a href="#Exported_identifiers">exported</a> and used in another package. 5883 </p> 5884 5885 <h3 id="Source_file_organization">Source file organization</h3> 5886 5887 <p> 5888 Each source file consists of a package clause defining the package 5889 to which it belongs, followed by a possibly empty set of import 5890 declarations that declare packages whose contents it wishes to use, 5891 followed by a possibly empty set of declarations of functions, 5892 types, variables, and constants. 5893 </p> 5894 5895 <pre class="ebnf"> 5896 SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } . 5897 </pre> 5898 5899 <h3 id="Package_clause">Package clause</h3> 5900 5901 <p> 5902 A package clause begins each source file and defines the package 5903 to which the file belongs. 5904 </p> 5905 5906 <pre class="ebnf"> 5907 PackageClause = "package" PackageName . 5908 PackageName = identifier . 5909 </pre> 5910 5911 <p> 5912 The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>. 5913 </p> 5914 5915 <pre> 5916 package math 5917 </pre> 5918 5919 <p> 5920 A set of files sharing the same PackageName form the implementation of a package. 5921 An implementation may require that all source files for a package inhabit the same directory. 5922 </p> 5923 5924 <h3 id="Import_declarations">Import declarations</h3> 5925 5926 <p> 5927 An import declaration states that the source file containing the declaration 5928 depends on functionality of the <i>imported</i> package 5929 (<a href="#Program_initialization_and_execution">Program initialization and execution</a>) 5930 and enables access to <a href="#Exported_identifiers">exported</a> identifiers 5931 of that package. 5932 The import names an identifier (PackageName) to be used for access and an ImportPath 5933 that specifies the package to be imported. 5934 </p> 5935 5936 <pre class="ebnf"> 5937 ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) . 5938 ImportSpec = [ "." | PackageName ] ImportPath . 5939 ImportPath = string_lit . 5940 </pre> 5941 5942 <p> 5943 The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a> 5944 to access exported identifiers of the package within the importing source file. 5945 It is declared in the <a href="#Blocks">file block</a>. 5946 If the PackageName is omitted, it defaults to the identifier specified in the 5947 <a href="#Package_clause">package clause</a> of the imported package. 5948 If an explicit period (<code>.</code>) appears instead of a name, all the 5949 package's exported identifiers declared in that package's 5950 <a href="#Blocks">package block</a> will be declared in the importing source 5951 file's file block and must be accessed without a qualifier. 5952 </p> 5953 5954 <p> 5955 The interpretation of the ImportPath is implementation-dependent but 5956 it is typically a substring of the full file name of the compiled 5957 package and may be relative to a repository of installed packages. 5958 </p> 5959 5960 <p> 5961 Implementation restriction: A compiler may restrict ImportPaths to 5962 non-empty strings using only characters belonging to 5963 <a href="http://www.unicode.org/versions/Unicode6.3.0/">Unicode's</a> 5964 L, M, N, P, and S general categories (the Graphic characters without 5965 spaces) and may also exclude the characters 5966 <code>!"#$%&'()*,:;<=>?[\]^`{|}</code> 5967 and the Unicode replacement character U+FFFD. 5968 </p> 5969 5970 <p> 5971 Assume we have compiled a package containing the package clause 5972 <code>package math</code>, which exports function <code>Sin</code>, and 5973 installed the compiled package in the file identified by 5974 <code>"lib/math"</code>. 5975 This table illustrates how <code>Sin</code> is accessed in files 5976 that import the package after the 5977 various types of import declaration. 5978 </p> 5979 5980 <pre class="grammar"> 5981 Import declaration Local name of Sin 5982 5983 import "lib/math" math.Sin 5984 import m "lib/math" m.Sin 5985 import . "lib/math" Sin 5986 </pre> 5987 5988 <p> 5989 An import declaration declares a dependency relation between 5990 the importing and imported package. 5991 It is illegal for a package to import itself, directly or indirectly, 5992 or to directly import a package without 5993 referring to any of its exported identifiers. To import a package solely for 5994 its side-effects (initialization), use the <a href="#Blank_identifier">blank</a> 5995 identifier as explicit package name: 5996 </p> 5997 5998 <pre> 5999 import _ "lib/math" 6000 </pre> 6001 6002 6003 <h3 id="An_example_package">An example package</h3> 6004 6005 <p> 6006 Here is a complete Go package that implements a concurrent prime sieve. 6007 </p> 6008 6009 <pre> 6010 package main 6011 6012 import "fmt" 6013 6014 // Send the sequence 2, 3, 4, to channel 'ch'. 6015 func generate(ch chan<- int) { 6016 for i := 2; ; i++ { 6017 ch <- i // Send 'i' to channel 'ch'. 6018 } 6019 } 6020 6021 // Copy the values from channel 'src' to channel 'dst', 6022 // removing those divisible by 'prime'. 6023 func filter(src <-chan int, dst chan<- int, prime int) { 6024 for i := range src { // Loop over values received from 'src'. 6025 if i%prime != 0 { 6026 dst <- i // Send 'i' to channel 'dst'. 6027 } 6028 } 6029 } 6030 6031 // The prime sieve: Daisy-chain filter processes together. 6032 func sieve() { 6033 ch := make(chan int) // Create a new channel. 6034 go generate(ch) // Start generate() as a subprocess. 6035 for { 6036 prime := <-ch 6037 fmt.Print(prime, "\n") 6038 ch1 := make(chan int) 6039 go filter(ch, ch1, prime) 6040 ch = ch1 6041 } 6042 } 6043 6044 func main() { 6045 sieve() 6046 } 6047 </pre> 6048 6049 <h2 id="Program_initialization_and_execution">Program initialization and execution</h2> 6050 6051 <h3 id="The_zero_value">The zero value</h3> 6052 <p> 6053 When storage is allocated for a <a href="#Variables">variable</a>, 6054 either through a declaration or a call of <code>new</code>, or when 6055 a new value is created, either through a composite literal or a call 6056 of <code>make</code>, 6057 and no explicit initialization is provided, the variable or value is 6058 given a default value. Each element of such a variable or value is 6059 set to the <i>zero value</i> for its type: <code>false</code> for booleans, 6060 <code>0</code> for integers, <code>0.0</code> for floats, <code>""</code> 6061 for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps. 6062 This initialization is done recursively, so for instance each element of an 6063 array of structs will have its fields zeroed if no value is specified. 6064 </p> 6065 <p> 6066 These two simple declarations are equivalent: 6067 </p> 6068 6069 <pre> 6070 var i int 6071 var i int = 0 6072 </pre> 6073 6074 <p> 6075 After 6076 </p> 6077 6078 <pre> 6079 type T struct { i int; f float64; next *T } 6080 t := new(T) 6081 </pre> 6082 6083 <p> 6084 the following holds: 6085 </p> 6086 6087 <pre> 6088 t.i == 0 6089 t.f == 0.0 6090 t.next == nil 6091 </pre> 6092 6093 <p> 6094 The same would also be true after 6095 </p> 6096 6097 <pre> 6098 var t T 6099 </pre> 6100 6101 <h3 id="Package_initialization">Package initialization</h3> 6102 6103 <p> 6104 Within a package, package-level variables are initialized in 6105 <i>declaration order</i> but after any of the variables 6106 they <i>depend</i> on. 6107 </p> 6108 6109 <p> 6110 More precisely, a package-level variable is considered <i>ready for 6111 initialization</i> if it is not yet initialized and either has 6112 no <a href="#Variable_declarations">initialization expression</a> or 6113 its initialization expression has no dependencies on uninitialized variables. 6114 Initialization proceeds by repeatedly initializing the next package-level 6115 variable that is earliest in declaration order and ready for initialization, 6116 until there are no variables ready for initialization. 6117 </p> 6118 6119 <p> 6120 If any variables are still uninitialized when this 6121 process ends, those variables are part of one or more initialization cycles, 6122 and the program is not valid. 6123 </p> 6124 6125 <p> 6126 The declaration order of variables declared in multiple files is determined 6127 by the order in which the files are presented to the compiler: Variables 6128 declared in the first file are declared before any of the variables declared 6129 in the second file, and so on. 6130 </p> 6131 6132 <p> 6133 Dependency analysis does not rely on the actual values of the 6134 variables, only on lexical <i>references</i> to them in the source, 6135 analyzed transitively. For instance, if a variable <code>x</code>'s 6136 initialization expression refers to a function whose body refers to 6137 variable <code>y</code> then <code>x</code> depends on <code>y</code>. 6138 Specifically: 6139 </p> 6140 6141 <ul> 6142 <li> 6143 A reference to a variable or function is an identifier denoting that 6144 variable or function. 6145 </li> 6146 6147 <li> 6148 A reference to a method <code>m</code> is a 6149 <a href="#Method_values">method value</a> or 6150 <a href="#Method_expressions">method expression</a> of the form 6151 <code>t.m</code>, where the (static) type of <code>t</code> is 6152 not an interface type, and the method <code>m</code> is in the 6153 <a href="#Method_sets">method set</a> of <code>t</code>. 6154 It is immaterial whether the resulting function value 6155 <code>t.m</code> is invoked. 6156 </li> 6157 6158 <li> 6159 A variable, function, or method <code>x</code> depends on a variable 6160 <code>y</code> if <code>x</code>'s initialization expression or body 6161 (for functions and methods) contains a reference to <code>y</code> 6162 or to a function or method that depends on <code>y</code>. 6163 </li> 6164 </ul> 6165 6166 <p> 6167 Dependency analysis is performed per package; only references referring 6168 to variables, functions, and methods declared in the current package 6169 are considered. 6170 </p> 6171 6172 <p> 6173 For example, given the declarations 6174 </p> 6175 6176 <pre> 6177 var ( 6178 a = c + b 6179 b = f() 6180 c = f() 6181 d = 3 6182 ) 6183 6184 func f() int { 6185 d++ 6186 return d 6187 } 6188 </pre> 6189 6190 <p> 6191 the initialization order is <code>d</code>, <code>b</code>, <code>c</code>, <code>a</code>. 6192 </p> 6193 6194 <p> 6195 Variables may also be initialized using functions named <code>init</code> 6196 declared in the package block, with no arguments and no result parameters. 6197 </p> 6198 6199 <pre> 6200 func init() { } 6201 </pre> 6202 6203 <p> 6204 Multiple such functions may be defined per package, even within a single 6205 source file. In the package block, the <code>init</code> identifier can 6206 be used only to declare <code>init</code> functions, yet the identifier 6207 itself is not <a href="#Declarations_and_scope">declared</a>. Thus 6208 <code>init</code> functions cannot be referred to from anywhere 6209 in a program. 6210 </p> 6211 6212 <p> 6213 A package with no imports is initialized by assigning initial values 6214 to all its package-level variables followed by calling all <code>init</code> 6215 functions in the order they appear in the source, possibly in multiple files, 6216 as presented to the compiler. 6217 If a package has imports, the imported packages are initialized 6218 before initializing the package itself. If multiple packages import 6219 a package, the imported package will be initialized only once. 6220 The importing of packages, by construction, guarantees that there 6221 can be no cyclic initialization dependencies. 6222 </p> 6223 6224 <p> 6225 Package initialization—variable initialization and the invocation of 6226 <code>init</code> functions—happens in a single goroutine, 6227 sequentially, one package at a time. 6228 An <code>init</code> function may launch other goroutines, which can run 6229 concurrently with the initialization code. However, initialization 6230 always sequences 6231 the <code>init</code> functions: it will not invoke the next one 6232 until the previous one has returned. 6233 </p> 6234 6235 <p> 6236 To ensure reproducible initialization behavior, build systems are encouraged 6237 to present multiple files belonging to the same package in lexical file name 6238 order to a compiler. 6239 </p> 6240 6241 6242 <h3 id="Program_execution">Program execution</h3> 6243 <p> 6244 A complete program is created by linking a single, unimported package 6245 called the <i>main package</i> with all the packages it imports, transitively. 6246 The main package must 6247 have package name <code>main</code> and 6248 declare a function <code>main</code> that takes no 6249 arguments and returns no value. 6250 </p> 6251 6252 <pre> 6253 func main() { } 6254 </pre> 6255 6256 <p> 6257 Program execution begins by initializing the main package and then 6258 invoking the function <code>main</code>. 6259 When that function invocation returns, the program exits. 6260 It does not wait for other (non-<code>main</code>) goroutines to complete. 6261 </p> 6262 6263 <h2 id="Errors">Errors</h2> 6264 6265 <p> 6266 The predeclared type <code>error</code> is defined as 6267 </p> 6268 6269 <pre> 6270 type error interface { 6271 Error() string 6272 } 6273 </pre> 6274 6275 <p> 6276 It is the conventional interface for representing an error condition, 6277 with the nil value representing no error. 6278 For instance, a function to read data from a file might be defined: 6279 </p> 6280 6281 <pre> 6282 func Read(f *File, b []byte) (n int, err error) 6283 </pre> 6284 6285 <h2 id="Run_time_panics">Run-time panics</h2> 6286 6287 <p> 6288 Execution errors such as attempting to index an array out 6289 of bounds trigger a <i>run-time panic</i> equivalent to a call of 6290 the built-in function <a href="#Handling_panics"><code>panic</code></a> 6291 with a value of the implementation-defined interface type <code>runtime.Error</code>. 6292 That type satisfies the predeclared interface type 6293 <a href="#Errors"><code>error</code></a>. 6294 The exact error values that 6295 represent distinct run-time error conditions are unspecified. 6296 </p> 6297 6298 <pre> 6299 package runtime 6300 6301 type Error interface { 6302 error 6303 // and perhaps other methods 6304 } 6305 </pre> 6306 6307 <h2 id="System_considerations">System considerations</h2> 6308 6309 <h3 id="Package_unsafe">Package <code>unsafe</code></h3> 6310 6311 <p> 6312 The built-in package <code>unsafe</code>, known to the compiler, 6313 provides facilities for low-level programming including operations 6314 that violate the type system. A package using <code>unsafe</code> 6315 must be vetted manually for type safety and may not be portable. 6316 The package provides the following interface: 6317 </p> 6318 6319 <pre class="grammar"> 6320 package unsafe 6321 6322 type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type 6323 type Pointer *ArbitraryType 6324 6325 func Alignof(variable ArbitraryType) uintptr 6326 func Offsetof(selector ArbitraryType) uintptr 6327 func Sizeof(variable ArbitraryType) uintptr 6328 </pre> 6329 6330 <p> 6331 A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code> 6332 value may not be <a href="#Address_operators">dereferenced</a>. 6333 Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to 6334 a <code>Pointer</code> type and vice versa. 6335 The effect of converting between <code>Pointer</code> and <code>uintptr</code> is implementation-defined. 6336 </p> 6337 6338 <pre> 6339 var f float64 6340 bits = *(*uint64)(unsafe.Pointer(&f)) 6341 6342 type ptr unsafe.Pointer 6343 bits = *(*uint64)(ptr(&f)) 6344 6345 var p ptr = nil 6346 </pre> 6347 6348 <p> 6349 The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code> 6350 of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code> 6351 as if <code>v</code> was declared via <code>var v = x</code>. 6352 </p> 6353 <p> 6354 The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a> 6355 <code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code> 6356 or <code>*s</code>, and returns the field offset in bytes relative to the struct's address. 6357 If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable 6358 without pointer indirections through fields of the struct. 6359 For a struct <code>s</code> with field <code>f</code>: 6360 </p> 6361 6362 <pre> 6363 uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&s.f)) 6364 </pre> 6365 6366 <p> 6367 Computer architectures may require memory addresses to be <i>aligned</i>; 6368 that is, for addresses of a variable to be a multiple of a factor, 6369 the variable's type's <i>alignment</i>. The function <code>Alignof</code> 6370 takes an expression denoting a variable of any type and returns the 6371 alignment of the (type of the) variable in bytes. For a variable 6372 <code>x</code>: 6373 </p> 6374 6375 <pre> 6376 uintptr(unsafe.Pointer(&x)) % unsafe.Alignof(x) == 0 6377 </pre> 6378 6379 <p> 6380 Calls to <code>Alignof</code>, <code>Offsetof</code>, and 6381 <code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>. 6382 </p> 6383 6384 <h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3> 6385 6386 <p> 6387 For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed: 6388 </p> 6389 6390 <pre class="grammar"> 6391 type size in bytes 6392 6393 byte, uint8, int8 1 6394 uint16, int16 2 6395 uint32, int32, float32 4 6396 uint64, int64, float64, complex64 8 6397 complex128 16 6398 </pre> 6399 6400 <p> 6401 The following minimal alignment properties are guaranteed: 6402 </p> 6403 <ol> 6404 <li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1. 6405 </li> 6406 6407 <li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of 6408 all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1. 6409 </li> 6410 6411 <li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as 6412 <code>unsafe.Alignof(x[0])</code>, but at least 1. 6413 </li> 6414 </ol> 6415 6416 <p> 6417 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. 6418 </p> 6419