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