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