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