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