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