go_spec.html 194 KB
Newer Older
1 2
<!--{
	"Title": "The Go Programming Language Specification",
3
	"Subtitle": "Version of October 19, 2016",
4
	"Path": "/ref/spec"
5
}-->
6

7
<h2 id="Introduction">Introduction</h2>
8

9
<p>
Rob Pike's avatar
Rob Pike committed
10
This is a reference manual for the Go programming language. For
11
more information and other documents, see <a href="/">golang.org</a>.
Rob Pike's avatar
Rob Pike committed
12
</p>
13

14
<p>
Rob Pike's avatar
Rob Pike committed
15
Go is a general-purpose language designed with systems programming
Rob Pike's avatar
Rob Pike committed
16
in mind. It is strongly typed and garbage-collected and has explicit
Rob Pike's avatar
Rob Pike committed
17 18 19 20 21
support for concurrent programming.  Programs are constructed from
<i>packages</i>, whose properties allow efficient management of
dependencies. The existing implementations use a traditional
compile/link model to generate executable binaries.
</p>
22

23
<p>
Rob Pike's avatar
Rob Pike committed
24 25 26
The grammar is compact and regular, allowing for easy analysis by
automatic tools such as integrated development environments.
</p>
27

28
<h2 id="Notation">Notation</h2>
Rob Pike's avatar
Rob Pike committed
29
<p>
30
The syntax is specified using Extended Backus-Naur Form (EBNF):
Rob Pike's avatar
Rob Pike committed
31
</p>
32

Rob Pike's avatar
Rob Pike committed
33
<pre class="grammar">
34
Production  = production_name "=" [ Expression ] "." .
Rob Pike's avatar
Rob Pike committed
35
Expression  = Alternative { "|" Alternative } .
36
Alternative = Term { Term } .
37
Term        = production_name | token [ "…" token ] | Group | Option | Repetition .
Rob Pike's avatar
Rob Pike committed
38
Group       = "(" Expression ")" .
39
Option      = "[" Expression "]" .
Rob Pike's avatar
Rob Pike committed
40
Repetition  = "{" Expression "}" .
41
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
42

Rob Pike's avatar
Rob Pike committed
43 44 45 46
<p>
Productions are expressions constructed from terms and the following
operators, in increasing precedence:
</p>
Rob Pike's avatar
Rob Pike committed
47
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
48 49 50 51
|   alternation
()  grouping
[]  option (0 or 1 times)
{}  repetition (0 to n times)
52
</pre>
53

54
<p>
Rob Pike's avatar
Rob Pike committed
55
Lower-case production names are used to identify lexical tokens.
56
Non-terminals are in CamelCase. Lexical tokens are enclosed in
Rob Pike's avatar
Rob Pike committed
57
double quotes <code>""</code> or back quotes <code>``</code>.
Rob Pike's avatar
Rob Pike committed
58 59
</p>

60
<p>
61 62
The form <code>a … b</code> represents the set of characters from
<code>a</code> through <code>b</code> as alternatives. The horizontal
63
ellipsis <code></code> is also used elsewhere in the spec to informally denote various
64
enumerations or code snippets that are not further specified. The character <code></code>
65 66
(as opposed to the three characters <code>...</code>) is not a token of the Go
language.
Rob Pike's avatar
Rob Pike committed
67 68
</p>

69
<h2 id="Source_code_representation">Source code representation</h2>
70

71
<p>
Robert Griesemer's avatar
Robert Griesemer committed
72 73
Source code is Unicode text encoded in
<a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. The text is not
Rob Pike's avatar
Rob Pike committed
74 75 76
canonicalized, so a single accented code point is distinct from the
same character constructed from combining an accent and a letter;
those are treated as two code points.  For simplicity, this document
77 78
will use the unqualified term <i>character</i> to refer to a Unicode code point
in the source text.
Rob Pike's avatar
Rob Pike committed
79
</p>
80
<p>
Rob Pike's avatar
Rob Pike committed
81 82 83
Each code point is distinct; for instance, upper and lower case letters
are different characters.
</p>
Russ Cox's avatar
Russ Cox committed
84
<p>
85 86
Implementation restriction: For compatibility with other tools, a
compiler may disallow the NUL character (U+0000) in the source text.
Russ Cox's avatar
Russ Cox committed
87
</p>
88 89
<p>
Implementation restriction: For compatibility with other tools, a
Rob Pike's avatar
Rob Pike committed
90 91
compiler may ignore a UTF-8-encoded byte order mark
(U+FEFF) if it is the first Unicode code point in the source text.
92
A byte order mark may be disallowed anywhere else in the source.
93
</p>
94

95
<h3 id="Characters">Characters</h3>
96

97
<p>
Rob Pike's avatar
Rob Pike committed
98 99
The following terms are used to denote specific Unicode character classes:
</p>
100
<pre class="ebnf">
101 102
newline        = /* the Unicode code point U+000A */ .
unicode_char   = /* an arbitrary Unicode code point except newline */ .
103
unicode_letter = /* a Unicode code point classified as "Letter" */ .
104
unicode_digit  = /* a Unicode code point classified as "Number, decimal digit" */ .
105
</pre>
106

Rob Pike's avatar
Rob Pike committed
107
<p>
108 109 110 111
In <a href="http://www.unicode.org/versions/Unicode8.0.0/">The Unicode Standard 8.0</a>,
Section 4.5 "General Category" defines a set of character categories.
Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo
as Unicode letters, and those in the Number category Nd as Unicode digits.
Rob Pike's avatar
Rob Pike committed
112
</p>
113

114
<h3 id="Letters_and_digits">Letters and digits</h3>
Rob Pike's avatar
Rob Pike committed
115 116

<p>
117
The underscore character <code>_</code> (U+005F) is considered a letter.
118 119
</p>
<pre class="ebnf">
120
letter        = unicode_letter | "_" .
121 122 123
decimal_digit = "0" … "9" .
octal_digit   = "0" … "7" .
hex_digit     = "0" … "9" | "A" … "F" | "a" … "f" .
124
</pre>
Rob Pike's avatar
Rob Pike committed
125

126
<h2 id="Lexical_elements">Lexical elements</h2>
127

128
<h3 id="Comments">Comments</h3>
129

Rob Pike's avatar
Rob Pike committed
130
<p>
131
Comments serve as program documentation. There are two forms:
Rob Pike's avatar
Rob Pike committed
132 133
</p>

134 135 136
<ol>
<li>
<i>Line comments</i> start with the character sequence <code>//</code>
137
and stop at the end of the line.
138 139 140
</li>
<li>
<i>General comments</i> start with the character sequence <code>/*</code>
141
and stop with the first subsequent character sequence <code>*/</code>.
142 143 144 145
</li>
</ol>

<p>
146 147 148 149
A comment cannot start inside a <a href="#Rune_literals">rune</a> or
<a href="#String_literals">string literal</a>, or inside a comment.
A general comment containing no newlines acts like a space.
Any other comment acts like a newline.
150 151
</p>

152
<h3 id="Tokens">Tokens</h3>
153

Rob Pike's avatar
Rob Pike committed
154 155
<p>
Tokens form the vocabulary of the Go language.
Robert Griesemer's avatar
Robert Griesemer committed
156 157
There are four classes: <i>identifiers</i>, <i>keywords</i>, <i>operators
and delimiters</i>, and <i>literals</i>.  <i>White space</i>, formed from
158 159 160
spaces (U+0020), horizontal tabs (U+0009),
carriage returns (U+000D), and newlines (U+000A),
is ignored except as it separates tokens
161
that would otherwise combine into a single token. Also, a newline or end of file
Robert Griesemer's avatar
Robert Griesemer committed
162
may trigger the insertion of a <a href="#Semicolons">semicolon</a>.
163
While breaking the input into tokens,
Rob Pike's avatar
Rob Pike committed
164 165 166
the next token is the longest sequence of characters that form a
valid token.
</p>
167

168 169 170 171 172 173 174 175 176 177 178
<h3 id="Semicolons">Semicolons</h3>

<p>
The formal grammar uses semicolons <code>";"</code> as terminators in
a number of productions. Go programs may omit most of these semicolons
using the following two rules:
</p>

<ol>
<li>
When the input is broken into tokens, a semicolon is automatically inserted
179
into the token stream immediately after a line's final token if that token is
180
<ul>
181 182
	<li>an
	    <a href="#Identifiers">identifier</a>
183
	</li>
184

185 186 187 188
	<li>an
	    <a href="#Integer_literals">integer</a>,
	    <a href="#Floating-point_literals">floating-point</a>,
	    <a href="#Imaginary_literals">imaginary</a>,
189
	    <a href="#Rune_literals">rune</a>, or
190 191
	    <a href="#String_literals">string</a> literal
	</li>
192

193 194 195 196 197 198
	<li>one of the <a href="#Keywords">keywords</a>
	    <code>break</code>,
	    <code>continue</code>,
	    <code>fallthrough</code>, or
	    <code>return</code>
	</li>
199

200 201 202 203 204 205
	<li>one of the <a href="#Operators_and_Delimiters">operators and delimiters</a>
	    <code>++</code>,
	    <code>--</code>,
	    <code>)</code>,
	    <code>]</code>, or
	    <code>}</code>
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
	</li>
</ul>
</li>

<li>
To allow complex statements to occupy a single line, a semicolon
may be omitted before a closing <code>")"</code> or <code>"}"</code>.
</li>
</ol>

<p>
To reflect idiomatic use, code examples in this document elide semicolons
using these rules.
</p>


222
<h3 id="Identifiers">Identifiers</h3>
223

Rob Pike's avatar
Rob Pike committed
224 225 226 227 228
<p>
Identifiers name program entities such as variables and types.
An identifier is a sequence of one or more letters and digits.
The first character in an identifier must be a letter.
</p>
229
<pre class="ebnf">
230
identifier = letter { letter | unicode_digit } .
231 232 233 234 235 236 237
</pre>
<pre>
a
_x9
ThisVariableIsExported
αβ
</pre>
238 239

<p>
Robert Griesemer's avatar
Robert Griesemer committed
240
Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>.
241 242
</p>

243

244
<h3 id="Keywords">Keywords</h3>
245

Rob Pike's avatar
Rob Pike committed
246 247 248 249 250 251 252 253 254 255
<p>
The following keywords are reserved and may not be used as identifiers.
</p>
<pre class="grammar">
break        default      func         interface    select
case         defer        go           map          struct
chan         else         goto         package      switch
const        fallthrough  if           range        type
continue     for          import       return       var
</pre>
256

257
<h3 id="Operators_and_Delimiters">Operators and Delimiters</h3>
Rob Pike's avatar
Rob Pike committed
258 259

<p>
260
The following character sequences represent <a href="#Operators">operators</a>, delimiters, and other special tokens:
Rob Pike's avatar
Rob Pike committed
261 262 263 264 265
</p>
<pre class="grammar">
+    &amp;     +=    &amp;=     &amp;&amp;    ==    !=    (    )
-    |     -=    |=     ||    &lt;     &lt;=    [    ]
*    ^     *=    ^=     &lt;-    &gt;     &gt;=    {    }
Robert Griesemer's avatar
Robert Griesemer committed
266 267
/    &lt;&lt;    /=    &lt;&lt;=    ++    =     :=    ,    ;
%    &gt;&gt;    %=    &gt;&gt;=    --    !     ...   .    :
Rob Pike's avatar
Rob Pike committed
268
     &amp;^          &amp;^=
Rob Pike's avatar
Rob Pike committed
269 270
</pre>

271
<h3 id="Integer_literals">Integer literals</h3>
Rob Pike's avatar
Rob Pike committed
272 273

<p>
274 275 276
An integer literal is a sequence of digits representing an
<a href="#Constants">integer constant</a>.
An optional prefix sets a non-decimal base: <code>0</code> for octal, <code>0x</code> or
277 278
<code>0X</code> for hexadecimal.  In hexadecimal literals, letters
<code>a-f</code> and <code>A-F</code> represent values 10 through 15.
Rob Pike's avatar
Rob Pike committed
279
</p>
280
<pre class="ebnf">
281
int_lit     = decimal_lit | octal_lit | hex_lit .
282
decimal_lit = ( "1" … "9" ) { decimal_digit } .
283 284
octal_lit   = "0" { octal_digit } .
hex_lit     = "0" ( "x" | "X" ) hex_digit { hex_digit } .
285 286 287 288 289 290 291 292
</pre>

<pre>
42
0600
0xBadFace
170141183460469231731687303715884105727
</pre>
293

294
<h3 id="Floating-point_literals">Floating-point literals</h3>
Rob Pike's avatar
Rob Pike committed
295
<p>
296 297 298
A floating-point literal is a decimal representation of a
<a href="#Constants">floating-point constant</a>.
It has an integer part, a decimal point, a fractional part,
Rob Pike's avatar
Rob Pike committed
299
and an exponent part.  The integer and fractional part comprise
300
decimal digits; the exponent part is an <code>e</code> or <code>E</code>
Rob Pike's avatar
Rob Pike committed
301 302 303 304
followed by an optionally signed decimal exponent.  One of the
integer part or the fractional part may be elided; one of the decimal
point or the exponent may be elided.
</p>
305
<pre class="ebnf">
306 307 308 309 310
float_lit = decimals "." [ decimals ] [ exponent ] |
            decimals exponent |
            "." decimals [ exponent ] .
decimals  = decimal_digit { decimal_digit } .
exponent  = ( "e" | "E" ) [ "+" | "-" ] decimals .
311 312 313 314
</pre>

<pre>
0.
Rob Pike's avatar
Rob Pike committed
315 316
72.40
072.40  // == 72.40
317 318 319 320 321 322 323
2.71828
1.e+0
6.67428e-11
1E6
.25
.12345E+5
</pre>
324

Rob Pike's avatar
Rob Pike committed
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
<h3 id="Imaginary_literals">Imaginary literals</h3>
<p>
An imaginary literal is a decimal representation of the imaginary part of a
<a href="#Constants">complex constant</a>.
It consists of a
<a href="#Floating-point_literals">floating-point literal</a>
or decimal integer followed
by the lower-case letter <code>i</code>.
</p>
<pre class="ebnf">
imaginary_lit = (decimals | float_lit) "i" .
</pre>

<pre>
0i
011i  // == 11i
0.i
2.71828i
1.e+0i
6.67428e-11i
1E6i
.25i
.12345E+5i
</pre>

350

351
<h3 id="Rune_literals">Rune literals</h3>
352

Rob Pike's avatar
Rob Pike committed
353
<p>
354 355
A rune literal represents a <a href="#Constants">rune constant</a>,
an integer value identifying a Unicode code point.
356 357 358 359
A rune literal is expressed as one or more characters enclosed in single quotes,
as in <code>'x'</code> or <code>'\n'</code>.
Within the quotes, any character may appear except newline and unescaped single
quote. A single quoted character represents the Unicode value
360
of the character itself,
Rob Pike's avatar
Rob Pike committed
361 362
while multi-character sequences beginning with a backslash encode
values in various formats.
Rob Pike's avatar
Rob Pike committed
363
</p>
364
<p>
Rob Pike's avatar
Rob Pike committed
365 366 367
The simplest form represents the single character within the quotes;
since Go source text is Unicode characters encoded in UTF-8, multiple
UTF-8-encoded bytes may represent a single integer value.  For
368 369 370 371
instance, the literal <code>'a'</code> holds a single byte representing
a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while
<code>'ä'</code> holds two bytes (<code>0xc3</code> <code>0xa4</code>) representing
a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>.
Rob Pike's avatar
Rob Pike committed
372
</p>
373
<p>
374
Several backslash escapes allow arbitrary values to be encoded as
Oling Cat's avatar
Oling Cat committed
375
ASCII text.  There are four ways to represent the integer value
376 377 378 379
as a numeric constant: <code>\x</code> followed by exactly two hexadecimal
digits; <code>\u</code> followed by exactly four hexadecimal digits;
<code>\U</code> followed by exactly eight hexadecimal digits, and a
plain backslash <code>\</code> followed by exactly three octal digits.
Rob Pike's avatar
Rob Pike committed
380 381 382
In each case the value of the literal is the value represented by
the digits in the corresponding base.
</p>
383
<p>
Rob Pike's avatar
Rob Pike committed
384 385
Although these representations all result in an integer, they have
different valid ranges.  Octal escapes must represent a value between
Rob Pike's avatar
Rob Pike committed
386 387
0 and 255 inclusive.  Hexadecimal escapes satisfy this condition
by construction. The escapes <code>\u</code> and <code>\U</code>
Rob Pike's avatar
Rob Pike committed
388
represent Unicode code points so within them some values are illegal,
389
in particular those above <code>0x10FFFF</code> and surrogate halves.
Rob Pike's avatar
Rob Pike committed
390
</p>
391
<p>
Rob Pike's avatar
Rob Pike committed
392 393 394 395 396 397 398 399 400 401 402
After a backslash, certain single-character escapes represent special values:
</p>
<pre class="grammar">
\a   U+0007 alert or bell
\b   U+0008 backspace
\f   U+000C form feed
\n   U+000A line feed or newline
\r   U+000D carriage return
\t   U+0009 horizontal tab
\v   U+000b vertical tab
\\   U+005c backslash
403
\'   U+0027 single quote  (valid escape only within rune literals)
Rob Pike's avatar
Rob Pike committed
404 405 406
\"   U+0022 double quote  (valid escape only within string literals)
</pre>
<p>
407
All other sequences starting with a backslash are illegal inside rune literals.
Rob Pike's avatar
Rob Pike committed
408
</p>
409
<pre class="ebnf">
Robert Griesemer's avatar
Robert Griesemer committed
410
rune_lit         = "'" ( unicode_value | byte_value ) "'" .
Rob Pike's avatar
Rob Pike committed
411 412
unicode_value    = unicode_char | little_u_value | big_u_value | escaped_char .
byte_value       = octal_byte_value | hex_byte_value .
413 414 415 416
octal_byte_value = `\` octal_digit octal_digit octal_digit .
hex_byte_value   = `\` "x" hex_digit hex_digit .
little_u_value   = `\` "u" hex_digit hex_digit hex_digit hex_digit .
big_u_value      = `\` "U" hex_digit hex_digit hex_digit hex_digit
Rob Pike's avatar
Rob Pike committed
417
                           hex_digit hex_digit hex_digit hex_digit .
418
escaped_char     = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
Rob Pike's avatar
Rob Pike committed
419
</pre>
420

421 422 423 424 425 426 427 428 429 430 431 432
<pre>
'a'
'ä'
'本'
'\t'
'\000'
'\007'
'\377'
'\x07'
'\xff'
'\u12e4'
'\U00101234'
433
'\''         // rune literal containing single quote character
434 435 436 437 438
'aa'         // illegal: too many characters
'\xa'        // illegal: too few hexadecimal digits
'\0'         // illegal: too few octal digits
'\uDFFF'     // illegal: surrogate half
'\U00110000' // illegal: invalid Unicode code point
439
</pre>
440 441


442
<h3 id="String_literals">String literals</h3>
Rob Pike's avatar
Rob Pike committed
443 444

<p>
445 446 447
A string literal represents a <a href="#Constants">string constant</a>
obtained from concatenating a sequence of characters. There are two forms:
raw string literals and interpreted string literals.
Rob Pike's avatar
Rob Pike committed
448 449
</p>
<p>
450 451
Raw string literals are character sequences between back quotes, as in
<code>`foo`</code>.  Within the quotes, any character may appear except
452
back quote. The value of a raw string literal is the
453 454
string composed of the uninterpreted (implicitly UTF-8-encoded) characters
between the quotes;
455
in particular, backslashes have no special meaning and the string may
456
contain newlines.
457
Carriage return characters ('\r') inside raw string literals
458
are discarded from the raw string value.
Rob Pike's avatar
Rob Pike committed
459 460 461
</p>
<p>
Interpreted string literals are character sequences between double
462 463 464
quotes, as in <code>&quot;bar&quot;</code>.
Within the quotes, any character may appear except newline and unescaped double quote.
The text between the quotes forms the
Rob Pike's avatar
Rob Pike committed
465
value of the literal, with backslash escapes interpreted as they
466
are in <a href="#Rune_literals">rune literals</a> (except that <code>\'</code> is illegal and
467 468
<code>\"</code> is legal), with the same restrictions.
The three-digit octal (<code>\</code><i>nnn</i>)
Robert Griesemer's avatar
Robert Griesemer committed
469
and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual
Rob Pike's avatar
Rob Pike committed
470 471
<i>bytes</i> of the resulting string; all other escapes represent
the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
472 473 474
Thus inside a string literal <code>\377</code> and <code>\xFF</code> represent
a single byte of value <code>0xFF</code>=255, while <code>ÿ</code>,
<code>\u00FF</code>, <code>\U000000FF</code> and <code>\xc3\xbf</code> represent
475
the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character
Rob Pike's avatar
Rob Pike committed
476 477 478
U+00FF.
</p>

479
<pre class="ebnf">
Rob Pike's avatar
Rob Pike committed
480
string_lit             = raw_string_lit | interpreted_string_lit .
481
raw_string_lit         = "`" { unicode_char | newline } "`" .
482
interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
483
</pre>
484

485
<pre>
486
`abc`                // same as "abc"
487
`\n
488
\n`                  // same as "\\n\n\\n"
489
"\n"
490
"\""                 // same as `"`
491 492 493 494
"Hello, world!\n"
"日本語"
"\u65e5本\U00008a9e"
"\xff\u00FF"
495 496
"\uD800"             // illegal: surrogate half
"\U00110000"         // illegal: invalid Unicode code point
497
</pre>
498

Rob Pike's avatar
Rob Pike committed
499
<p>
500
These examples all represent the same string:
Rob Pike's avatar
Rob Pike committed
501
</p>
502

503
<pre>
Rob Pike's avatar
Rob Pike committed
504 505
"日本語"                                 // UTF-8 input text
`日本語`                                 // UTF-8 input text as a raw literal
506 507 508
"\u65e5\u672c\u8a9e"                    // the explicit Unicode code points
"\U000065e5\U0000672c\U00008a9e"        // the explicit Unicode code points
"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"  // the explicit UTF-8 bytes
509
</pre>
510

511
<p>
512 513
If the source code represents a character as two code points, such as
a combining form involving an accent and a letter, the result will be
514
an error if placed in a rune literal (it is not a single code
515 516
point), and will appear as two code points if placed in a string
literal.
Rob Pike's avatar
Rob Pike committed
517
</p>
518

519 520 521

<h2 id="Constants">Constants</h2>

522
<p>There are <i>boolean constants</i>,
523
<i>rune constants</i>,
524
<i>integer constants</i>,
Rob Pike's avatar
Rob Pike committed
525
<i>floating-point constants</i>, <i>complex constants</i>,
526
and <i>string constants</i>. Rune, integer, floating-point,
Rob Pike's avatar
Rob Pike committed
527
and complex constants are
528 529 530 531
collectively called <i>numeric constants</i>.
</p>

<p>
532
A constant value is represented by a
533
<a href="#Rune_literals">rune</a>,
534 535
<a href="#Integer_literals">integer</a>,
<a href="#Floating-point_literals">floating-point</a>,
Rob Pike's avatar
Rob Pike committed
536
<a href="#Imaginary_literals">imaginary</a>,
537
or
538 539
<a href="#String_literals">string</a> literal,
an identifier denoting a constant,
540 541
a <a href="#Constant_expressions">constant expression</a>,
a <a href="#Conversions">conversion</a> with a result that is a constant, or
542 543 544 545
the result value of some built-in functions such as
<code>unsafe.Sizeof</code> applied to any value,
<code>cap</code> or <code>len</code> applied to
<a href="#Length_and_capacity">some expressions</a>,
Rob Pike's avatar
Rob Pike committed
546
<code>real</code> and <code>imag</code> applied to a complex constant
547
and <code>complex</code> applied to numeric constants.
548 549 550 551
The boolean truth values are represented by the predeclared constants
<code>true</code> and <code>false</code>. The predeclared identifier
<a href="#Iota">iota</a> denotes an integer constant.
</p>
Rob Pike's avatar
Rob Pike committed
552

Rob Pike's avatar
Rob Pike committed
553 554 555 556 557 558
<p>
In general, complex constants are a form of
<a href="#Constant_expressions">constant expression</a>
and are discussed in that section.
</p>

Rob Pike's avatar
Rob Pike committed
559
<p>
560 561 562
Numeric constants represent exact values of arbitrary precision and do not overflow.
Consequently, there are no constants denoting the IEEE-754 negative zero, infinity,
and not-a-number values.
Rob Pike's avatar
Rob Pike committed
563 564
</p>

565
<p>
566
Constants may be <a href="#Types">typed</a> or <i>untyped</i>.
567 568 569 570 571 572 573 574 575 576 577 578
Literal constants, <code>true</code>, <code>false</code>, <code>iota</code>,
and certain <a href="#Constant_expressions">constant expressions</a>
containing only untyped constant operands are untyped.
</p>

<p>
A constant may be given a type explicitly by a <a href="#Constant_declarations">constant declaration</a>
or <a href="#Conversions">conversion</a>, or implicitly when used in a
<a href="#Variable_declarations">variable declaration</a> or an
<a href="#Assignments">assignment</a> or as an
operand in an <a href="#Expressions">expression</a>.
It is an error if the constant value
579
cannot be represented as a value of the respective type.
Robert Griesemer's avatar
Robert Griesemer committed
580
For instance, <code>3.0</code> can be given any integer or any
581 582 583
floating-point type, while <code>2147483648.0</code> (equal to <code>1&lt;&lt;31</code>)
can be given the types <code>float32</code>, <code>float64</code>, or <code>uint32</code> but
not <code>int32</code> or <code>string</code>.
584 585
</p>

586 587 588 589 590 591 592 593 594 595 596
<p>
An untyped constant has a <i>default type</i> which is the type to which the
constant is implicitly converted in contexts where a typed value is required,
for instance, in a <a href="#Short_variable_declarations">short variable declaration</a>
such as <code>i := 0</code> where there is no explicit type.
The default type of an untyped constant is <code>bool</code>, <code>rune</code>,
<code>int</code>, <code>float64</code>, <code>complex128</code> or <code>string</code>
respectively, depending on whether it is a boolean, rune, integer, floating-point,
complex, or string constant.
</p>

597
<p>
598 599 600 601
Implementation restriction: Although numeric constants have arbitrary
precision in the language, a compiler may implement them using an
internal representation with limited precision.  That said, every
implementation must:
602
</p>
603 604 605 606 607
<ul>
	<li>Represent integer constants with at least 256 bits.</li>

	<li>Represent floating-point constants, including the parts of
	    a complex constant, with a mantissa of at least 256 bits
608
	    and a signed binary exponent of at least 16 bits.</li>
609 610 611

	<li>Give an error if unable to represent an integer constant
	    precisely.</li>
612

613 614 615 616 617 618 619 620 621 622 623 624
	<li>Give an error if unable to represent a floating-point or
	    complex constant due to overflow.</li>

	<li>Round to the nearest representable constant if unable to
	    represent a floating-point or complex constant due to limits
	    on precision.</li>
</ul>
<p>
These requirements apply both to literal constants and to the result
of evaluating <a href="#Constant_expressions">constant
expressions</a>.
</p>
625

Robert Griesemer's avatar
Robert Griesemer committed
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
<h2 id="Variables">Variables</h2>

<p>
A variable is a storage location for holding a <i>value</i>.
The set of permissible values is determined by the
variable's <i><a href="#Types">type</a></i>.
</p>

<p>
A <a href="#Variable_declarations">variable declaration</a>
or, for function parameters and results, the signature
of a <a href="#Function_declarations">function declaration</a>
or <a href="#Function_literals">function literal</a> reserves
storage for a named variable.

Calling the built-in function <a href="#Allocation"><code>new</code></a>
or taking the address of a <a href="#Composite_literals">composite literal</a>
allocates storage for a variable at run time.
Such an anonymous variable is referred to via a (possibly implicit)
<a href="#Address_operators">pointer indirection</a>.
</p>

<p>
<i>Structured</i> variables of <a href="#Array_types">array</a>, <a href="#Slice_types">slice</a>,
and <a href="#Struct_types">struct</a> types have elements and fields that may
be <a href="#Address_operators">addressed</a> individually. Each such element
acts like a variable.
</p>

<p>
656
The <i>static type</i> (or just <i>type</i>) of a variable is the
Robert Griesemer's avatar
Robert Griesemer committed
657 658 659 660 661 662 663 664 665
type given in its declaration, the type provided in the
<code>new</code> call or composite literal, or the type of
an element of a structured variable.
Variables of interface type also have a distinct <i>dynamic type</i>,
which is the concrete type of the value assigned to the variable at run time
(unless the value is the predeclared identifier <code>nil</code>,
which has no type).
The dynamic type may vary during execution but values stored in interface
variables are always <a href="#Assignability">assignable</a>
666 667
to the static type of the variable.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684

<pre>
var x interface{}  // x is nil and has static type interface{}
var v *T           // v has value nil, static type *T
x = 42             // x has value 42 and dynamic type int
x = v              // x has value (*T)(nil) and dynamic type *T
</pre>

<p>
A variable's value is retrieved by referring to the variable in an
<a href="#Expressions">expression</a>; it is the most recent value
<a href="#Assignments">assigned</a> to the variable.
If a variable has not yet been assigned a value, its value is the
<a href="#The_zero_value">zero value</a> for its type.
</p>


685
<h2 id="Types">Types</h2>
686

687
<p>
Robert Griesemer's avatar
Robert Griesemer committed
688
A type determines the set of values and operations specific to values of that
689 690 691 692
type. Types may be <i>named</i> or <i>unnamed</i>. Named types are specified
by a (possibly <a href="#Qualified_identifiers">qualified</a>)
<a href="#Type_declarations"><i>type name</i></a>; unnamed types are specified
using a <i>type literal</i>, which composes a new type from existing types.
Rob Pike's avatar
Rob Pike committed
693
</p>
694

695
<pre class="ebnf">
Rob Pike's avatar
Rob Pike committed
696
Type      = TypeName | TypeLit | "(" Type ")" .
697
TypeName  = identifier | QualifiedIdent .
Rob Pike's avatar
Rob Pike committed
698 699
TypeLit   = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
	    SliceType | MapType | ChannelType .
700
</pre>
701

702
<p>
703 704 705 706 707
Named instances of the boolean, numeric, and string types are
<a href="#Predeclared_identifiers">predeclared</a>.
<i>Composite types</i>&mdash;array, struct, pointer, function,
interface, slice, map, and channel types&mdash;may be constructed using
type literals.
Rob Pike's avatar
Rob Pike committed
708
</p>
709

710 711
<p>
Each type <code>T</code> has an <i>underlying type</i>: If <code>T</code>
712 713
is one of the predeclared boolean, numeric, or string types, or a type literal,
the corresponding underlying
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
type is <code>T</code> itself. Otherwise, <code>T</code>'s underlying type
is the underlying type of the type to which <code>T</code> refers in its
<a href="#Type_declarations">type declaration</a>.
</p>

<pre>
   type T1 string
   type T2 T1
   type T3 []T1
   type T4 T3
</pre>

<p>
The underlying type of <code>string</code>, <code>T1</code>, and <code>T2</code>
is <code>string</code>. The underlying type of <code>[]T1</code>, <code>T3</code>,
and <code>T4</code> is <code>[]T1</code>.
</p>

732
<h3 id="Method_sets">Method sets</h3>
Rob Pike's avatar
Rob Pike committed
733
<p>
734
A type may have a <i>method set</i> associated with it.
735
The method set of an <a href="#Interface_types">interface type</a> is its interface.
736 737 738 739
The method set of any other type <code>T</code> consists of all
<a href="#Method_declarations">methods</a> declared with receiver type <code>T</code>.
The method set of the corresponding <a href="#Pointer_types">pointer type</a> <code>*T</code>
is the set of all methods declared with receiver <code>*T</code> or <code>T</code>
Robert Griesemer's avatar
Robert Griesemer committed
740
(that is, it also contains the method set of <code>T</code>).
741 742
Further rules apply to structs containing anonymous fields, as described
in the section on <a href="#Struct_types">struct types</a>.
Robert Griesemer's avatar
Robert Griesemer committed
743
Any other type has an empty method set.
744
In a method set, each method must have a
745 746
<a href="#Uniqueness_of_identifiers">unique</a>
non-<a href="#Blank_identifier">blank</a> <a href="#MethodName">method name</a>.
Rob Pike's avatar
Rob Pike committed
747
</p>
Robert Griesemer's avatar
Robert Griesemer committed
748

749 750 751 752 753 754
<p>
The method set of a type determines the interfaces that the
type <a href="#Interface_types">implements</a>
and the methods that can be <a href="#Calls">called</a>
using a receiver of that type.
</p>
755

756 757
<h3 id="Boolean_types">Boolean types</h3>

758
<p>
759 760 761
A <i>boolean type</i> represents the set of Boolean truth values
denoted by the predeclared constants <code>true</code>
and <code>false</code>. The predeclared boolean type is <code>bool</code>.
762
</p>
763

764
<h3 id="Numeric_types">Numeric types</h3>
765

Rob Pike's avatar
Rob Pike committed
766
<p>
767 768
A <i>numeric type</i> represents sets of integer or floating-point values.
The predeclared architecture-independent numeric types are:
Rob Pike's avatar
Rob Pike committed
769
</p>
770

Rob Pike's avatar
Rob Pike committed
771
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
772 773 774 775 776 777 778 779 780
uint8       the set of all unsigned  8-bit integers (0 to 255)
uint16      the set of all unsigned 16-bit integers (0 to 65535)
uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)

int8        the set of all signed  8-bit integers (-128 to 127)
int16       the set of all signed 16-bit integers (-32768 to 32767)
int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
781

Rob Pike's avatar
Rob Pike committed
782 783
float32     the set of all IEEE-754 32-bit floating-point numbers
float64     the set of all IEEE-754 64-bit floating-point numbers
784

Rob Pike's avatar
Rob Pike committed
785 786
complex64   the set of all complex numbers with float32 real and imaginary parts
complex128  the set of all complex numbers with float64 real and imaginary parts
Rob Pike's avatar
Rob Pike committed
787

788
byte        alias for uint8
789
rune        alias for int32
790
</pre>
791

Rob Pike's avatar
Rob Pike committed
792
<p>
Robert Griesemer's avatar
Robert Griesemer committed
793 794
The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using
<a href="http://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>.
Rob Pike's avatar
Rob Pike committed
795
</p>
796

Rob Pike's avatar
Rob Pike committed
797
<p>
798
There is also a set of predeclared numeric types with implementation-specific sizes:
Rob Pike's avatar
Rob Pike committed
799
</p>
800

801
<pre class="grammar">
802
uint     either 32 or 64 bits
803
int      same size as uint
804
uintptr  an unsigned integer large enough to store the uninterpreted bits of a pointer value
805
</pre>
806

807
<p>
808
To avoid portability issues all numeric types are distinct except
809
<code>byte</code>, which is an alias for <code>uint8</code>, and
810
<code>rune</code>, which is an alias for <code>int32</code>.
811
Conversions
812
are required when different numeric types are mixed in an expression
Rob Pike's avatar
Rob Pike committed
813
or assignment. For instance, <code>int32</code> and <code>int</code>
814
are not the same type even though they may have the same size on a
Rob Pike's avatar
Rob Pike committed
815
particular architecture.
816

817

818
<h3 id="String_types">String types</h3>
819

820
<p>
821
A <i>string type</i> represents the set of string values.
822 823
A string value is a (possibly empty) sequence of bytes.
Strings are immutable: once created,
Rob Pike's avatar
Rob Pike committed
824
it is impossible to change the contents of a string.
825
The predeclared string type is <code>string</code>.
826
</p>
Rob Pike's avatar
Rob Pike committed
827 828

<p>
829 830 831
The length of a string <code>s</code> (its size in bytes) can be discovered using
the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
The length is a compile-time constant if the string is a constant.
832 833
A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>
0 through <code>len(s)-1</code>.
834 835 836
It is illegal to take the address of such an element; if
<code>s[i]</code> is the <code>i</code>'th byte of a
string, <code>&amp;s[i]</code> is invalid.
Rob Pike's avatar
Rob Pike committed
837
</p>
838 839


840
<h3 id="Array_types">Array types</h3>
Russ Cox's avatar
Russ Cox committed
841 842 843

<p>
An array is a numbered sequence of elements of a single
844 845
type, called the element type.
The number of elements is called the length and is never
Russ Cox's avatar
Russ Cox committed
846 847 848
negative.
</p>

849
<pre class="ebnf">
Russ Cox's avatar
Russ Cox committed
850 851
ArrayType   = "[" ArrayLength "]" ElementType .
ArrayLength = Expression .
852
ElementType = Type .
Russ Cox's avatar
Russ Cox committed
853 854 855
</pre>

<p>
856 857
The length is part of the array's type; it must evaluate to a
non-negative <a href="#Constants">constant</a> representable by a value
858 859
of type <code>int</code>.
The length of array <code>a</code> can be discovered
860
using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
861
The elements can be addressed by integer <a href="#Index_expressions">indices</a>
862
0 through <code>len(a)-1</code>.
863 864
Array types are always one-dimensional but may be composed to form
multi-dimensional types.
Russ Cox's avatar
Russ Cox committed
865 866 867 868 869 870
</p>

<pre>
[32]byte
[2*N] struct { x, y int32 }
[1000]*float64
871 872
[3][5]int
[2][2][2]float64  // same as [2]([2]([2]float64))
Russ Cox's avatar
Russ Cox committed
873 874
</pre>

875
<h3 id="Slice_types">Slice types</h3>
Russ Cox's avatar
Russ Cox committed
876 877

<p>
878
A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and
879 880
provides access to a numbered sequence of elements from that array.
A slice type denotes the set of all slices of arrays of its element type.
881
The value of an uninitialized slice is <code>nil</code>.
Russ Cox's avatar
Russ Cox committed
882 883
</p>

884
<pre class="ebnf">
Russ Cox's avatar
Russ Cox committed
885 886 887 888 889 890
SliceType = "[" "]" ElementType .
</pre>

<p>
Like arrays, slices are indexable and have a length.  The length of a
slice <code>s</code> can be discovered by the built-in function
891
<a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during
892 893
execution.  The elements can be addressed by integer <a href="#Index_expressions">indices</a>
0 through <code>len(s)-1</code>.  The slice index of a
Russ Cox's avatar
Russ Cox committed
894 895 896 897 898
given element may be less than the index of the same element in the
underlying array.
</p>
<p>
A slice, once initialized, is always associated with an underlying
Rob Pike's avatar
Rob Pike committed
899
array that holds its elements.  A slice therefore shares storage
Russ Cox's avatar
Russ Cox committed
900 901 902 903 904
with its array and with other slices of the same array; by contrast,
distinct arrays always represent distinct storage.
</p>
<p>
The array underlying a slice may extend past the end of the slice.
905
The <i>capacity</i> is a measure of that extent: it is the sum of
Russ Cox's avatar
Russ Cox committed
906
the length of the slice and the length of the array beyond the slice;
907
a slice of length up to that capacity can be created by
Robert Griesemer's avatar
Robert Griesemer committed
908
<a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice.
Russ Cox's avatar
Russ Cox committed
909
The capacity of a slice <code>a</code> can be discovered using the
910
built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.
Russ Cox's avatar
Russ Cox committed
911 912 913
</p>

<p>
914 915 916 917
A new, initialized slice value for a given element type <code>T</code> is
made using the built-in function
<a href="#Making_slices_maps_and_channels"><code>make</code></a>,
which takes a slice type
918 919 920
and parameters specifying the length and optionally the capacity.
A slice created with <code>make</code> always allocates a new, hidden array
to which the returned slice value refers. That is, executing
Russ Cox's avatar
Russ Cox committed
921 922 923 924 925
</p>

<pre>
make([]T, length, capacity)
</pre>
926

Russ Cox's avatar
Russ Cox committed
927
<p>
928 929
produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a>
it, so these two expressions are equivalent:
Russ Cox's avatar
Russ Cox committed
930 931 932 933 934 935 936
</p>

<pre>
make([]int, 50, 100)
new([100]int)[0:50]
</pre>

937 938 939 940
<p>
Like arrays, slices are always one-dimensional but may be composed to construct
higher-dimensional objects.
With arrays of arrays, the inner arrays are, by construction, always the same length;
941 942
however with slices of slices (or arrays of slices), the inner lengths may vary dynamically.
Moreover, the inner slices must be initialized individually.
943
</p>
Russ Cox's avatar
Russ Cox committed
944

945
<h3 id="Struct_types">Struct types</h3>
946

Rob Pike's avatar
Rob Pike committed
947
<p>
948 949 950 951
A struct is a sequence of named elements, called fields, each of which has a
name and a type. Field names may be specified explicitly (IdentifierList) or
implicitly (AnonymousField).
Within a struct, non-<a href="#Blank_identifier">blank</a> field names must
952
be <a href="#Uniqueness_of_identifiers">unique</a>.
Rob Pike's avatar
Rob Pike committed
953
</p>
954

955
<pre class="ebnf">
956
StructType     = "struct" "{" { FieldDecl ";" } "}" .
957 958
FieldDecl      = (IdentifierList Type | AnonymousField) [ Tag ] .
AnonymousField = [ "*" ] TypeName .
959
Tag            = string_lit .
960
</pre>
961

962
<pre>
963 964
// An empty struct.
struct {}
965

Robert Griesemer's avatar
Robert Griesemer committed
966
// A struct with 6 fields.
967
struct {
968
	x, y int
969 970
	u float32
	_ float32  // padding
971 972
	A *[]int
	F func()
973 974
}
</pre>
975

Rob Pike's avatar
Rob Pike committed
976
<p>
Russ Cox's avatar
Russ Cox committed
977 978 979
A field declared with a type but no explicit field name is an <i>anonymous field</i>,
also called an <i>embedded</i> field or an embedding of the type in the struct.
An embedded type must be specified as
980
a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>,
981
and <code>T</code> itself may not be
982
a pointer type. The unqualified type name acts as the field name.
Rob Pike's avatar
Rob Pike committed
983
</p>
984

985 986 987
<pre>
// A struct with four anonymous fields of type T1, *T2, P.T3 and *P.T4
struct {
988 989 990 991 992
	T1        // field name is T1
	*T2       // field name is T2
	P.T3      // field name is T3
	*P.T4     // field name is T4
	x, y int  // field names are x and y
993
}
994 995
</pre>

Rob Pike's avatar
Rob Pike committed
996
<p>
997 998
The following declaration is illegal because field names must be unique
in a struct type:
Rob Pike's avatar
Rob Pike committed
999
</p>
1000

1001
<pre>
1002
struct {
1003 1004 1005
	T     // conflicts with anonymous field *T and *P.T
	*T    // conflicts with anonymous field T and *P.T
	*P.T  // conflicts with anonymous field T and *T
1006
}
1007
</pre>
1008

1009
<p>
1010 1011 1012 1013
A field or <a href="#Method_declarations">method</a> <code>f</code> of an
anonymous field in a struct <code>x</code> is called <i>promoted</i> if
<code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes
that field or method <code>f</code>.
Rob Pike's avatar
Rob Pike committed
1014
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1015

1016 1017 1018 1019 1020
<p>
Promoted fields act like ordinary fields
of a struct except that they cannot be used as field names in
<a href="#Composite_literals">composite literals</a> of the struct.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1021

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
<p>
Given a struct type <code>S</code> and a type named <code>T</code>,
promoted methods are included in the method set of the struct as follows:
</p>
<ul>
	<li>
	If <code>S</code> contains an anonymous field <code>T</code>,
	the <a href="#Method_sets">method sets</a> of <code>S</code>
	and <code>*S</code> both include promoted methods with receiver
	<code>T</code>. The method set of <code>*S</code> also
	includes promoted methods with receiver <code>*T</code>.
	</li>
1034

1035 1036 1037 1038 1039
	<li>
	If <code>S</code> contains an anonymous field <code>*T</code>,
	the method sets of <code>S</code> and <code>*S</code> both
	include promoted methods with receiver <code>T</code> or
	<code>*T</code>.
Robert Griesemer's avatar
Robert Griesemer committed
1040 1041
	</li>
</ul>
1042

Rob Pike's avatar
Rob Pike committed
1043
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1044
A field declaration may be followed by an optional string literal <i>tag</i>,
1045
which becomes an attribute for all the fields in the corresponding
1046 1047
field declaration. An empty tag string is equivalent to an absent tag.
The tags are made visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a>
1048
and take part in <a href="#Type_identity">type identity</a> for structs
Rob Pike's avatar
Rob Pike committed
1049 1050
but are otherwise ignored.
</p>
1051

1052
<pre>
1053
struct {
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
	x, y float64 ""  // an empty tag string is like an absent tag
	name string  "any string is permitted as a tag"
	_    [4]byte "ceci n'est pas un champ de structure"
}

// A struct corresponding to a TimeStamp protocol buffer.
// The tag strings define the protocol buffer field numbers;
// they follow the convention outlined by the reflect package.
struct {
	microsec  uint64 `protobuf:"1"`
	serverIP6 uint64 `protobuf:"2"`
1065
}
1066
</pre>
1067

1068
<h3 id="Pointer_types">Pointer types</h3>
1069

Rob Pike's avatar
Rob Pike committed
1070
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1071
A pointer type denotes the set of all pointers to <a href="#Variables">variables</a> of a given
1072
type, called the <i>base type</i> of the pointer.
Peter Mundy's avatar
Peter Mundy committed
1073
The value of an uninitialized pointer is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
1074
</p>
1075

1076
<pre class="ebnf">
1077
PointerType = "*" BaseType .
1078
BaseType    = Type .
1079
</pre>
1080

1081
<pre>
Robert Griesemer's avatar
Robert Griesemer committed
1082 1083
*Point
*[4]int
1084
</pre>
1085

1086
<h3 id="Function_types">Function types</h3>
1087

Rob Pike's avatar
Rob Pike committed
1088
<p>
1089
A function type denotes the set of all functions with the same parameter
Peter Mundy's avatar
Peter Mundy committed
1090
and result types. The value of an uninitialized variable of function type
1091
is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
1092
</p>
1093

1094
<pre class="ebnf">
Rob Pike's avatar
Rob Pike committed
1095 1096
FunctionType   = "func" Signature .
Signature      = Parameters [ Result ] .
1097
Result         = Parameters | Type .
1098
Parameters     = "(" [ ParameterList [ "," ] ] ")" .
Rob Pike's avatar
Rob Pike committed
1099
ParameterList  = ParameterDecl { "," ParameterDecl } .
Russ Cox's avatar
Russ Cox committed
1100
ParameterDecl  = [ IdentifierList ] [ "..." ] Type .
1101 1102 1103
</pre>

<p>
Rob Pike's avatar
Rob Pike committed
1104 1105
Within a list of parameters or results, the names (IdentifierList)
must either all be present or all be absent. If present, each name
1106 1107 1108 1109 1110
stands for one item (parameter or result) of the specified type and
all non-<a href="#Blank_identifier">blank</a> names in the signature
must be <a href="#Uniqueness_of_identifiers">unique</a>.
If absent, each type stands for one item of that type.
Parameter and result
Rob Pike's avatar
Rob Pike committed
1111
lists are always parenthesized except that if there is exactly
Robert Griesemer's avatar
Robert Griesemer committed
1112
one unnamed result it may be written as an unparenthesized type.
Rob Pike's avatar
Rob Pike committed
1113
</p>
Russ Cox's avatar
Russ Cox committed
1114

Robert Griesemer's avatar
Robert Griesemer committed
1115
<p>
1116
The final incoming parameter in a function signature may have
Robert Griesemer's avatar
Robert Griesemer committed
1117 1118 1119
a type prefixed with <code>...</code>.
A function with such a parameter is called <i>variadic</i> and
may be invoked with zero or more arguments for that parameter.
Rob Pike's avatar
Rob Pike committed
1120
</p>
1121 1122

<pre>
Russ Cox's avatar
Russ Cox committed
1123
func()
Robert Griesemer's avatar
Robert Griesemer committed
1124 1125
func(x int) int
func(a, _ int, z float32) bool
1126
func(a, b int, z float32) (bool)
Robert Griesemer's avatar
Robert Griesemer committed
1127
func(prefix string, values ...int)
1128 1129
func(a, b int, z float64, opt ...interface{}) (success bool)
func(int, int, float64) (float64, *[]int)
Russ Cox's avatar
Russ Cox committed
1130
func(n int) func(p *T)
1131 1132 1133
</pre>


1134
<h3 id="Interface_types">Interface types</h3>
1135

Rob Pike's avatar
Rob Pike committed
1136
<p>
1137
An interface type specifies a <a href="#Method_sets">method set</a> called its <i>interface</i>.
Robert Griesemer's avatar
Robert Griesemer committed
1138 1139
A variable of interface type can store a value of any type with a method set
that is any superset of the interface. Such a type is said to
1140
<i>implement the interface</i>.
Peter Mundy's avatar
Peter Mundy committed
1141
The value of an uninitialized variable of interface type is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
1142
</p>
1143

1144
<pre class="ebnf">
1145
InterfaceType      = "interface" "{" { MethodSpec ";" } "}" .
1146 1147
MethodSpec         = MethodName Signature | InterfaceTypeName .
MethodName         = identifier .
Rob Pike's avatar
Rob Pike committed
1148
InterfaceTypeName  = TypeName .
1149
</pre>
1150

1151
<p>
1152
As with all method sets, in an interface type, each method must have a
1153 1154
<a href="#Uniqueness_of_identifiers">unique</a>
non-<a href="#Blank_identifier">blank</a> name.
1155 1156
</p>

1157
<pre>
Rob Pike's avatar
Rob Pike committed
1158
// A simple File interface
1159
interface {
1160 1161 1162
	Read(b Buffer) bool
	Write(b Buffer) bool
	Close()
1163 1164
}
</pre>
1165

Rob Pike's avatar
Rob Pike committed
1166
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1167
More than one type may implement an interface.
Rob Pike's avatar
Rob Pike committed
1168
For instance, if two types <code>S1</code> and <code>S2</code>
Robert Griesemer's avatar
Robert Griesemer committed
1169
have the method set
Rob Pike's avatar
Rob Pike committed
1170
</p>
1171

1172
<pre>
1173 1174 1175
func (p T) Read(b Buffer) bool { return … }
func (p T) Write(b Buffer) bool { return … }
func (p T) Close() { … }
1176
</pre>
1177

Rob Pike's avatar
Rob Pike committed
1178 1179 1180 1181 1182 1183
<p>
(where <code>T</code> stands for either <code>S1</code> or <code>S2</code>)
then the <code>File</code> interface is implemented by both <code>S1</code> and
<code>S2</code>, regardless of what other methods
<code>S1</code> and <code>S2</code> may have or share.
</p>
1184

Rob Pike's avatar
Rob Pike committed
1185 1186 1187 1188 1189
<p>
A type implements any interface comprising any subset of its methods
and may therefore implement several distinct interfaces. For
instance, all types implement the <i>empty interface</i>:
</p>
1190

1191
<pre>
1192
interface{}
1193
</pre>
1194

Rob Pike's avatar
Rob Pike committed
1195 1196
<p>
Similarly, consider this interface specification,
Robert Griesemer's avatar
Robert Griesemer committed
1197
which appears within a <a href="#Type_declarations">type declaration</a>
1198
to define an interface called <code>Locker</code>:
Rob Pike's avatar
Rob Pike committed
1199
</p>
1200 1201

<pre>
1202
type Locker interface {
1203 1204
	Lock()
	Unlock()
1205
}
1206
</pre>
1207

Rob Pike's avatar
Rob Pike committed
1208 1209 1210
<p>
If <code>S1</code> and <code>S2</code> also implement
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1211

1212
<pre>
1213 1214
func (p T) Lock() { … }
func (p T) Unlock() { … }
1215 1216
</pre>

1217
<p>
1218
they implement the <code>Locker</code> interface as well
Rob Pike's avatar
Rob Pike committed
1219 1220
as the <code>File</code> interface.
</p>
1221

Rob Pike's avatar
Rob Pike committed
1222
<p>
1223 1224 1225 1226 1227
An interface <code>T</code> may use a (possibly qualified) interface type
name <code>E</code> in place of a method specification. This is called
<i>embedding</i> interface <code>E</code> in <code>T</code>; it adds
all (exported and non-exported) methods of <code>E</code> to the interface
<code>T</code>.
Rob Pike's avatar
Rob Pike committed
1228
</p>
1229

1230
<pre>
1231
type ReadWriter interface {
1232 1233
	Read(b Buffer) bool
	Write(b Buffer) bool
1234
}
1235

1236
type File interface {
1237 1238
	ReadWriter  // same as adding the methods of ReadWriter
	Locker      // same as adding the methods of Locker
1239
	Close()
1240
}
1241 1242 1243 1244 1245 1246

type LockedFile interface {
	Locker
	File        // illegal: Lock, Unlock not unique
	Lock()      // illegal: Lock not unique
}
1247
</pre>
1248

1249
<p>
Russ Cox's avatar
Russ Cox committed
1250 1251
An interface type <code>T</code> may not embed itself
or any interface type that embeds <code>T</code>, recursively.
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
</p>

<pre>
// illegal: Bad cannot embed itself
type Bad interface {
	Bad
}

// illegal: Bad1 cannot embed itself using Bad2
type Bad1 interface {
	Bad2
}
type Bad2 interface {
	Bad1
}
</pre>

1269
<h3 id="Map_types">Map types</h3>
1270

Rob Pike's avatar
Rob Pike committed
1271 1272
<p>
A map is an unordered group of elements of one type, called the
1273
element type, indexed by a set of unique <i>keys</i> of another type,
1274
called the key type.
1275
The value of an uninitialized map is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
1276
</p>
1277

1278
<pre class="ebnf">
1279
MapType     = "map" "[" KeyType "]" ElementType .
1280
KeyType     = Type .
1281
</pre>
1282

1283
<p>
1284 1285
The <a href="#Comparison_operators">comparison operators</a>
<code>==</code> and <code>!=</code> must be fully defined
1286 1287
for operands of the key type; thus the key type must not be a function, map, or
slice.
1288
If the key type is an interface type, these
Rob Pike's avatar
Rob Pike committed
1289
comparison operators must be defined for the dynamic key values;
Rob Pike's avatar
Rob Pike committed
1290
failure will cause a <a href="#Run_time_panics">run-time panic</a>.
Rob Pike's avatar
Rob Pike committed
1291 1292

</p>
1293

1294
<pre>
1295 1296 1297
map[string]int
map[*T]struct{ x, y float64 }
map[string]interface{}
1298
</pre>
1299

Rob Pike's avatar
Rob Pike committed
1300
<p>
1301 1302
The number of map elements is called its length.
For a map <code>m</code>, it can be discovered using the
1303
built-in function <a href="#Length_and_capacity"><code>len</code></a>
1304 1305
and may change during execution. Elements may be added during execution
using <a href="#Assignments">assignments</a> and retrieved with
1306
<a href="#Index_expressions">index expressions</a>; they may be removed with the
1307
<a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function.
Rob Pike's avatar
Rob Pike committed
1308 1309 1310
</p>
<p>
A new, empty map value is made using the built-in
1311 1312
function <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
which takes the map type and an optional capacity hint as arguments:
Rob Pike's avatar
Rob Pike committed
1313
</p>
1314

1315
<pre>
1316 1317
make(map[string]int)
make(map[string]int, 100)
1318
</pre>
1319

1320 1321 1322
<p>
The initial capacity does not bound its size:
maps grow to accommodate the number of items
1323 1324 1325
stored in them, with the exception of <code>nil</code> maps.
A <code>nil</code> map is equivalent to an empty map except that no elements
may be added.
1326

1327
<h3 id="Channel_types">Channel types</h3>
1328

Rob Pike's avatar
Rob Pike committed
1329
<p>
1330 1331 1332 1333 1334 1335
A channel provides a mechanism for
<a href="#Go_statements">concurrently executing functions</a>
to communicate by
<a href="#Send_statements">sending</a> and
<a href="#Receive_operator">receiving</a>
values of a specified element type.
1336
The value of an uninitialized channel is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
1337
</p>
1338

1339
<pre class="ebnf">
1340
ChannelType = ( "chan" | "chan" "&lt;-" | "&lt;-" "chan" ) ElementType .
1341
</pre>
1342

1343
<p>
1344
The optional <code>&lt;-</code> operator specifies the channel <i>direction</i>,
1345
<i>send</i> or <i>receive</i>. If no direction is given, the channel is
1346
<i>bidirectional</i>.
1347 1348
A channel may be constrained only to send or only to receive by
<a href="#Conversions">conversion</a> or <a href="#Assignments">assignment</a>.
1349 1350 1351
</p>

<pre>
1352 1353 1354
chan T          // can be used to send and receive values of type T
chan&lt;- float64  // can only be used to send float64s
&lt;-chan int      // can only be used to receive ints
1355 1356
</pre>

Rob Pike's avatar
Rob Pike committed
1357
<p>
1358 1359
The <code>&lt;-</code> operator associates with the leftmost <code>chan</code>
possible:
Rob Pike's avatar
Rob Pike committed
1360
</p>
1361

1362
<pre>
1363 1364 1365
chan&lt;- chan int    // same as chan&lt;- (chan int)
chan&lt;- &lt;-chan int  // same as chan&lt;- (&lt;-chan int)
&lt;-chan &lt;-chan int  // same as &lt;-chan (&lt;-chan int)
1366
chan (&lt;-chan int)
1367
</pre>
1368

Rob Pike's avatar
Rob Pike committed
1369
<p>
1370
A new, initialized channel
1371 1372
value can be made using the built-in function
<a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1373
which takes the channel type and an optional <i>capacity</i> as arguments:
Rob Pike's avatar
Rob Pike committed
1374
</p>
1375

1376
<pre>
1377
make(chan int, 100)
1378
</pre>
1379

Rob Pike's avatar
Rob Pike committed
1380
<p>
1381 1382
The capacity, in number of elements, sets the size of the buffer in the channel.
If the capacity is zero or absent, the channel is unbuffered and communication
1383 1384
succeeds only when both a sender and receiver are ready. Otherwise, the channel
is buffered and communication succeeds without blocking if the buffer
1385
is not full (sends) or not empty (receives).
1386
A <code>nil</code> channel is never ready for communication.
Rob Pike's avatar
Rob Pike committed
1387
</p>
1388

1389
<p>
1390
A channel may be closed with the built-in function
1391 1392
<a href="#Close"><code>close</code></a>.
The multi-valued assignment form of the
1393
<a href="#Receive_operator">receive operator</a>
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
reports whether a received value was sent before
the channel was closed.
</p>

<p>
A single channel may be used in
<a href="#Send_statements">send statements</a>,
<a href="#Receive_operator">receive operations</a>,
and calls to the built-in functions
<a href="#Length_and_capacity"><code>cap</code></a> and
<a href="#Length_and_capacity"><code>len</code></a>
by any number of goroutines without further synchronization.
Channels act as first-in-first-out queues.
For example, if one goroutine sends values on a channel
and a second goroutine receives them, the values are
received in the order sent.
1410 1411
</p>

1412
<h2 id="Properties_of_types_and_values">Properties of types and values</h2>
1413

1414 1415
<h3 id="Type_identity">Type identity</h3>

1416
<p>
1417
Two types are either <i>identical</i> or <i>different</i>.
1418
</p>
1419

1420
<p>
1421
Two <a href="#Types">named types</a> are identical if their type names originate in the same
1422
<a href="#Type_declarations">TypeSpec</a>.
1423
A named and an <a href="#Types">unnamed type</a> are always different. Two unnamed types are identical
1424
if the corresponding type literals are identical, that is, if they have the same
1425
literal structure and corresponding components have identical types. In detail:
1426
</p>
Rob Pike's avatar
Rob Pike committed
1427

1428
<ul>
1429 1430
	<li>Two array types are identical if they have identical element types and
	    the same array length.</li>
1431

1432
	<li>Two slice types are identical if they have identical element types.</li>
1433

1434
	<li>Two struct types are identical if they have the same sequence of fields,
1435 1436
	    and if corresponding fields have the same names, and identical types,
	    and identical tags.
1437 1438
	    Two anonymous fields are considered to have the same name. Lower-case field
	    names from different packages are always different.</li>
1439

1440
	<li>Two pointer types are identical if they have identical base types.</li>
1441

1442
	<li>Two function types are identical if they have the same number of parameters
Russ Cox's avatar
Russ Cox committed
1443 1444
	    and result values, corresponding parameter and result types are
	    identical, and either both functions are variadic or neither is.
1445
	    Parameter and result names are not required to match.</li>
1446

1447
	<li>Two interface types are identical if they have the same set of methods
1448 1449
	    with the same names and identical function types. Lower-case method names from
	    different packages are always different. The order of the methods is irrelevant.</li>
1450

1451
	<li>Two map types are identical if they have identical key and value types.</li>
1452

1453 1454
	<li>Two channel types are identical if they have identical value types and
	    the same direction.</li>
1455 1456 1457
</ul>

<p>
Rob Pike's avatar
Rob Pike committed
1458 1459
Given the declarations
</p>
1460 1461 1462

<pre>
type (
1463 1464
	T0 []string
	T1 []string
1465 1466
	T2 struct{ a, b int }
	T3 struct{ a, c int }
1467 1468
	T4 func(int, float64) *T0
	T5 func(x int, y float64) *[]string
1469
)
1470
</pre>
1471

Rob Pike's avatar
Rob Pike committed
1472
<p>
1473
these types are identical:
Rob Pike's avatar
Rob Pike committed
1474
</p>
1475

1476
<pre>
1477
T0 and T0
1478
[]int and []int
1479
struct{ a, b *T5 } and struct{ a, b *T5 }
1480
func(x int, y float64) *[]string and func(int, float64) (result *[]string)
1481
</pre>
1482

Rob Pike's avatar
Rob Pike committed
1483
<p>
1484
<code>T0</code> and <code>T1</code> are different because they are named types
1485 1486
with distinct declarations; <code>func(int, float64) *T0</code> and
<code>func(x int, y float64) *[]string</code> are different because <code>T0</code>
1487
is different from <code>[]string</code>.
Rob Pike's avatar
Rob Pike committed
1488
</p>
1489 1490


1491
<h3 id="Assignability">Assignability</h3>
Rob Pike's avatar
Rob Pike committed
1492 1493

<p>
Robert Griesemer's avatar
Robert Griesemer committed
1494
A value <code>x</code> is <i>assignable</i> to a <a href="#Variables">variable</a> of type <code>T</code>
1495
("<code>x</code> is assignable to <code>T</code>") in any of these cases:
Rob Pike's avatar
Rob Pike committed
1496
</p>
1497

Rob Pike's avatar
Rob Pike committed
1498 1499
<ul>
<li>
1500 1501 1502
<code>x</code>'s type is identical to <code>T</code>.
</li>
<li>
Rob Pike's avatar
Rob Pike committed
1503 1504
<code>x</code>'s type <code>V</code> and <code>T</code> have identical
<a href="#Types">underlying types</a> and at least one of <code>V</code>
1505
or <code>T</code> is not a <a href="#Types">named type</a>.
Robert Griesemer's avatar
Robert Griesemer committed
1506 1507
</li>
<li>
1508
<code>T</code> is an interface type and
1509 1510 1511 1512 1513
<code>x</code> <a href="#Interface_types">implements</a> <code>T</code>.
</li>
<li>
<code>x</code> is a bidirectional channel value, <code>T</code> is a channel type,
<code>x</code>'s type <code>V</code> and <code>T</code> have identical element types,
Rob Pike's avatar
Rob Pike committed
1514
and at least one of <code>V</code> or <code>T</code> is not a named type.
Rob Pike's avatar
Rob Pike committed
1515 1516
</li>
<li>
1517 1518 1519 1520 1521 1522
<code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code>
is a pointer, function, slice, map, channel, or interface type.
</li>
<li>
<code>x</code> is an untyped <a href="#Constants">constant</a> representable
by a value of type <code>T</code>.
Robert Griesemer's avatar
Robert Griesemer committed
1523
</li>
Rob Pike's avatar
Rob Pike committed
1524 1525
</ul>

1526

1527
<h2 id="Blocks">Blocks</h2>
Robert Griesemer's avatar
Robert Griesemer committed
1528 1529

<p>
1530 1531
A <i>block</i> is a possibly empty sequence of declarations and statements
within matching brace brackets.
Robert Griesemer's avatar
Robert Griesemer committed
1532 1533 1534
</p>

<pre class="ebnf">
1535 1536
Block = "{" StatementList "}" .
StatementList = { Statement ";" } .
Robert Griesemer's avatar
Robert Griesemer committed
1537 1538 1539 1540 1541 1542 1543 1544 1545
</pre>

<p>
In addition to explicit blocks in the source code, there are implicit blocks:
</p>

<ol>
	<li>The <i>universe block</i> encompasses all Go source text.</li>

Robert Griesemer's avatar
Robert Griesemer committed
1546
	<li>Each <a href="#Packages">package</a> has a <i>package block</i> containing all
Robert Griesemer's avatar
Robert Griesemer committed
1547 1548 1549 1550 1551
	    Go source text for that package.</li>

	<li>Each file has a <i>file block</i> containing all Go source text
	    in that file.</li>

1552 1553 1554
	<li>Each <a href="#If_statements">"if"</a>,
	    <a href="#For_statements">"for"</a>, and
	    <a href="#Switch_statements">"switch"</a>
Robert Griesemer's avatar
Robert Griesemer committed
1555 1556
	    statement is considered to be in its own implicit block.</li>

1557 1558
	<li>Each clause in a <a href="#Switch_statements">"switch"</a>
	    or <a href="#Select_statements">"select"</a> statement
Robert Griesemer's avatar
Robert Griesemer committed
1559 1560 1561 1562
	    acts as an implicit block.</li>
</ol>

<p>
Robert Griesemer's avatar
Robert Griesemer committed
1563
Blocks nest and influence <a href="#Declarations_and_scope">scoping</a>.
Robert Griesemer's avatar
Robert Griesemer committed
1564 1565 1566
</p>


1567
<h2 id="Declarations_and_scope">Declarations and scope</h2>
1568 1569

<p>
1570 1571 1572 1573 1574 1575 1576
A <i>declaration</i> binds a non-<a href="#Blank_identifier">blank</a> identifier to a
<a href="#Constant_declarations">constant</a>,
<a href="#Type_declarations">type</a>,
<a href="#Variable_declarations">variable</a>,
<a href="#Function_declarations">function</a>,
<a href="#Labeled_statements">label</a>, or
<a href="#Import_declarations">package</a>.
1577
Every identifier in a program must be declared.
Robert Griesemer's avatar
Robert Griesemer committed
1578 1579
No identifier may be declared twice in the same block, and
no identifier may be declared in both the file and package block.
1580
</p>
1581

1582 1583 1584
<p>
The <a href="#Blank_identifier">blank identifier</a> may be used like any other identifier
in a declaration, but it does not introduce a binding and thus is not declared.
1585 1586 1587
In the package block, the identifier <code>init</code> may only be used for
<a href="#Package_initialization"><code>init</code> function</a> declarations,
and like the blank identifier it does not introduce a new binding.
1588 1589
</p>

1590
<pre class="ebnf">
Robert Griesemer's avatar
Robert Griesemer committed
1591 1592
Declaration   = ConstDecl | TypeDecl | VarDecl .
TopLevelDecl  = Declaration | FunctionDecl | MethodDecl .
1593
</pre>
1594

1595
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1596
The <i>scope</i> of a declared identifier is the extent of source text in which
1597
the identifier denotes the specified constant, type, variable, function, label, or package.
1598
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1599

1600
<p>
1601
Go is lexically scoped using <a href="#Blocks">blocks</a>:
1602
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1603

1604
<ol>
1605
	<li>The scope of a <a href="#Predeclared_identifiers">predeclared identifier</a> is the universe block.</li>
Robert Griesemer's avatar
Robert Griesemer committed
1606 1607

	<li>The scope of an identifier denoting a constant, type, variable,
1608 1609
	    or function (but not method) declared at top level (outside any
	    function) is the package block.</li>
Robert Griesemer's avatar
Robert Griesemer committed
1610

1611
	<li>The scope of the package name of an imported package is the file block
Robert Griesemer's avatar
Robert Griesemer committed
1612 1613
	    of the file containing the import declaration.</li>

1614 1615
	<li>The scope of an identifier denoting a method receiver, function parameter,
	    or result variable is the function body.</li>
Robert Griesemer's avatar
Robert Griesemer committed
1616 1617 1618

	<li>The scope of a constant or variable identifier declared
	    inside a function begins at the end of the ConstSpec or VarSpec
1619
	    (ShortVarDecl for short variable declarations)
Robert Griesemer's avatar
Robert Griesemer committed
1620 1621 1622
	    and ends at the end of the innermost containing block.</li>

	<li>The scope of a type identifier declared inside a function
Russ Cox's avatar
Russ Cox committed
1623
	    begins at the identifier in the TypeSpec
Robert Griesemer's avatar
Robert Griesemer committed
1624
	    and ends at the end of the innermost containing block.</li>
1625
</ol>
1626

1627
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1628 1629 1630
An identifier declared in a block may be redeclared in an inner block.
While the identifier of the inner declaration is in scope, it denotes
the entity declared by the inner declaration.
1631
</p>
1632

Robert Griesemer's avatar
Robert Griesemer committed
1633
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1634
The <a href="#Package_clause">package clause</a> is not a declaration; the package name
Robert Griesemer's avatar
Robert Griesemer committed
1635
does not appear in any scope. Its purpose is to identify the files belonging
1636
to the same <a href="#Packages">package</a> and to specify the default package name for import
Robert Griesemer's avatar
Robert Griesemer committed
1637 1638
declarations.
</p>
1639 1640


1641
<h3 id="Label_scopes">Label scopes</h3>
1642

Robert Griesemer's avatar
Robert Griesemer committed
1643
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1644
Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are
1645 1646 1647
used in the <a href="#Break_statements">"break"</a>,
<a href="#Continue_statements">"continue"</a>, and
<a href="#Goto_statements">"goto"</a> statements.
Russ Cox's avatar
Russ Cox committed
1648
It is illegal to define a label that is never used.
Robert Griesemer's avatar
Robert Griesemer committed
1649 1650 1651 1652 1653
In contrast to other identifiers, labels are not block scoped and do
not conflict with identifiers that are not labels. The scope of a label
is the body of the function in which it is declared and excludes
the body of any nested function.
</p>
1654 1655


1656 1657 1658
<h3 id="Blank_identifier">Blank identifier</h3>

<p>
1659 1660 1661 1662
The <i>blank identifier</i> is represented by the underscore character <code>_</code>.
It serves as an anonymous placeholder instead of a regular (non-blank)
identifier and has special meaning in <a href="#Declarations_and_scope">declarations</a>,
as an <a href="#Operands">operand</a>, and in <a href="#Assignments">assignments</a>.
1663 1664 1665
</p>


1666
<h3 id="Predeclared_identifiers">Predeclared identifiers</h3>
1667

1668
<p>
1669 1670
The following identifiers are implicitly declared in the
<a href="#Blocks">universe block</a>:
1671 1672
</p>
<pre class="grammar">
Russ Cox's avatar
Russ Cox committed
1673 1674 1675 1676
Types:
	bool byte complex64 complex128 error float32 float64
	int int8 int16 int32 int64 rune string
	uint uint8 uint16 uint32 uint64 uintptr
1677

1678
Constants:
1679 1680 1681 1682
	true false iota

Zero value:
	nil
1683

1684
Functions:
1685
	append cap close complex copy delete imag len
Robert Griesemer's avatar
Robert Griesemer committed
1686
	make new panic print println real recover
1687
</pre>
1688

1689

1690
<h3 id="Exported_identifiers">Exported identifiers</h3>
Robert Griesemer's avatar
Robert Griesemer committed
1691

1692
<p>
1693 1694
An identifier may be <i>exported</i> to permit access to it from another package.
An identifier is exported if both:
1695 1696
</p>
<ol>
1697 1698 1699 1700 1701
	<li>the first character of the identifier's name is a Unicode upper case
	letter (Unicode class "Lu"); and</li>
	<li>the identifier is declared in the <a href="#Blocks">package block</a>
	or it is a <a href="#Struct_types">field name</a> or
	<a href="#MethodName">method name</a>.</li>
1702
</ol>
1703
<p>
1704
All other identifiers are not exported.
1705
</p>
1706

1707

1708
<h3 id="Uniqueness_of_identifiers">Uniqueness of identifiers</h3>
Robert Griesemer's avatar
Robert Griesemer committed
1709 1710

<p>
1711 1712 1713 1714
Given a set of identifiers, an identifier is called <i>unique</i> if it is
<i>different</i> from every other in the set.
Two identifiers are different if they are spelled differently, or if they
appear in different <a href="#Packages">packages</a> and are not
Shenghou Ma's avatar
Shenghou Ma committed
1715
<a href="#Exported_identifiers">exported</a>. Otherwise, they are the same.
Robert Griesemer's avatar
Robert Griesemer committed
1716 1717
</p>

1718
<h3 id="Constant_declarations">Constant declarations</h3>
1719

1720 1721
<p>
A constant declaration binds a list of identifiers (the names of
Robert Griesemer's avatar
Robert Griesemer committed
1722 1723 1724 1725
the constants) to the values of a list of <a href="#Constant_expressions">constant expressions</a>.
The number of identifiers must be equal
to the number of expressions, and the <i>n</i>th identifier on
the left is bound to the value of the <i>n</i>th expression on the
1726 1727
right.
</p>
1728

1729
<pre class="ebnf">
1730
ConstDecl      = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1731
ConstSpec      = IdentifierList [ [ Type ] "=" ExpressionList ] .
1732

1733 1734
IdentifierList = identifier { "," identifier } .
ExpressionList = Expression { "," Expression } .
1735
</pre>
1736

1737
<p>
1738
If the type is present, all constants take the type specified, and
1739
the expressions must be <a href="#Assignability">assignable</a> to that type.
1740
If the type is omitted, the constants take the
1741 1742 1743 1744 1745 1746
individual types of the corresponding expressions.
If the expression values are untyped <a href="#Constants">constants</a>,
the declared constants remain untyped and the constant identifiers
denote the constant values. For instance, if the expression is a
floating-point literal, the constant identifier denotes a floating-point
constant, even if the literal's fractional part is zero.
1747
</p>
1748

1749
<pre>
1750
const Pi float64 = 3.14159265358979323846
1751
const zero = 0.0         // untyped floating-point constant
1752
const (
1753
	size int64 = 1024
1754
	eof        = -1  // untyped integer constant
1755
)
1756
const a, b, c = 3, 4, "foo"  // a = 3, b = 4, c = "foo", untyped integer and string constants
1757
const u, v float32 = 0, 3    // u = 0.0, v = 3.0
1758
</pre>
1759

1760 1761 1762 1763
<p>
Within a parenthesized <code>const</code> declaration list the
expression list may be omitted from any but the first declaration.
Such an empty list is equivalent to the textual substitution of the
Rob Pike's avatar
Rob Pike committed
1764
first preceding non-empty expression list and its type if any.
1765 1766 1767
Omitting the list of expressions is therefore equivalent to
repeating the previous list.  The number of identifiers must be equal
to the number of expressions in the previous list.
Robert Griesemer's avatar
Robert Griesemer committed
1768 1769
Together with the <a href="#Iota"><code>iota</code> constant generator</a>
this mechanism permits light-weight declaration of sequential values:
1770
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1771

1772
<pre>
1773
const (
1774 1775 1776 1777 1778 1779 1780 1781
	Sunday = iota
	Monday
	Tuesday
	Wednesday
	Thursday
	Friday
	Partyday
	numberOfDays  // this constant is not exported
1782
)
1783
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
1784 1785


1786
<h3 id="Iota">Iota</h3>
1787

1788
<p>
1789
Within a <a href="#Constant_declarations">constant declaration</a>, the predeclared identifier
1790 1791
<code>iota</code> represents successive untyped integer <a href="#Constants">
constants</a>. It is reset to 0 whenever the reserved word <code>const</code>
1792 1793
appears in the source and increments after each <a href="#ConstSpec">ConstSpec</a>.
It can be used to construct a set of related constants:
1794
</p>
1795

1796
<pre>
1797
const ( // iota is reset to 0
1798 1799 1800
	c0 = iota  // c0 == 0
	c1 = iota  // c1 == 1
	c2 = iota  // c2 == 2
1801 1802
)

1803 1804
const ( // iota is reset to 0
	a = 1 &lt;&lt; iota  // a == 1
1805
	b = 1 &lt;&lt; iota  // b == 2
1806 1807
	c = 3          // c == 3  (iota is not used but still incremented)
	d = 1 &lt;&lt; iota  // d == 8
1808 1809
)

1810
const ( // iota is reset to 0
1811 1812 1813
	u         = iota * 42  // u == 0     (untyped integer constant)
	v float64 = iota * 42  // v == 42.0  (float64 constant)
	w         = iota * 42  // w == 84    (untyped integer constant)
1814 1815
)

1816 1817
const x = iota  // x == 0  (iota has been reset)
const y = iota  // y == 0  (iota has been reset)
1818
</pre>
1819

1820
<p>
1821
Within an ExpressionList, the value of each <code>iota</code> is the same because
1822
it is only incremented after each ConstSpec:
1823
</p>
1824

1825
<pre>
1826
const (
1827 1828 1829 1830
	bit0, mask0 = 1 &lt;&lt; iota, 1&lt;&lt;iota - 1  // bit0 == 1, mask0 == 0
	bit1, mask1                           // bit1 == 2, mask1 == 1
	_, _                                  // skips iota == 2
	bit3, mask3                           // bit3 == 8, mask3 == 7
1831
)
1832
</pre>
1833

1834
<p>
1835 1836 1837
This last example exploits the implicit repetition of the
last non-empty expression list.
</p>
1838 1839


1840
<h3 id="Type_declarations">Type declarations</h3>
1841

1842
<p>
1843
A type declaration binds an identifier, the <i>type name</i>, to a new type
1844 1845 1846
that has the same <a href="#Types">underlying type</a> as an existing type,
and operations defined for the existing type are also defined for the new type.
The new type is <a href="#Type_identity">different</a> from the existing type.
1847
</p>
1848

1849
<pre class="ebnf">
1850
TypeDecl     = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
1851
TypeSpec     = identifier Type .
1852
</pre>
1853

1854
<pre>
1855
type IntArray [16]int
1856

1857
type (
1858
	Point struct{ x, y float64 }
1859 1860
	Polar Point
)
1861

1862
type TreeNode struct {
1863 1864
	left, right *TreeNode
	value *Comparable
1865 1866
}

1867
type Block interface {
1868 1869 1870
	BlockSize() int
	Encrypt(src, dst []byte)
	Decrypt(src, dst []byte)
1871
}
1872
</pre>
1873

1874 1875
<p>
The declared type does not inherit any <a href="#Method_declarations">methods</a>
1876
bound to the existing type, but the <a href="#Method_sets">method set</a>
1877
of an interface type or of elements of a composite type remains unchanged:
1878 1879 1880
</p>

<pre>
Rob Pike's avatar
Rob Pike committed
1881
// A Mutex is a data type with two methods, Lock and Unlock.
1882 1883 1884 1885 1886 1887 1888
type Mutex struct         { /* Mutex fields */ }
func (m *Mutex) Lock()    { /* Lock implementation */ }
func (m *Mutex) Unlock()  { /* Unlock implementation */ }

// NewMutex has the same composition as Mutex but its method set is empty.
type NewMutex Mutex

1889 1890 1891 1892
// The method set of the <a href="#Pointer_types">base type</a> of PtrMutex remains unchanged,
// but the method set of PtrMutex is empty.
type PtrMutex *Mutex

Robert Griesemer's avatar
Robert Griesemer committed
1893
// The method set of *PrintableMutex contains the methods
1894
// Lock and Unlock bound to its anonymous field Mutex.
1895
type PrintableMutex struct {
1896
	Mutex
1897
}
1898

1899 1900
// MyBlock is an interface type that has the same method set as Block.
type MyBlock Block
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
</pre>

<p>
A type declaration may be used to define a different boolean, numeric, or string
type and attach methods to it:
</p>

<pre>
type TimeZone int

const (
1912 1913 1914 1915
	EST TimeZone = -(5 + iota)
	CST
	MST
	PST
1916 1917 1918
)

func (tz TimeZone) String() string {
1919
	return fmt.Sprintf("GMT%+dh", tz)
1920 1921 1922 1923
}
</pre>


1924
<h3 id="Variable_declarations">Variable declarations</h3>
1925 1926

<p>
1927 1928
A variable declaration creates one or more variables, binds corresponding
identifiers to them, and gives each a type and an initial value.
1929
</p>
1930

1931
<pre class="ebnf">
1932
VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
1933
VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
1934
</pre>
1935

1936
<pre>
1937
var i int
1938
var U, V, W float64
1939
var k = 0
1940
var x, y float32 = -1, -2
1941
var (
1942
	i       int
1943 1944
	u, v, s = 2.0, 3.0, "bar"
)
Robert Griesemer's avatar
Robert Griesemer committed
1945
var re, im = complexSqrt(-1)
1946
var _, found = entries[name]  // map lookup; only interested in "found"
1947
</pre>
1948

1949
<p>
1950
If a list of expressions is given, the variables are initialized
1951
with the expressions following the rules for <a href="#Assignments">assignments</a>.
1952
Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>.
1953
</p>
1954

1955
<p>
1956 1957 1958 1959 1960 1961 1962 1963
If a type is present, each variable is given that type.
Otherwise, each variable is given the type of the corresponding
initialization value in the assignment.
If that value is an untyped constant, it is first
<a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>;
if it is an untyped boolean value, it is first converted to type <code>bool</code>.
The predeclared value <code>nil</code> cannot be used to initialize a variable
with no explicit type.
1964
</p>
1965

1966
<pre>
Brad Fitzpatrick's avatar
Brad Fitzpatrick committed
1967
var d = math.Sin(0.5)  // d is float64
1968 1969 1970 1971
var i = 42             // i is int
var t, ok = x.(T)      // t is T, ok is bool
var n = nil            // illegal
</pre>
1972 1973 1974 1975 1976 1977

<p>
Implementation restriction: A compiler may make it illegal to declare a variable
inside a <a href="#Function_declarations">function body</a> if the variable is
never used.
</p>
1978

1979
<h3 id="Short_variable_declarations">Short variable declarations</h3>
1980

1981
<p>
1982
A <i>short variable declaration</i> uses the syntax:
1983
</p>
1984

1985
<pre class="ebnf">
1986
ShortVarDecl = IdentifierList ":=" ExpressionList .
1987
</pre>
1988

1989
<p>
1990
It is shorthand for a regular <a href="#Variable_declarations">variable declaration</a>
1991
with initializer expressions but no types:
1992
</p>
1993

1994 1995
<pre class="grammar">
"var" IdentifierList = ExpressionList .
1996
</pre>
1997

1998
<pre>
1999 2000 2001 2002 2003
i, j := 0, 10
f := func() int { return 7 }
ch := make(chan int)
r, w := os.Pipe(fd)  // os.Pipe() returns two values
_, y, _ := coord(p)  // coord() returns three values; only interested in y coordinate
2004
</pre>
2005

Rob Pike's avatar
Rob Pike committed
2006
<p>
2007 2008 2009 2010 2011 2012
Unlike regular variable declarations, a short variable declaration may <i>redeclare</i>
variables provided they were originally declared earlier in the same block
(or the parameter lists if the block is the function body) with the same type, 
and at least one of the non-<a href="#Blank_identifier">blank</a> variables is new.
As a consequence, redeclaration can only appear in a multi-variable short declaration.
Redeclaration does not introduce a new variable; it just assigns a new value to the original.
Rob Pike's avatar
Rob Pike committed
2013 2014 2015
</p>

<pre>
2016 2017
field1, offset := nextField(str, 0)
field2, offset := nextField(str, offset)  // redeclares offset
2018
a, a := 1, 2                              // illegal: double declaration of a or no new variable if a was declared elsewhere
Rob Pike's avatar
Rob Pike committed
2019 2020
</pre>

Rob Pike's avatar
Rob Pike committed
2021
<p>
2022
Short variable declarations may appear only inside functions.
2023 2024 2025 2026 2027
In some contexts such as the initializers for
<a href="#If_statements">"if"</a>,
<a href="#For_statements">"for"</a>, or
<a href="#Switch_statements">"switch"</a> statements,
they can be used to declare local temporary variables.
Rob Pike's avatar
Rob Pike committed
2028
</p>
2029

2030
<h3 id="Function_declarations">Function declarations</h3>
2031

2032
<p>
2033 2034
A function declaration binds an identifier, the <i>function name</i>,
to a function.
2035
</p>
2036

2037
<pre class="ebnf">
2038
FunctionDecl = "func" FunctionName ( Function | Signature ) .
2039
FunctionName = identifier .
2040 2041
Function     = Signature FunctionBody .
FunctionBody = Block .
2042
</pre>
2043

2044 2045 2046 2047 2048 2049
<p>
If the function's <a href="#Function_types">signature</a> declares
result parameters, the function body's statement list must end in
a <a href="#Terminating_statements">terminating statement</a>.
</p>

2050
<pre>
2051 2052 2053 2054
func IndexRune(s string, r rune) int {
	for i, c := range s {
		if c == r {
			return i
2055 2056
		}
	}
2057
	// invalid: missing return statement
2058 2059 2060
}
</pre>

2061 2062 2063 2064 2065
<p>
A function declaration may omit the body. Such a declaration provides the
signature for a function implemented outside Go, such as an assembly routine.
</p>

2066 2067 2068
<pre>
func min(x int, y int) int {
	if x &lt; y {
2069
		return x
2070
	}
2071
	return y
2072
}
2073 2074

func flushICache(begin, end uintptr)  // implemented externally
2075
</pre>
2076

2077
<h3 id="Method_declarations">Method declarations</h3>
2078

2079
<p>
2080 2081 2082
A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>.
A method declaration binds an identifier, the <i>method name</i>, to a method,
and associates the method with the receiver's <i>base type</i>.
Rob Pike's avatar
Rob Pike committed
2083
</p>
2084

2085
<pre class="ebnf">
2086
MethodDecl   = "func" Receiver MethodName ( Function | Signature ) .
2087
Receiver     = Parameters .
2088 2089
</pre>

2090
<p>
Paolo Martini's avatar
Paolo Martini committed
2091
The receiver is specified via an extra parameter section preceding the method
2092
name. That parameter section must declare a single non-variadic parameter, the receiver.
2093 2094
Its type must be of the form <code>T</code> or <code>*T</code> (possibly using
parentheses) where <code>T</code> is a type name. The type denoted by <code>T</code> is called
2095 2096 2097
the receiver <i>base type</i>; it must not be a pointer or interface type and
it must be declared in the same package as the method.
The method is said to be <i>bound</i> to the base type and the method name
2098 2099
is visible only within <a href="#Selectors">selectors</a> for type <code>T</code>
or <code>*T</code>.
2100 2101 2102
</p>

<p>
2103 2104 2105 2106 2107 2108 2109 2110 2111
A non-<a href="#Blank_identifier">blank</a> receiver identifier must be
<a href="#Uniqueness_of_identifiers">unique</a> in the method signature.
If the receiver's value is not referenced inside the body of the method,
its identifier may be omitted in the declaration. The same applies in
general to parameters of functions and methods.
</p>

<p>
For a base type, the non-blank names of methods bound to it must be unique.
2112 2113
If the base type is a <a href="#Struct_types">struct type</a>,
the non-blank method and field names must be distinct.
Rob Pike's avatar
Rob Pike committed
2114
</p>
2115

2116 2117 2118
<p>
Given type <code>Point</code>, the declarations
</p>
2119

2120
<pre>
2121 2122
func (p *Point) Length() float64 {
	return math.Sqrt(p.x * p.x + p.y * p.y)
2123
}
2124

2125 2126 2127
func (p *Point) Scale(factor float64) {
	p.x *= factor
	p.y *= factor
2128 2129
}
</pre>
2130

2131
<p>
Rob Pike's avatar
Rob Pike committed
2132 2133
bind the methods <code>Length</code> and <code>Scale</code>,
with receiver type <code>*Point</code>,
2134 2135
to the base type <code>Point</code>.
</p>
2136

Rob Pike's avatar
Rob Pike committed
2137 2138 2139 2140 2141 2142
<p>
The type of a method is the type of a function with the receiver as first
argument.  For instance, the method <code>Scale</code> has type
</p>

<pre>
2143
func(p *Point, factor float64)
Rob Pike's avatar
Rob Pike committed
2144 2145 2146 2147 2148 2149
</pre>

<p>
However, a function declared this way is not a method.
</p>

2150

2151
<h2 id="Expressions">Expressions</h2>
2152

2153
<p>
Rob Pike's avatar
Rob Pike committed
2154
An expression specifies the computation of a value by applying
2155
operators and functions to operands.
Rob Pike's avatar
Rob Pike committed
2156
</p>
2157

2158
<h3 id="Operands">Operands</h3>
2159

2160
<p>
2161
Operands denote the elementary values in an expression. An operand may be a
2162 2163
literal, a (possibly <a href="#Qualified_identifiers">qualified</a>)
non-<a href="#Blank_identifier">blank</a> identifier denoting a
2164 2165 2166 2167 2168
<a href="#Constant_declarations">constant</a>,
<a href="#Variable_declarations">variable</a>, or
<a href="#Function_declarations">function</a>,
a <a href="#Method_expressions">method expression</a> yielding a function,
or a parenthesized expression.
2169
</p>
2170

2171 2172 2173 2174 2175
<p>
The <a href="#Blank_identifier">blank identifier</a> may appear as an
operand only on the left-hand side of an <a href="#Assignments">assignment</a>.
</p>

2176
<pre class="ebnf">
2177 2178 2179
Operand     = Literal | OperandName | MethodExpr | "(" Expression ")" .
Literal     = BasicLit | CompositeLit | FunctionLit .
BasicLit    = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
2180
OperandName = identifier | QualifiedIdent.
2181
</pre>
2182

2183
<h3 id="Qualified_identifiers">Qualified identifiers</h3>
2184

2185
<p>
2186 2187 2188
A qualified identifier is an identifier qualified with a package name prefix.
Both the package name and the identifier must not be
<a href="#Blank_identifier">blank</a>.
Rob Pike's avatar
Rob Pike committed
2189
</p>
2190

2191
<pre class="ebnf">
2192
QualifiedIdent = PackageName "." identifier .
2193
</pre>
2194

Rob Pike's avatar
Rob Pike committed
2195
<p>
Robert Griesemer's avatar
Robert Griesemer committed
2196 2197
A qualified identifier accesses an identifier in a different package, which
must be <a href="#Import_declarations">imported</a>.
2198 2199
The identifier must be <a href="#Exported_identifiers">exported</a> and
declared in the <a href="#Blocks">package block</a> of that package.
Rob Pike's avatar
Rob Pike committed
2200 2201 2202
</p>

<pre>
2203
math.Sin	// denotes the Sin function in package math
Rob Pike's avatar
Rob Pike committed
2204
</pre>
2205

2206
<h3 id="Composite_literals">Composite literals</h3>
2207

Rob Pike's avatar
Rob Pike committed
2208 2209 2210
<p>
Composite literals construct values for structs, arrays, slices, and maps
and create a new value each time they are evaluated.
2211
They consist of the type of the literal followed by a brace-bound list of elements.
2212
Each element may optionally be preceded by a corresponding key.
Rob Pike's avatar
Rob Pike committed
2213
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2214

2215
<pre class="ebnf">
2216
CompositeLit  = LiteralType LiteralValue .
Rob Pike's avatar
Rob Pike committed
2217
LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
2218
                SliceType | MapType | TypeName .
2219
LiteralValue  = "{" [ ElementList [ "," ] ] "}" .
2220 2221
ElementList   = KeyedElement { "," KeyedElement } .
KeyedElement  = [ Key ":" ] Element .
2222
Key           = FieldName | Expression | LiteralValue .
Rob Pike's avatar
Rob Pike committed
2223
FieldName     = identifier .
2224
Element       = Expression | LiteralValue .
2225
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2226

Rob Pike's avatar
Rob Pike committed
2227
<p>
2228
The LiteralType's underlying type must be a struct, array, slice, or map type
2229 2230
(the grammar enforces this constraint except when the type is given
as a TypeName).
2231
The types of the elements and keys must be <a href="#Assignability">assignable</a>
2232
to the respective field, element, and key types of the literal type;
2233
there is no additional conversion.
2234
The key is interpreted as a field name for struct literals,
2235
an index for array and slice literals, and a key for map literals.
2236 2237 2238
For map literals, all elements must have a key. It is an error
to specify multiple elements with the same field name or
constant key value.
Rob Pike's avatar
Rob Pike committed
2239
</p>
2240

2241 2242
<p>
For struct literals the following rules apply:
2243
</p>
2244
<ul>
2245
	<li>A key must be a field name declared in the struct type.
2246
	</li>
2247
	<li>An element list that does not contain any keys must
2248 2249 2250 2251 2252
	    list an element for each struct field in the
	    order in which the fields are declared.
	</li>
	<li>If any element has a key, every element must have a key.
	</li>
2253
	<li>An element list that contains keys does not need to
2254 2255 2256 2257
	    have an element for each struct field. Omitted fields
	    get the zero value for that field.
	</li>
	<li>A literal may omit the element list; such a literal evaluates
2258
	    to the zero value for its type.
2259 2260 2261 2262 2263 2264 2265 2266 2267
	</li>
	<li>It is an error to specify an element for a non-exported
	    field of a struct belonging to a different package.
	</li>
</ul>

<p>
Given the declarations
</p>
2268
<pre>
2269 2270
type Point3D struct { x, y, z float64 }
type Line struct { p, q Point3D }
2271
</pre>
2272

Rob Pike's avatar
Rob Pike committed
2273 2274 2275
<p>
one may write
</p>
2276

2277
<pre>
2278 2279
origin := Point3D{}                            // zero value for Point3D
line := Line{origin, Point3D{y: -4, z: 12.3}}  // zero value for line.q.x
2280 2281
</pre>

2282 2283 2284
<p>
For array and slice literals the following rules apply:
</p>
2285 2286 2287 2288
<ul>
	<li>Each element has an associated integer index marking
	    its position in the array.
	</li>
2289 2290 2291 2292
	<li>An element with a key uses the key as its index. The
	    key must be a non-negative constant representable by
	    a value of type <code>int</code>; and if it is typed
	    it must be of integer type.
2293 2294 2295 2296 2297 2298
	</li>
	<li>An element without a key uses the previous element's index plus one.
	    If the first element has no key, its index is zero.
	</li>
</ul>

2299
<p>
2300
<a href="#Address_operators">Taking the address</a> of a composite literal
Robert Griesemer's avatar
Robert Griesemer committed
2301 2302
generates a pointer to a unique <a href="#Variables">variable</a> initialized
with the literal's value.
2303 2304
</p>
<pre>
2305
var pointer *Point3D = &amp;Point3D{y: 1000}
2306
</pre>
2307

Rob Pike's avatar
Rob Pike committed
2308
<p>
2309
The length of an array literal is the length specified in the literal type.
2310
If fewer elements than the length are provided in the literal, the missing
Rob Pike's avatar
Rob Pike committed
2311
elements are set to the zero value for the array element type.
2312 2313 2314
It is an error to provide elements with index values outside the index range
of the array. The notation <code>...</code> specifies an array length equal
to the maximum element index plus one.
Rob Pike's avatar
Rob Pike committed
2315
</p>
2316

2317
<pre>
2318 2319 2320
buffer := [10]string{}             // len(buffer) == 10
intSet := [6]int{1, 2, 3, 5}       // len(intSet) == 6
days := [...]string{"Sat", "Sun"}  // len(days) == 2
2321
</pre>
2322

Rob Pike's avatar
Rob Pike committed
2323 2324
<p>
A slice literal describes the entire underlying array literal.
2325
Thus the length and capacity of a slice literal are the maximum
2326
element index plus one. A slice literal has the form
Rob Pike's avatar
Rob Pike committed
2327
</p>
2328

2329
<pre>
2330
[]T{x1, x2, … xn}
2331
</pre>
2332

Rob Pike's avatar
Rob Pike committed
2333
<p>
2334
and is shorthand for a slice operation applied to an array:
Rob Pike's avatar
Rob Pike committed
2335
</p>
2336

2337
<pre>
Russ Cox's avatar
Russ Cox committed
2338 2339
tmp := [n]T{x1, x2, … xn}
tmp[0 : n]
2340
</pre>
2341

2342 2343
<p>
Within a composite literal of array, slice, or map type <code>T</code>,
2344 2345 2346 2347
elements or map keys that are themselves composite literals may elide the respective
literal type if it is identical to the element or key type of <code>T</code>.
Similarly, elements or keys that are addresses of composite literals may elide
the <code>&amp;T</code> when the element or key type is <code>*T</code>.
2348 2349 2350
</p>

<pre>
2351 2352 2353 2354
[...]Point{{1.5, -3.5}, {0, 0}}     // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}}
[][]int{{1, 2, 3}, {4, 5}}          // same as [][]int{[]int{1, 2, 3}, []int{4, 5}}
[][]Point{{{0, 1}, {1, 2}}}         // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}}
map[string]Point{"orig": {0, 0}}    // same as map[string]Point{"orig": Point{0, 0}}
2355

2356 2357 2358
[...]*Point{{1.5, -3.5}, {0, 0}}    // same as [...]*Point{&amp;Point{1.5, -3.5}, &amp;Point{0, 0}}

map[Point]string{{0, 0}: "orig"}    // same as map[Point]string{Point{0, 0}: "orig"}
2359 2360
</pre>

2361 2362
<p>
A parsing ambiguity arises when a composite literal using the
2363 2364 2365 2366 2367 2368 2369
TypeName form of the LiteralType appears as an operand between the
<a href="#Keywords">keyword</a> and the opening brace of the block
of an "if", "for", or "switch" statement, and the composite literal
is not enclosed in parentheses, square brackets, or curly braces.
In this rare case, the opening brace of the literal is erroneously parsed
as the one introducing the block of statements. To resolve the ambiguity,
the composite literal must appear within parentheses.
2370 2371 2372
</p>

<pre>
2373 2374
if x == (T{a,b,c}[i]) { … }
if (x == T{a,b,c}[i]) { … }
2375 2376
</pre>

2377 2378 2379 2380 2381 2382
<p>
Examples of valid array, slice, and map literals:
</p>

<pre>
// list of prime numbers
Rob Pike's avatar
Rob Pike committed
2383
primes := []int{2, 3, 5, 7, 9, 2147483647}
2384 2385

// vowels[ch] is true if ch is a vowel
2386
vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}
2387

2388 2389
// the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1}
filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1}
2390 2391

// frequencies in Hz for equal-tempered scale (A4 = 440Hz)
2392
noteFrequency := map[string]float32{
2393 2394 2395 2396 2397 2398
	"C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83,
	"G0": 24.50, "A0": 27.50, "B0": 30.87,
}
</pre>


2399
<h3 id="Function_literals">Function literals</h3>
2400

Rob Pike's avatar
Rob Pike committed
2401
<p>
2402
A function literal represents an anonymous <a href="#Function_declarations">function</a>.
Rob Pike's avatar
Rob Pike committed
2403
</p>
2404

2405
<pre class="ebnf">
2406
FunctionLit = "func" Function .
2407
</pre>
2408

2409
<pre>
2410
func(a, b int, z float64) bool { return a*b &lt; int(z) }
2411
</pre>
2412

Rob Pike's avatar
Rob Pike committed
2413 2414 2415
<p>
A function literal can be assigned to a variable or invoked directly.
</p>
2416

2417
<pre>
Rob Pike's avatar
Rob Pike committed
2418
f := func(x, y int) int { return x + y }
2419
func(ch chan int) { ch &lt;- ACK }(replyChan)
2420
</pre>
2421

Rob Pike's avatar
Rob Pike committed
2422 2423
<p>
Function literals are <i>closures</i>: they may refer to variables
2424 2425
defined in a surrounding function. Those variables are then shared between
the surrounding function and the function literal, and they survive as long
Rob Pike's avatar
Rob Pike committed
2426 2427
as they are accessible.
</p>
2428

2429

2430
<h3 id="Primary_expressions">Primary expressions</h3>
2431

2432 2433 2434 2435
<p>
Primary expressions are the operands for unary and binary expressions.
</p>

2436
<pre class="ebnf">
2437 2438
PrimaryExpr =
	Operand |
2439
	Conversion |
2440 2441 2442
	PrimaryExpr Selector |
	PrimaryExpr Index |
	PrimaryExpr Slice |
2443
	PrimaryExpr TypeAssertion |
2444
	PrimaryExpr Arguments .
2445

2446 2447
Selector       = "." identifier .
Index          = "[" Expression "]" .
2448 2449
Slice          = "[" [ Expression ] ":" [ Expression ] "]" |
                 "[" [ Expression ] ":" Expression ":" Expression "]" .
2450
TypeAssertion  = "." "(" Type ")" .
2451
Arguments      = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
2452 2453 2454 2455 2456 2457 2458 2459
</pre>


<pre>
x
2
(s + ".txt")
f(3.1415, true)
2460
Point{1, 2}
2461 2462 2463 2464 2465 2466 2467
m["foo"]
s[i : j + 1]
obj.color
f.p[i].x()
</pre>


2468
<h3 id="Selectors">Selectors</h3>
2469

Rob Pike's avatar
Rob Pike committed
2470
<p>
2471 2472 2473
For a <a href="#Primary_expressions">primary expression</a> <code>x</code>
that is not a <a href="#Package_clause">package name</a>, the
<i>selector expression</i>
Rob Pike's avatar
Rob Pike committed
2474
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2475

2476 2477 2478
<pre>
x.f
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2479

2480
<p>
2481 2482 2483 2484 2485 2486 2487
denotes the field or method <code>f</code> of the value <code>x</code>
(or sometimes <code>*x</code>; see below).
The identifier <code>f</code> is called the (field or method) <i>selector</i>;
it must not be the <a href="#Blank_identifier">blank identifier</a>.
The type of the selector expression is the type of <code>f</code>.
If <code>x</code> is a package name, see the section on
<a href="#Qualified_identifiers">qualified identifiers</a>.
Rob Pike's avatar
Rob Pike committed
2488
</p>
2489

2490
<p>
Rob Pike's avatar
Rob Pike committed
2491 2492
A selector <code>f</code> may denote a field or method <code>f</code> of
a type <code>T</code>, or it may refer
2493 2494
to a field or method <code>f</code> of a nested
<a href="#Struct_types">anonymous field</a> of <code>T</code>.
Rob Pike's avatar
Rob Pike committed
2495 2496 2497 2498 2499 2500 2501 2502
The number of anonymous fields traversed
to reach <code>f</code> is called its <i>depth</i> in <code>T</code>.
The depth of a field or method <code>f</code>
declared in <code>T</code> is zero.
The depth of a field or method <code>f</code> declared in
an anonymous field <code>A</code> in <code>T</code> is the
depth of <code>f</code> in <code>A</code> plus one.
</p>
2503

2504
<p>
2505
The following rules apply to selectors:
Rob Pike's avatar
Rob Pike committed
2506
</p>
2507

Rob Pike's avatar
Rob Pike committed
2508 2509 2510
<ol>
<li>
For a value <code>x</code> of type <code>T</code> or <code>*T</code>
2511
where <code>T</code> is not a pointer or interface type,
Rob Pike's avatar
Rob Pike committed
2512 2513 2514
<code>x.f</code> denotes the field or method at the shallowest depth
in <code>T</code> where there
is such an <code>f</code>.
2515 2516
If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a>
with shallowest depth, the selector expression is illegal.
Rob Pike's avatar
Rob Pike committed
2517
</li>
2518

Rob Pike's avatar
Rob Pike committed
2519
<li>
2520
For a value <code>x</code> of type <code>I</code> where <code>I</code>
2521
is an interface type, <code>x.f</code> denotes the actual method with name
2522
<code>f</code> of the dynamic value of <code>x</code>.
2523 2524 2525
If there is no method with name <code>f</code> in the
<a href="#Method_sets">method set</a> of <code>I</code>, the selector
expression is illegal.
Rob Pike's avatar
Rob Pike committed
2526
</li>
2527 2528 2529 2530 2531 2532 2533

<li>
As an exception, if the type of <code>x</code> is a named pointer type
and <code>(*x).f</code> is a valid selector expression denoting a field
(but not a method), <code>x.f</code> is shorthand for <code>(*x).f</code>.
</li>

Rob Pike's avatar
Rob Pike committed
2534 2535
<li>
In all other cases, <code>x.f</code> is illegal.
2536
</li>
2537

2538
<li>
Russ Cox's avatar
Russ Cox committed
2539 2540 2541 2542 2543
If <code>x</code> is of pointer type and has the value
<code>nil</code> and <code>x.f</code> denotes a struct field,
assigning to or evaluating <code>x.f</code>
causes a <a href="#Run_time_panics">run-time panic</a>.
</li>
2544

Russ Cox's avatar
Russ Cox committed
2545 2546 2547 2548
<li>
If <code>x</code> is of interface type and has the value
<code>nil</code>, <a href="#Calls">calling</a> or
<a href="#Method_values">evaluating</a> the method <code>x.f</code>
2549
causes a <a href="#Run_time_panics">run-time panic</a>.
2550
</li>
Rob Pike's avatar
Rob Pike committed
2551
</ol>
2552

2553
<p>
Rob Pike's avatar
Rob Pike committed
2554 2555
For example, given the declarations:
</p>
2556

2557 2558
<pre>
type T0 struct {
2559
	x int
2560
}
2561

2562
func (*T0) M0()
2563

2564
type T1 struct {
2565
	y int
2566
}
2567

2568
func (T1) M1()
2569

2570
type T2 struct {
2571 2572 2573
	z int
	T1
	*T0
2574
}
Robert Griesemer's avatar
Robert Griesemer committed
2575

2576
func (*T2) M2()
Robert Griesemer's avatar
Robert Griesemer committed
2577

2578 2579 2580 2581 2582
type Q *T2

var t T2     // with t.T0 != nil
var p *T2    // with p != nil and (*p).T0 != nil
var q Q = p
2583
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2584

Rob Pike's avatar
Rob Pike committed
2585 2586 2587
<p>
one may write:
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2588

2589
<pre>
2590 2591
t.z          // t.z
t.y          // t.T1.y
Robert Griesemer's avatar
Robert Griesemer committed
2592
t.x          // (*t.T0).x
2593 2594 2595 2596 2597 2598 2599

p.z          // (*p).z
p.y          // (*p).T1.y
p.x          // (*(*p).T0).x

q.x          // (*(*q).T0).x        (*q).x is a valid field selector

2600
p.M0()       // ((*p).T0).M0()      M0 expects *T0 receiver
2601
p.M1()       // ((*p).T1).M1()      M1 expects T1 receiver
2602 2603
p.M2()       // p.M2()              M2 expects *T2 receiver
t.M2()       // (&amp;t).M2()           M2 expects *T2 receiver, see section on Calls
2604
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2605

2606 2607 2608 2609 2610 2611
<p>
but the following is invalid:
</p>

<pre>
q.M0()       // (*q).M0 is valid but not a field selector
2612
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2613 2614


2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
<h3 id="Method_expressions">Method expressions</h3>

<p>
If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
<code>T.M</code> is a function that is callable as a regular function
with the same arguments as <code>M</code> prefixed by an additional
argument that is the receiver of the method.
</p>

<pre class="ebnf">
MethodExpr    = ReceiverType "." MethodName .
ReceiverType  = TypeName | "(" "*" TypeName ")" | "(" ReceiverType ")" .
</pre>

<p>
Consider a struct type <code>T</code> with two methods,
<code>Mv</code>, whose receiver is of type <code>T</code>, and
<code>Mp</code>, whose receiver is of type <code>*T</code>.
</p>

<pre>
type T struct {
	a int
}
func (tv  T) Mv(a int) int         { return 0 }  // value receiver
func (tp *T) Mp(f float32) float32 { return 1 }  // pointer receiver

var t T
</pre>

<p>
The expression
</p>

<pre>
T.Mv
</pre>

<p>
yields a function equivalent to <code>Mv</code> but
with an explicit receiver as its first argument; it has signature
</p>

<pre>
func(tv T, a int) int
</pre>

<p>
That function may be called normally with an explicit receiver, so
these five invocations are equivalent:
</p>

<pre>
t.Mv(7)
T.Mv(t, 7)
(T).Mv(t, 7)
f1 := T.Mv; f1(t, 7)
f2 := (T).Mv; f2(t, 7)
</pre>

<p>
Similarly, the expression
</p>

<pre>
(*T).Mp
</pre>

<p>
yields a function value representing <code>Mp</code> with signature
</p>

<pre>
func(tp *T, f float32) float32
</pre>

<p>
For a method with a value receiver, one can derive a function
with an explicit pointer receiver, so
</p>

<pre>
(*T).Mv
</pre>

<p>
yields a function value representing <code>Mv</code> with signature
</p>

<pre>
func(tv *T, a int) int
</pre>

<p>
Such a function indirects through the receiver to create a value
to pass as the receiver to the underlying method;
the method does not overwrite the value whose address is passed in
the function call.
</p>

<p>
The final case, a value-receiver function for a pointer-receiver method,
is illegal because pointer-receiver methods are not in the method set
of the value type.
</p>

<p>
Function values derived from methods are called with function call syntax;
the receiver is provided as the first argument to the call.
That is, given <code>f := T.Mv</code>, <code>f</code> is invoked
as <code>f(t, 7)</code> not <code>t.f(7)</code>.
To construct a function that binds the receiver, use a
<a href="#Function_literals">function literal</a> or
<a href="#Method_values">method value</a>.
</p>

<p>
It is legal to derive a function value from a method of an interface type.
The resulting function takes an explicit receiver of that interface type.
</p>

<h3 id="Method_values">Method values</h3>

<p>
If the expression <code>x</code> has static type <code>T</code> and
<code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
<code>x.M</code> is called a <i>method value</i>.
The method value <code>x.M</code> is a function value that is callable
with the same arguments as a method call of <code>x.M</code>.
The expression <code>x</code> is evaluated and saved during the evaluation of the
method value; the saved copy is then used as the receiver in any calls,
which may be executed later.
</p>

<p>
The type <code>T</code> may be an interface or non-interface type.
</p>

<p>
As in the discussion of <a href="#Method_expressions">method expressions</a> above,
consider a struct type <code>T</code> with two methods,
<code>Mv</code>, whose receiver is of type <code>T</code>, and
<code>Mp</code>, whose receiver is of type <code>*T</code>.
</p>

<pre>
type T struct {
	a int
}
func (tv  T) Mv(a int) int         { return 0 }  // value receiver
func (tp *T) Mp(f float32) float32 { return 1 }  // pointer receiver

var t T
var pt *T
func makeT() T
</pre>

<p>
The expression
</p>

<pre>
t.Mv
</pre>

<p>
yields a function value of type
</p>

<pre>
func(int) int
</pre>

<p>
These two invocations are equivalent:
</p>

<pre>
t.Mv(7)
f := t.Mv; f(7)
</pre>

<p>
Similarly, the expression
</p>

<pre>
pt.Mp
</pre>

<p>
yields a function value of type
</p>

<pre>
func(float32) float32
</pre>

<p>
As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver
using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>.
</p>

<p>
As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver
using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&amp;t).Mp</code>.
</p>

<pre>
f := t.Mv; f(7)   // like t.Mv(7)
f := pt.Mp; f(7)  // like pt.Mp(7)
f := pt.Mv; f(7)  // like (*pt).Mv(7)
f := t.Mp; f(7)   // like (&amp;t).Mp(7)
f := makeT().Mp   // invalid: result of makeT() is not addressable
</pre>

<p>
Although the examples above use non-interface types, it is also legal to create a method value
from a value of interface type.
</p>

<pre>
var i interface { M(int) } = myVal
f := i.M; f(7)  // like i.M(7)
</pre>


2842
<h3 id="Index_expressions">Index expressions</h3>
2843

Rob Pike's avatar
Rob Pike committed
2844
<p>
Robert Griesemer's avatar
Robert Griesemer committed
2845
A primary expression of the form
Rob Pike's avatar
Rob Pike committed
2846
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2847

2848 2849 2850
<pre>
a[x]
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2851

Rob Pike's avatar
Rob Pike committed
2852
<p>
2853 2854 2855
denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>.
The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively.
The following rules apply:
Rob Pike's avatar
Rob Pike committed
2856
</p>
2857

2858 2859 2860 2861
<p>
If <code>a</code> is not a map:
</p>
<ul>
2862 2863
	<li>the index <code>x</code> must be of integer type or untyped;
	    it is <i>in range</i> if <code>0 &lt;= x &lt; len(a)</code>,
2864 2865
	    otherwise it is <i>out of range</i></li>
	<li>a <a href="#Constants">constant</a> index must be non-negative
2866
	    and representable by a value of type <code>int</code>
2867 2868
</ul>

2869
<p>
2870
For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>:
Rob Pike's avatar
Rob Pike committed
2871
</p>
2872
<ul>
2873
	<li>a <a href="#Constants">constant</a> index must be in range</li>
2874
	<li>if <code>x</code> is out of range at run time,
2875
	    a <a href="#Run_time_panics">run-time panic</a> occurs</li>
Rob Pike's avatar
Rob Pike committed
2876
	<li><code>a[x]</code> is the array element at index <code>x</code> and the type of
2877
	    <code>a[x]</code> is the element type of <code>A</code></li>
2878 2879 2880
</ul>

<p>
2881 2882 2883 2884 2885 2886 2887 2888
For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type:
</p>
<ul>
	<li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li>
</ul>

<p>
For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>:
2889 2890
</p>
<ul>
2891
	<li>if <code>x</code> is out of range at run time,
2892 2893
	    a <a href="#Run_time_panics">run-time panic</a> occurs</li>
	<li><code>a[x]</code> is the slice element at index <code>x</code> and the type of
2894
	    <code>a[x]</code> is the element type of <code>S</code></li>
2895
</ul>
2896 2897

<p>
2898
For <code>a</code> of <a href="#String_types">string type</a>:
2899 2900
</p>
<ul>
2901
	<li>a <a href="#Constants">constant</a> index must be in range
2902 2903 2904
	    if the string <code>a</code> is also constant</li>
	<li>if <code>x</code> is out of range at run time,
	    a <a href="#Run_time_panics">run-time panic</a> occurs</li>
2905
	<li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of
2906
	    <code>a[x]</code> is <code>byte</code></li>
2907
	<li><code>a[x]</code> may not be assigned to</li>
2908 2909
</ul>

2910
<p>
2911
For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>:
Rob Pike's avatar
Rob Pike committed
2912
</p>
2913
<ul>
2914
	<li><code>x</code>'s type must be
2915 2916
	    <a href="#Assignability">assignable</a>
	    to the key type of <code>M</code></li>
2917
	<li>if the map contains an entry with key <code>x</code>,
2918 2919
	    <code>a[x]</code> is the map value with key <code>x</code>
	    and the type of <code>a[x]</code> is the value type of <code>M</code></li>
2920
	<li>if the map is <code>nil</code> or does not contain such an entry,
2921 2922
	    <code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
	    for the value type of <code>M</code></li>
2923
</ul>
Robert Griesemer's avatar
Robert Griesemer committed
2924

2925
<p>
2926
Otherwise <code>a[x]</code> is illegal.
Rob Pike's avatar
Rob Pike committed
2927 2928 2929
</p>

<p>
2930
An index expression on a map <code>a</code> of type <code>map[K]V</code>
2931
used in an <a href="#Assignments">assignment</a> or initialization of the special form
Rob Pike's avatar
Rob Pike committed
2932 2933 2934
</p>

<pre>
2935 2936 2937
v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
2938
var v, ok T = a[x]
Rob Pike's avatar
Rob Pike committed
2939 2940 2941
</pre>

<p>
2942
yields an additional untyped boolean value. The value of <code>ok</code> is
2943
<code>true</code> if the key <code>x</code> is present in the map, and
2944
<code>false</code> otherwise.
Rob Pike's avatar
Rob Pike committed
2945 2946
</p>

2947 2948 2949 2950 2951
<p>
Assigning to an element of a <code>nil</code> map causes a
<a href="#Run_time_panics">run-time panic</a>.
</p>

2952

Robert Griesemer's avatar
Robert Griesemer committed
2953 2954 2955 2956 2957 2958 2959 2960 2961
<h3 id="Slice_expressions">Slice expressions</h3>

<p>
Slice expressions construct a substring or slice from a string, array, pointer
to array, or slice. There are two variants: a simple form that specifies a low
and high bound, and a full form that also specifies a bound on the capacity.
</p>

<h4>Simple slice expressions</h4>
2962

Rob Pike's avatar
Rob Pike committed
2963
<p>
2964
For a string, array, pointer to array, or slice <code>a</code>, the primary expression
Rob Pike's avatar
Rob Pike committed
2965
</p>
2966

2967
<pre>
2968
a[low : high]
2969
</pre>
2970

Rob Pike's avatar
Rob Pike committed
2971
<p>
2972 2973 2974
constructs a substring or slice. The <i>indices</i> <code>low</code> and
<code>high</code> select which elements of operand <code>a</code> appear
in the result. The result has indices starting at 0 and length equal to
2975
<code>high</code>&nbsp;-&nbsp;<code>low</code>.
2976 2977 2978 2979
After slicing the array <code>a</code>
</p>

<pre>
2980 2981
a := [5]int{1, 2, 3, 4, 5}
s := a[1:4]
2982 2983 2984 2985
</pre>

<p>
the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements
Rob Pike's avatar
Rob Pike committed
2986
</p>
2987

2988 2989 2990
<pre>
s[0] == 2
s[1] == 3
2991
s[2] == 4
2992
</pre>
2993

Rob Pike's avatar
Rob Pike committed
2994
<p>
2995
For convenience, any of the indices may be omitted. A missing <code>low</code>
2996 2997
index defaults to zero; a missing <code>high</code> index defaults to the length of the
sliced operand:
2998 2999
</p>

3000
<pre>
3001
a[2:]  // same as a[2 : len(a)]
3002 3003
a[:3]  // same as a[0 : 3]
a[:]   // same as a[0 : len(a)]
3004 3005
</pre>

3006
<p>
3007 3008 3009 3010 3011 3012 3013
If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for
<code>(*a)[low : high]</code>.
</p>

<p>
For arrays or strings, the indices are <i>in range</i> if
<code>0</code> &lt;= <code>low</code> &lt;= <code>high</code> &lt;= <code>len(a)</code>,
3014 3015
otherwise they are <i>out of range</i>.
For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length.
3016
A <a href="#Constants">constant</a> index must be non-negative and representable by a value of type
3017
<code>int</code>; for arrays or constant strings, constant indices must also be in range.
3018 3019
If both indices are constant, they must satisfy <code>low &lt;= high</code>.
If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3020 3021
</p>

3022
<p>
3023 3024 3025
Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice,
the result of the slice operation is a non-constant value of the same type as the operand.
For untyped string operands the result is a non-constant value of type <code>string</code>.
3026 3027
If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>
and the result of the slice operation is a slice with the same element type as the array.
Rob Pike's avatar
Rob Pike committed
3028
</p>
3029

3030 3031
<p>
If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result
3032 3033
is a <code>nil</code> slice. Otherwise, the result shares its underlying array with the
operand.
3034
</p>
3035

Robert Griesemer's avatar
Robert Griesemer committed
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076
<h4>Full slice expressions</h4>

<p>
For an array, pointer to array, or slice <code>a</code> (but not a string), the primary expression
</p>

<pre>
a[low : high : max]
</pre>

<p>
constructs a slice of the same type, and with the same length and elements as the simple slice
expression <code>a[low : high]</code>. Additionally, it controls the resulting slice's capacity
by setting it to <code>max - low</code>. Only the first index may be omitted; it defaults to 0.
After slicing the array <code>a</code>
</p>

<pre>
a := [5]int{1, 2, 3, 4, 5}
t := a[1:3:5]
</pre>

<p>
the slice <code>t</code> has type <code>[]int</code>, length 2, capacity 4, and elements
</p>

<pre>
t[0] == 2
t[1] == 3
</pre>

<p>
As for simple slice expressions, if <code>a</code> is a pointer to an array,
<code>a[low : high : max]</code> is shorthand for <code>(*a)[low : high : max]</code>.
If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>.
</p>

<p>
The indices are <i>in range</i> if <code>0 &lt;= low &lt;= high &lt;= max &lt;= cap(a)</code>,
otherwise they are <i>out of range</i>.
A <a href="#Constants">constant</a> index must be non-negative and representable by a value of type
3077
<code>int</code>; for arrays, constant indices must also be in range.
Robert Griesemer's avatar
Robert Griesemer committed
3078 3079 3080 3081 3082
If multiple indices are constant, the constants that are present must be in range relative to each
other.
If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
</p>

3083
<h3 id="Type_assertions">Type assertions</h3>
3084

Rob Pike's avatar
Rob Pike committed
3085
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3086 3087
For an expression <code>x</code> of <a href="#Interface_types">interface type</a>
and a type <code>T</code>, the primary expression
Rob Pike's avatar
Rob Pike committed
3088
</p>
3089

3090 3091 3092
<pre>
x.(T)
</pre>
3093

3094
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3095
asserts that <code>x</code> is not <code>nil</code>
Russ Cox's avatar
Russ Cox committed
3096
and that the value stored in <code>x</code> is of type <code>T</code>.
3097
The notation <code>x.(T)</code> is called a <i>type assertion</i>.
Rob Pike's avatar
Rob Pike committed
3098 3099
</p>
<p>
3100
More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
3101 3102
that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a>
to the type <code>T</code>.
3103 3104 3105
In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>;
otherwise the type assertion is invalid since it is not possible for <code>x</code>
to store a value of type <code>T</code>.
3106
If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
3107
of <code>x</code> implements the interface <code>T</code>.
Rob Pike's avatar
Rob Pike committed
3108
</p>
3109
<p>
3110
If the type assertion holds, the value of the expression is the value
Rob Pike's avatar
Rob Pike committed
3111 3112 3113
stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false,
a <a href="#Run_time_panics">run-time panic</a> occurs.
In other words, even though the dynamic type of <code>x</code>
3114
is known only at run time, the type of <code>x.(T)</code> is
Rob Pike's avatar
Rob Pike committed
3115 3116
known to be <code>T</code> in a correct program.
</p>
3117 3118

<pre>
3119 3120
var x interface{} = 7          // x has dynamic type int and value 7
i := x.(int)                   // i has type int and value 7
3121 3122

type I interface { m() }
3123 3124 3125 3126 3127 3128

func f(y I) {
	s := y.(string)        // illegal: string does not implement I (missing method m)
	r := y.(io.Reader)     // r has type io.Reader and the dynamic type of y must implement both I and io.Reader

}
3129 3130
</pre>

3131
<p>
3132
A type assertion used in an <a href="#Assignments">assignment</a> or initialization of the special form
Rob Pike's avatar
Rob Pike committed
3133
</p>
3134

3135 3136 3137
<pre>
v, ok = x.(T)
v, ok := x.(T)
Rob Pike's avatar
Rob Pike committed
3138
var v, ok = x.(T)
3139
var v, ok T1 = x.(T)
3140
</pre>
3141

3142
<p>
3143 3144 3145
yields an additional untyped boolean value. The value of <code>ok</code> is <code>true</code>
if the assertion holds. Otherwise it is <code>false</code> and the value of <code>v</code> is
the <a href="#The_zero_value">zero value</a> for type <code>T</code>.
Rob Pike's avatar
Rob Pike committed
3146
No run-time panic occurs in this case.
Rob Pike's avatar
Rob Pike committed
3147
</p>
3148

3149

3150
<h3 id="Calls">Calls</h3>
3151

3152
<p>
Rob Pike's avatar
Rob Pike committed
3153 3154
Given an expression <code>f</code> of function type
<code>F</code>,
Rob Pike's avatar
Rob Pike committed
3155
</p>
3156

3157
<pre>
3158
f(a1, a2, … an)
3159
</pre>
3160

3161
<p>
3162
calls <code>f</code> with arguments <code>a1, a2, … an</code>.
3163
Except for one special case, arguments must be single-valued expressions
3164
<a href="#Assignability">assignable</a> to the parameter types of
Rob Pike's avatar
Rob Pike committed
3165 3166 3167 3168 3169 3170 3171
<code>F</code> and are evaluated before the function is called.
The type of the expression is the result type
of <code>F</code>.
A method invocation is similar but the method itself
is specified as a selector upon a value of the receiver type for
the method.
</p>
3172

3173
<pre>
3174
math.Atan2(x, y)  // function call
3175
var pt *Point
3176
pt.Scale(3.5)     // method call with receiver pt
3177
</pre>
3178

3179 3180 3181 3182 3183 3184 3185 3186 3187 3188
<p>
In a function call, the function value and arguments are evaluated in
<a href="#Order_of_evaluation">the usual order</a>.
After they are evaluated, the parameters of the call are passed by value to the function
and the called function begins execution.
The return parameters of the function are passed by value
back to the calling function when the function returns.
</p>

<p>
Hong Ruiqi's avatar
Hong Ruiqi committed
3189
Calling a <code>nil</code> function value
3190 3191 3192
causes a <a href="#Run_time_panics">run-time panic</a>.
</p>

3193
<p>
3194
As a special case, if the return values of a function or method
3195 3196
<code>g</code> are equal in number and individually
assignable to the parameters of another function or method
3197 3198 3199
<code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code>
will invoke <code>f</code> after binding the return values of
<code>g</code> to the parameters of <code>f</code> in order.  The call
3200 3201
of <code>f</code> must contain no parameters other than the call of <code>g</code>,
and <code>g</code> must have at least one return value.
3202 3203 3204 3205 3206 3207 3208
If <code>f</code> has a final <code>...</code> parameter, it is
assigned the return values of <code>g</code> that remain after
assignment of regular parameters.
</p>

<pre>
func Split(s string, pos int) (string, string) {
3209
	return s[0:pos], s[pos:]
3210 3211 3212 3213 3214 3215 3216
}

func Join(s, t string) string {
	return s + t
}

if Join(Split(value, len(value)/2)) != value {
3217
	log.Panic("test fails")
3218 3219 3220
}
</pre>

Rob Pike's avatar
Rob Pike committed
3221
<p>
3222 3223
A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a>
of (the type of) <code>x</code> contains <code>m</code> and the
3224
argument list can be assigned to the parameter list of <code>m</code>.
Rob Pike's avatar
Rob Pike committed
3225
If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&amp;x</code>'s method
Robert Griesemer's avatar
Robert Griesemer committed
3226 3227
set contains <code>m</code>, <code>x.m()</code> is shorthand
for <code>(&amp;x).m()</code>:
Rob Pike's avatar
Rob Pike committed
3228
</p>
3229

3230
<pre>
3231
var p Point
Rob Pike's avatar
Rob Pike committed
3232
p.Scale(3.5)
3233
</pre>
3234

3235
<p>
3236
There is no distinct method type and there are no method literals.
Rob Pike's avatar
Rob Pike committed
3237
</p>
3238

3239
<h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3>
3240

Rob Pike's avatar
Rob Pike committed
3241
<p>
3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252
If <code>f</code> is <a href="#Function_types">variadic</a> with a final
parameter <code>p</code> of type <code>...T</code>, then within <code>f</code>
the type of <code>p</code> is equivalent to type <code>[]T</code>.
If <code>f</code> is invoked with no actual arguments for <code>p</code>,
the value passed to <code>p</code> is <code>nil</code>.
Otherwise, the value passed is a new slice
of type <code>[]T</code> with a new underlying array whose successive elements
are the actual arguments, which all must be <a href="#Assignability">assignable</a>
to <code>T</code>. The length and capacity of the slice is therefore
the number of arguments bound to <code>p</code> and may differ for each
call site.
3253
</p>
3254

Rob Pike's avatar
Rob Pike committed
3255
<p>
3256
Given the function and calls
3257 3258
</p>
<pre>
3259
func Greeting(prefix string, who ...string)
3260
Greeting("nobody")
3261 3262 3263 3264
Greeting("hello:", "Joe", "Anna", "Eileen")
</pre>

<p>
Robert Griesemer's avatar
Robert Griesemer committed
3265
within <code>Greeting</code>, <code>who</code> will have the value
3266 3267
<code>nil</code> in the first call, and
<code>[]string{"Joe", "Anna", "Eileen"}</code> in the second.
3268 3269
</p>

Robert Griesemer's avatar
Robert Griesemer committed
3270
<p>
3271 3272 3273
If the final argument is assignable to a slice type <code>[]T</code>, it may be
passed unchanged as the value for a <code>...T</code> parameter if the argument
is followed by <code>...</code>. In this case no new slice is created.
Robert Griesemer's avatar
Robert Griesemer committed
3274
</p>
3275 3276

<p>
Robert Griesemer's avatar
Robert Griesemer committed
3277
Given the slice <code>s</code> and call
3278
</p>
3279

Robert Griesemer's avatar
Robert Griesemer committed
3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290
<pre>
s := []string{"James", "Jasmine"}
Greeting("goodbye:", s...)
</pre>

<p>
within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code>
with the same underlying array.
</p>


3291
<h3 id="Operators">Operators</h3>
3292

Rob Pike's avatar
Rob Pike committed
3293
<p>
3294
Operators combine operands into expressions.
Rob Pike's avatar
Rob Pike committed
3295
</p>
3296

3297
<pre class="ebnf">
3298
Expression = UnaryExpr | Expression binary_op Expression .
Rob Pike's avatar
Rob Pike committed
3299
UnaryExpr  = PrimaryExpr | unary_op UnaryExpr .
3300

3301
binary_op  = "||" | "&amp;&amp;" | rel_op | add_op | mul_op .
Rob Pike's avatar
Rob Pike committed
3302 3303
rel_op     = "==" | "!=" | "&lt;" | "&lt;=" | ">" | ">=" .
add_op     = "+" | "-" | "|" | "^" .
Robert Griesemer's avatar
Robert Griesemer committed
3304
mul_op     = "*" | "/" | "%" | "&lt;&lt;" | "&gt;&gt;" | "&amp;" | "&amp;^" .
3305

Rob Pike's avatar
Rob Pike committed
3306
unary_op   = "+" | "-" | "!" | "^" | "*" | "&amp;" | "&lt;-" .
3307
</pre>
3308

3309
<p>
3310
Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>.
3311
For other binary operators, the operand types must be <a href="#Type_identity">identical</a>
3312
unless the operation involves shifts or untyped <a href="#Constants">constants</a>.
3313 3314
For operations involving constants only, see the section on
<a href="#Constant_expressions">constant expressions</a>.
Rob Pike's avatar
Rob Pike committed
3315
</p>
3316

3317
<p>
3318
Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a>
3319 3320
and the other operand is not, the constant is <a href="#Conversions">converted</a>
to the type of the other operand.
3321
</p>
3322

3323
<p>
3324
The right operand in a shift expression must have unsigned integer type
3325
or be an untyped constant that can be converted to unsigned integer type.
3326
If the left operand of a non-constant shift expression is an untyped constant,
3327
it is first converted to the type it would assume if the shift expression were
3328
replaced by its left operand alone.
3329
</p>
3330

3331
<pre>
3332
var s uint = 33
3333 3334 3335
var i = 1&lt;&lt;s           // 1 has type int
var j int32 = 1&lt;&lt;s     // 1 has type int32; j == 0
var k = uint64(1&lt;&lt;s)   // 1 has type uint64; k == 1&lt;&lt;33
3336 3337
var m int = 1.0&lt;&lt;s     // 1.0 has type int; m == 0 if ints are 32bits in size
var n = 1.0&lt;&lt;s == j    // 1.0 has type int32; n == true
Robert Griesemer's avatar
Robert Griesemer committed
3338
var o = 1&lt;&lt;s == 2&lt;&lt;s   // 1 and 2 have type int; o == true if ints are 32bits in size
3339
var p = 1&lt;&lt;s == 1&lt;&lt;33  // illegal if ints are 32bits in size: 1 has type int, but 1&lt;&lt;33 overflows int
3340
var u = 1.0&lt;&lt;s         // illegal: 1.0 has type float64, cannot shift
3341 3342
var u1 = 1.0&lt;&lt;s != 0   // illegal: 1.0 has type float64, cannot shift
var u2 = 1&lt;&lt;s != 1.0   // illegal: 1 has type float64, cannot shift
3343
var v float32 = 1&lt;&lt;s   // illegal: 1 has type float32, cannot shift
Robert Griesemer's avatar
Robert Griesemer committed
3344
var w int64 = 1.0&lt;&lt;33  // 1.0&lt;&lt;33 is a constant shift expression
3345
</pre>
3346

3347 3348

<h4 id="Operator_precedence">Operator precedence</h4>
3349
<p>
Russ Cox's avatar
Russ Cox committed
3350 3351
Unary operators have the highest precedence.
As the  <code>++</code> and <code>--</code> operators form
Rob Pike's avatar
Rob Pike committed
3352
statements, not expressions, they fall
Russ Cox's avatar
Russ Cox committed
3353
outside the operator hierarchy.
Rob Pike's avatar
Rob Pike committed
3354 3355
As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>.
<p>
3356
There are five precedence levels for binary operators.
Rob Pike's avatar
Rob Pike committed
3357
Multiplication operators bind strongest, followed by addition
3358 3359
operators, comparison operators, <code>&amp;&amp;</code> (logical AND),
and finally <code>||</code> (logical OR):
Rob Pike's avatar
Rob Pike committed
3360
</p>
3361

Rob Pike's avatar
Rob Pike committed
3362
<pre class="grammar">
3363
Precedence    Operator
3364 3365
    5             *  /  %  &lt;&lt;  &gt;&gt;  &amp;  &amp;^
    4             +  -  |  ^
3366
    3             ==  !=  &lt;  &lt;=  &gt;  &gt;=
3367 3368 3369
    2             &amp;&amp;
    1             ||
</pre>
3370

Rob Pike's avatar
Rob Pike committed
3371
<p>
3372
Binary operators of the same precedence associate from left to right.
3373
For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>.
Rob Pike's avatar
Rob Pike committed
3374
</p>
3375

3376 3377 3378 3379
<pre>
+x
23 + 3*x[i]
x &lt;= f()
Robert Griesemer's avatar
Robert Griesemer committed
3380
^a &gt;&gt; b
3381
f() || g()
3382
x == y+1 &amp;&amp; &lt;-chanPtr &gt; 0
3383
</pre>
3384 3385


3386
<h3 id="Arithmetic_operators">Arithmetic operators</h3>
3387
<p>
3388
Arithmetic operators apply to numeric values and yield a result of the same
Rob Pike's avatar
Rob Pike committed
3389
type as the first operand. The four standard arithmetic operators (<code>+</code>,
3390 3391 3392
<code>-</code>, <code>*</code>, <code>/</code>) apply to integer,
floating-point, and complex types; <code>+</code> also applies to strings.
The bitwise logical and shift operators apply to integers only.
Rob Pike's avatar
Rob Pike committed
3393
</p>
3394

Rob Pike's avatar
Rob Pike committed
3395
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
3396 3397 3398 3399
+    sum                    integers, floats, complex values, strings
-    difference             integers, floats, complex values
*    product                integers, floats, complex values
/    quotient               integers, floats, complex values
3400
%    remainder              integers
3401

3402 3403 3404 3405
&amp;    bitwise AND            integers
|    bitwise OR             integers
^    bitwise XOR            integers
&amp;^   bit clear (AND NOT)    integers
3406

Robert Griesemer's avatar
Robert Griesemer committed
3407 3408
&lt;&lt;   left shift             integer &lt;&lt; unsigned integer
&gt;&gt;   right shift            integer &gt;&gt; unsigned integer
3409
</pre>
3410 3411


3412
<h4 id="Integer_operators">Integer operators</h4>
3413

Rob Pike's avatar
Rob Pike committed
3414
<p>
3415 3416 3417
For two integer values <code>x</code> and <code>y</code>, the integer quotient
<code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following
relationships:
Rob Pike's avatar
Rob Pike committed
3418
</p>
3419

3420
<pre>
3421
x = q*y + r  and  |r| &lt; |y|
3422
</pre>
3423

Rob Pike's avatar
Rob Pike committed
3424
<p>
3425 3426
with <code>x / y</code> truncated towards zero
(<a href="http://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>).
Rob Pike's avatar
Rob Pike committed
3427
</p>
3428

3429 3430 3431 3432 3433 3434 3435
<pre>
 x     y     x / y     x % y
 5     3       1         2
-5     3      -1        -2
 5    -3      -1         2
-5    -3       1        -2
</pre>
3436

3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450
<p>
As an exception to this rule, if the dividend <code>x</code> is the most
negative value for the int type of <code>x</code>, the quotient
<code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>).
</p>

<pre>
			 x, q
int8                     -128
int16                  -32768
int32             -2147483648
int64    -9223372036854775808
</pre>

Rob Pike's avatar
Rob Pike committed
3451
<p>
3452 3453
If the divisor is a <a href="#Constants">constant</a>, it must not be zero.
If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3454
If the dividend is non-negative and the divisor is a constant power of 2,
3455
the division may be replaced by a right shift, and computing the remainder may
3456
be replaced by a bitwise AND operation:
Rob Pike's avatar
Rob Pike committed
3457
</p>
3458

3459
<pre>
Robert Griesemer's avatar
Robert Griesemer committed
3460
 x     x / 4     x % 4     x &gt;&gt; 2     x &amp; 3
3461 3462 3463
 11      2         3         2          3
-11     -2        -3        -3          1
</pre>
3464

Rob Pike's avatar
Rob Pike committed
3465
<p>
3466 3467
The shift operators shift the left operand by the shift count specified by the
right operand. They implement arithmetic shifts if the left operand is a signed
3468 3469
integer and logical shifts if it is an unsigned integer.
There is no upper limit on the shift count. Shifts behave
Rob Pike's avatar
Rob Pike committed
3470 3471
as if the left operand is shifted <code>n</code> times by 1 for a shift
count of <code>n</code>.
Robert Griesemer's avatar
Robert Griesemer committed
3472 3473
As a result, <code>x &lt;&lt; 1</code> is the same as <code>x*2</code>
and <code>x &gt;&gt; 1</code> is the same as
Robert Griesemer's avatar
Robert Griesemer committed
3474
<code>x/2</code> but truncated towards negative infinity.
Rob Pike's avatar
Rob Pike committed
3475
</p>
3476

Rob Pike's avatar
Rob Pike committed
3477 3478 3479
<p>
For integer operands, the unary operators
<code>+</code>, <code>-</code>, and <code>^</code> are defined as
Robert Griesemer's avatar
Robert Griesemer committed
3480
follows:
Rob Pike's avatar
Rob Pike committed
3481
</p>
3482

Rob Pike's avatar
Rob Pike committed
3483
<pre class="grammar">
3484 3485
+x                          is 0 + x
-x    negation              is 0 - x
Russ Cox's avatar
Russ Cox committed
3486 3487
^x    bitwise complement    is m ^ x  with m = "all bits set to 1" for unsigned x
                                      and  m = -1 for signed x
3488
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3489 3490


3491
<h4 id="Integer_overflow">Integer overflow</h4>
Robert Griesemer's avatar
Robert Griesemer committed
3492

Rob Pike's avatar
Rob Pike committed
3493 3494 3495 3496
<p>
For unsigned integer values, the operations <code>+</code>,
<code>-</code>, <code>*</code>, and <code>&lt;&lt;</code> are
computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of
3497 3498
the <a href="#Numeric_types">unsigned integer</a>'s type.
Loosely speaking, these unsigned integer operations
Robert Griesemer's avatar
Robert Griesemer committed
3499
discard high bits upon overflow, and programs may rely on ``wrap around''.
Rob Pike's avatar
Rob Pike committed
3500
</p>
3501
<p>
Rob Pike's avatar
Rob Pike committed
3502 3503
For signed integers, the operations <code>+</code>,
<code>-</code>, <code>*</code>, and <code>&lt;&lt;</code> may legally
Robert Griesemer's avatar
Robert Griesemer committed
3504 3505
overflow and the resulting value exists and is deterministically defined
by the signed integer representation, the operation, and its operands.
Rob Pike's avatar
Rob Pike committed
3506
No exception is raised as a result of overflow. A
Robert Griesemer's avatar
Robert Griesemer committed
3507
compiler may not optimize code under the assumption that overflow does
Rob Pike's avatar
Rob Pike committed
3508 3509
not occur. For instance, it may not assume that <code>x &lt; x + 1</code> is always true.
</p>
3510 3511


3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540
<h4 id="Floating_point_operators">Floating-point operators</h4>

<p>
For floating-point and complex numbers,
<code>+x</code> is the same as <code>x</code>,
while <code>-x</code> is the negation of <code>x</code>.
The result of a floating-point or complex division by zero is not specified beyond the
IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a>
occurs is implementation-specific.
</p>


<h4 id="String_concatenation">String concatenation</h4>

<p>
Strings can be concatenated using the <code>+</code> operator
or the <code>+=</code> assignment operator:
</p>

<pre>
s := "hi" + string(c)
s += " and good bye"
</pre>

<p>
String addition creates a new string by concatenating the operands.
</p>


3541
<h3 id="Comparison_operators">Comparison operators</h3>
3542

Rob Pike's avatar
Rob Pike committed
3543
<p>
3544
Comparison operators compare two operands and yield an untyped boolean value.
Rob Pike's avatar
Rob Pike committed
3545
</p>
3546

Rob Pike's avatar
Rob Pike committed
3547
<pre class="grammar">
3548 3549
==    equal
!=    not equal
Anthony Martin's avatar
Anthony Martin committed
3550 3551
&lt;     less
&lt;=    less or equal
3552 3553
&gt;     greater
&gt;=    greater or equal
3554
</pre>
3555

Rob Pike's avatar
Rob Pike committed
3556
<p>
3557
In any comparison, the first operand
3558 3559
must be <a href="#Assignability">assignable</a>
to the type of the second operand, or vice versa.
Rob Pike's avatar
Rob Pike committed
3560
</p>
3561
<p>
3562 3563 3564 3565 3566
The equality operators <code>==</code> and <code>!=</code> apply
to operands that are <i>comparable</i>.
The ordering operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code>
apply to operands that are <i>ordered</i>.
These terms and the result of the comparisons are defined as follows:
Rob Pike's avatar
Rob Pike committed
3567
</p>
3568

3569 3570
<ul>
	<li>
3571 3572 3573
	Boolean values are comparable.
	Two boolean values are equal if they are either both
	<code>true</code> or both <code>false</code>.
3574
	</li>
3575

3576
	<li>
3577
	Integer values are comparable and ordered, in the usual way.
3578
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3579

3580
	<li>
3581 3582
	Floating point values are comparable and ordered,
	as defined by the IEEE-754 standard.
3583
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3584

3585
	<li>
3586 3587 3588 3589
	Complex values are comparable.
	Two complex values <code>u</code> and <code>v</code> are
	equal if both <code>real(u) == real(v)</code> and
	<code>imag(u) == imag(v)</code>.
3590
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3591

3592
	<li>
3593
	String values are comparable and ordered, lexically byte-wise.
3594
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3595

3596
	<li>
3597
	Pointer values are comparable.
3598 3599
	Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>.
	Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal.
3600
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3601

3602
	<li>
3603
	Channel values are comparable.
3604 3605
	Two channel values are equal if they were created by the same call to
	<a href="#Making_slices_maps_and_channels"><code>make</code></a>
3606
	or if both have value <code>nil</code>.
3607
	</li>
3608

3609
	<li>
3610 3611 3612
	Interface values are comparable.
	Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types
	and equal dynamic values or if both have value <code>nil</code>.
3613
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3614

3615
	<li>
3616 3617 3618 3619 3620 3621
	A value <code>x</code> of non-interface type <code>X</code> and
	a value <code>t</code> of interface type <code>T</code> are comparable when values
	of type <code>X</code> are comparable and
	<code>X</code> implements <code>T</code>.
	They are equal if <code>t</code>'s dynamic type is identical to <code>X</code>
	and <code>t</code>'s dynamic value is equal to <code>x</code>.
3622
	</li>
3623

3624
	<li>
3625 3626 3627
	Struct values are comparable if all their fields are comparable.
	Two struct values are equal if their corresponding
	non-<a href="#Blank_identifier">blank</a> fields are equal.
3628
	</li>
Hong Ruiqi's avatar
Hong Ruiqi committed
3629

3630
	<li>
3631 3632
	Array values are comparable if values of the array element type are comparable.
	Two array values are equal if their corresponding elements are equal.
3633 3634 3635
	</li>
</ul>

3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650
<p>
A comparison of two interface values with identical dynamic types
causes a <a href="#Run_time_panics">run-time panic</a> if values
of that type are not comparable.  This behavior applies not only to direct interface
value comparisons but also when comparing arrays of interface values
or structs with interface-valued fields.
</p>

<p>
Slice, map, and function values are not comparable.
However, as a special case, a slice, map, or function value may
be compared to the predeclared identifier <code>nil</code>.
Comparison of pointer, channel, and interface values to <code>nil</code>
is also allowed and follows from the general rules above.
</p>
3651

3652
<pre>
3653
const c = 3 &lt; 4            // c is the untyped boolean constant true
3654

3655
type MyBool bool
3656 3657
var x, y int
var (
3658
	// The result of a comparison is an untyped boolean.
3659 3660 3661 3662
	// The usual assignment rules apply.
	b3        = x == y // b3 has type bool
	b4 bool   = x == y // b4 has type bool
	b5 MyBool = x == y // b5 has type MyBool
3663 3664 3665
)
</pre>

3666
<h3 id="Logical_operators">Logical operators</h3>
3667

Rob Pike's avatar
Rob Pike committed
3668
<p>
3669 3670
Logical operators apply to <a href="#Boolean_types">boolean</a> values
and yield a result of the same type as the operands.
3671
The right operand is evaluated conditionally.
Rob Pike's avatar
Rob Pike committed
3672
</p>
3673

Rob Pike's avatar
Rob Pike committed
3674
<pre class="grammar">
3675 3676 3677
&amp;&amp;    conditional AND    p &amp;&amp; q  is  "if p then q else false"
||    conditional OR     p || q  is  "if p then true else q"
!     NOT                !p      is  "not p"
3678
</pre>
3679 3680


3681
<h3 id="Address_operators">Address operators</h3>
3682

Rob Pike's avatar
Rob Pike committed
3683
<p>
3684 3685 3686
For an operand <code>x</code> of type <code>T</code>, the address operation
<code>&amp;x</code> generates a pointer of type <code>*T</code> to <code>x</code>.
The operand must be <i>addressable</i>,
3687
that is, either a variable, pointer indirection, or slice indexing
3688
operation; or a field selector of an addressable struct operand;
3689
or an array indexing operation of an addressable array.
3690
As an exception to the addressability requirement, <code>x</code> may also be a
3691
(possibly parenthesized)
3692
<a href="#Composite_literals">composite literal</a>.
3693
If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>,
3694
then the evaluation of <code>&amp;x</code> does too.
3695
</p>
Russ Cox's avatar
Russ Cox committed
3696

3697 3698
<p>
For an operand <code>x</code> of pointer type <code>*T</code>, the pointer
Robert Griesemer's avatar
Robert Griesemer committed
3699
indirection <code>*x</code> denotes the <a href="#Variables">variable</a> of type <code>T</code> pointed
3700
to by <code>x</code>.
3701 3702
If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code>
will cause a <a href="#Run_time_panics">run-time panic</a>.
Rob Pike's avatar
Rob Pike committed
3703 3704 3705 3706 3707
</p>

<pre>
&amp;x
&amp;a[f(2)]
3708
&amp;Point{2, 3}
Rob Pike's avatar
Rob Pike committed
3709 3710
*p
*pf(x)
Russ Cox's avatar
Russ Cox committed
3711 3712 3713

var x *int = nil
*x   // causes a run-time panic
3714
&amp;*x  // causes a run-time panic
Rob Pike's avatar
Rob Pike committed
3715 3716
</pre>

Rob Pike's avatar
Rob Pike committed
3717

3718
<h3 id="Receive_operator">Receive operator</h3>
3719

Rob Pike's avatar
Rob Pike committed
3720
<p>
3721 3722
For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>,
the value of the receive operation <code>&lt;-ch</code> is the value received
3723 3724 3725
from the channel <code>ch</code>. The channel direction must permit receive operations,
and the type of the receive operation is the element type of the channel.
The expression blocks until a value is available.
3726
Receiving from a <code>nil</code> channel blocks forever.
3727
A receive operation on a <a href="#Close">closed</a> channel can always proceed
3728 3729
immediately, yielding the element type's <a href="#The_zero_value">zero value</a>
after any previously sent values have been received.
Rob Pike's avatar
Rob Pike committed
3730
</p>
3731

3732
<pre>
3733 3734 3735
v1 := &lt;-ch
v2 = &lt;-ch
f(&lt;-ch)
3736
&lt;-strobe  // wait until clock pulse and discard received value
3737
</pre>
3738

Rob Pike's avatar
Rob Pike committed
3739
<p>
3740
A receive expression used in an <a href="#Assignments">assignment</a> or initialization of the special form
Rob Pike's avatar
Rob Pike committed
3741
</p>
3742

3743
<pre>
3744 3745 3746
x, ok = &lt;-ch
x, ok := &lt;-ch
var x, ok = &lt;-ch
3747
var x, ok T = &lt;-ch
3748
</pre>
3749

Rob Pike's avatar
Rob Pike committed
3750
<p>
3751
yields an additional untyped boolean result reporting whether the
3752 3753 3754 3755
communication succeeded. The value of <code>ok</code> is <code>true</code>
if the value received was delivered by a successful send operation to the
channel, or <code>false</code> if it is a zero value generated because the
channel is closed and empty.
Rob Pike's avatar
Rob Pike committed
3756
</p>
3757

3758

3759 3760 3761 3762 3763 3764 3765 3766 3767
<h3 id="Conversions">Conversions</h3>

<p>
Conversions are expressions of the form <code>T(x)</code>
where <code>T</code> is a type and <code>x</code> is an expression
that can be converted to type <code>T</code>.
</p>

<pre class="ebnf">
3768
Conversion = Type "(" Expression [ "," ] ")" .
3769 3770 3771
</pre>

<p>
3772
If the type starts with the operator <code>*</code> or <code>&lt;-</code>,
3773 3774 3775
or if the type starts with the keyword <code>func</code>
and has no result list, it must be parenthesized when
necessary to avoid ambiguity:
3776 3777 3778 3779
</p>

<pre>
*Point(p)        // same as *(Point(p))
3780
(*Point)(p)      // p is converted to *Point
3781
&lt;-chan int(c)    // same as &lt;-(chan int(c))
3782
(&lt;-chan int)(c)  // c is converted to &lt;-chan int
3783
func()(x)        // function signature func() x
3784 3785 3786
(func())(x)      // x is converted to func()
(func() int)(x)  // x is converted to func() int
func() int(x)    // x is converted to func() int (unambiguous)
3787 3788 3789
</pre>

<p>
3790 3791 3792 3793 3794 3795 3796 3797 3798
A <a href="#Constants">constant</a> value <code>x</code> can be converted to
type <code>T</code> in any of these cases:
</p>

<ul>
	<li>
	<code>x</code> is representable by a value of type <code>T</code>.
	</li>
	<li>
3799 3800 3801 3802
	<code>x</code> is a floating-point constant,
	<code>T</code> is a floating-point type,
	and <code>x</code> is representable by a value
	of type <code>T</code> after rounding using
3803 3804
	IEEE 754 round-to-even rules, but with an IEEE <code>-0.0</code>
	further rounded to an unsigned <code>0.0</code>.
3805 3806 3807
	The constant <code>T(x)</code> is the rounded value.
	</li>
	<li>
3808 3809
	<code>x</code> is an integer constant and <code>T</code> is a
	<a href="#String_types">string type</a>.
3810 3811
	The <a href="#Conversions_to_and_from_a_string_type">same rule</a>
	as for non-constant <code>x</code> applies in this case.
3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822
	</li>
</ul>

<p>
Converting a constant yields a typed constant as result.
</p>

<pre>
uint(iota)               // iota value of type uint
float32(2.718281828)     // 2.718281828 of type float32
complex128(1)            // 1.0 + 0.0i of type complex128
3823
float32(0.49999999)      // 0.5 of type float32
3824
float64(-1e-1000)        // 0.0 of type float64
3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836
string('x')              // "x" of type string
string(0x266c)           // "♬" of type string
MyString("foo" + "bar")  // "foobar" of type MyString
string([]byte{'a'})      // not a constant: []byte{'a'} is not a constant
(*int)(nil)              // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
int(1.2)                 // illegal: 1.2 cannot be represented as an int
string(65.0)             // illegal: 65.0 is not an integer constant
</pre>

<p>
A non-constant value <code>x</code> can be converted to type <code>T</code>
in any of these cases:
3837
</p>
3838

3839 3840
<ul>
	<li>
3841
	<code>x</code> is <a href="#Assignability">assignable</a>
3842 3843 3844
	to <code>T</code>.
	</li>
	<li>
3845 3846
	ignoring struct tags (see below),
	<code>x</code>'s type and <code>T</code> have <a href="#Type_identity">identical</a>
3847 3848 3849
	<a href="#Types">underlying types</a>.
	</li>
	<li>
3850
	ignoring struct tags (see below),
3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861
	<code>x</code>'s type and <code>T</code> are unnamed pointer types
	and their pointer base types have identical underlying types.
	</li>
	<li>
	<code>x</code>'s type and <code>T</code> are both integer or floating
	point types.
	</li>
	<li>
	<code>x</code>'s type and <code>T</code> are both complex types.
	</li>
	<li>
3862 3863
	<code>x</code> is an integer or a slice of bytes or runes
	and <code>T</code> is a string type.
3864 3865
	</li>
	<li>
3866
	<code>x</code> is a string and <code>T</code> is a slice of bytes or runes.
3867 3868
	</li>
</ul>
3869

3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894
<p>
<a href="#Struct_types">Struct tags</a> are ignored when comparing struct types
for identity for the purpose of conversion:
</p>

<pre>
type Person struct {
	Name    string
	Address *struct {
		Street string
		City   string
	}
}

var data *struct {
	Name    string `json:"name"`
	Address *struct {
		Street string `json:"street"`
		City   string `json:"city"`
	} `json:"address"`
}

var person = (*Person)(data)  // ignoring tags, the underlying types are identical
</pre>

3895
<p>
3896 3897
Specific rules apply to (non-constant) conversions between numeric types or
to and from a string type.
3898 3899 3900 3901
These conversions may change the representation of <code>x</code>
and incur a run-time cost.
All other conversions only change the type but not the representation
of <code>x</code>.
3902 3903
</p>

3904 3905 3906 3907 3908 3909 3910
<p>
There is no linguistic mechanism to convert between pointers and integers.
The package <a href="#Package_unsafe"><code>unsafe</code></a>
implements this functionality under
restricted circumstances.
</p>

3911
<h4>Conversions between numeric types</h4>
3912 3913 3914 3915 3916

<p>
For the conversion of non-constant numeric values, the following rules apply:
</p>

3917
<ol>
3918
<li>
3919 3920 3921 3922 3923
When converting between integer types, if the value is a signed integer, it is
sign extended to implicit infinite precision; otherwise it is zero extended.
It is then truncated to fit in the result type's size.
For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>.
The conversion always yields a valid value; there is no indication of overflow.
3924 3925
</li>
<li>
3926 3927
When converting a floating-point number to an integer, the fraction is discarded
(truncation towards zero).
3928
</li>
Rob Pike's avatar
Rob Pike committed
3929
<li>
3930 3931
When converting an integer or floating-point number to a floating-point type,
or a complex number to another complex type, the result value is rounded
Rob Pike's avatar
Rob Pike committed
3932
to the precision specified by the destination type.
3933 3934 3935 3936
For instance, the value of a variable <code>x</code> of type <code>float32</code>
may be stored using additional precision beyond that of an IEEE-754 32-bit number,
but float32(x) represents the result of rounding <code>x</code>'s value to
32-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits
Evan Shaw's avatar
Evan Shaw committed
3937
of precision, but <code>float32(x + 0.1)</code> does not.
3938
</li>
3939 3940 3941
</ol>

<p>
3942
In all non-constant conversions involving floating-point or complex values,
Rob Pike's avatar
Rob Pike committed
3943
if the result type cannot represent the value the conversion
3944
succeeds but the result value is implementation-dependent.
3945 3946
</p>

3947
<h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4>
3948

3949
<ol>
3950
<li>
3951
Converting a signed or unsigned integer value to a string type yields a
3952 3953
string containing the UTF-8 representation of the integer. Values outside
the range of valid Unicode code points are converted to <code>"\uFFFD"</code>.
3954 3955

<pre>
3956
string('a')       // "a"
3957
string(-1)        // "\ufffd" == "\xef\xbf\xbd"
3958
string(0xf8)      // "\u00f8" == "ø" == "\xc3\xb8"
3959
type MyString string
3960
MyString(0x65e5)  // "\u65e5" == "日" == "\xe6\x97\xa5"
3961 3962 3963 3964
</pre>
</li>

<li>
3965
Converting a slice of bytes to a string type yields
3966
a string whose successive bytes are the elements of the slice.
3967 3968

<pre>
3969 3970 3971
string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'})   // "hellø"
string([]byte{})                                     // ""
string([]byte(nil))                                  // ""
3972 3973 3974

type MyBytes []byte
string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'})  // "hellø"
3975 3976
</pre>
</li>
3977

3978
<li>
3979
Converting a slice of runes to a string type yields
3980
a string that is the concatenation of the individual rune values
3981
converted to strings.
3982

3983
<pre>
3984 3985 3986
string([]rune{0x767d, 0x9d6c, 0x7fd4})   // "\u767d\u9d6c\u7fd4" == "白鵬翔"
string([]rune{})                         // ""
string([]rune(nil))                      // ""
3987 3988 3989

type MyRunes []rune
string(MyRunes{0x767d, 0x9d6c, 0x7fd4})  // "\u767d\u9d6c\u7fd4" == "白鵬翔"
3990
</pre>
3991 3992 3993
</li>

<li>
3994
Converting a value of a string type to a slice of bytes type
3995 3996 3997
yields a slice whose successive elements are the bytes of the string.

<pre>
3998
[]byte("hellø")   // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
3999 4000
[]byte("")        // []byte{}

4001
MyBytes("hellø")  // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
4002 4003
</pre>
</li>
4004

4005
<li>
4006 4007
Converting a value of a string type to a slice of runes type
yields a slice containing the individual Unicode code points of the string.
4008

4009
<pre>
4010
[]rune(MyString("白鵬翔"))  // []rune{0x767d, 0x9d6c, 0x7fd4}
4011 4012
[]rune("")                 // []rune{}

4013
MyRunes("白鵬翔")           // []rune{0x767d, 0x9d6c, 0x7fd4}
4014 4015
</pre>
</li>
4016
</ol>
4017 4018


4019
<h3 id="Constant_expressions">Constant expressions</h3>
Robert Griesemer's avatar
Robert Griesemer committed
4020

4021
<p>
4022
Constant expressions may contain only <a href="#Constants">constant</a>
4023
operands and are evaluated at compile time.
4024
</p>
Robert Griesemer's avatar
Robert Griesemer committed
4025

4026
<p>
4027 4028
Untyped boolean, numeric, and string constants may be used as operands
wherever it is legal to use an operand of boolean, numeric, or string type,
4029 4030
respectively.
Except for shift operations, if the operands of a binary operation are
4031
different kinds of untyped constants, the operation and, for non-boolean operations, the result use
4032
the kind that appears later in this list: integer, rune, floating-point, complex.
4033 4034
For example, an untyped integer constant divided by an
untyped complex constant yields an untyped complex constant.
4035
</p>
4036 4037

<p>
4038
A constant <a href="#Comparison_operators">comparison</a> always yields
4039
an untyped boolean constant.  If the left operand of a constant
4040 4041
<a href="#Operators">shift expression</a> is an untyped constant, the
result is an integer constant; otherwise it is a constant of the same
4042 4043
type as the left operand, which must be of
<a href="#Numeric_types">integer type</a>.
4044
Applying all other operators to untyped constants results in an untyped
Rob Pike's avatar
Rob Pike committed
4045
constant of the same kind (that is, a boolean, integer, floating-point,
4046
complex, or string constant).
4047 4048
</p>

4049
<pre>
4050 4051 4052
const a = 2 + 3.0          // a == 5.0   (untyped floating-point constant)
const b = 15 / 4           // b == 3     (untyped integer constant)
const c = 15 / 4.0         // c == 3.75  (untyped floating-point constant)
4053 4054
const Θ float64 = 3/2      // Θ == 1.0   (type float64, 3/2 is integer division)
const Π float64 = 3/2.     // Π == 1.5   (type float64, 3/2. is float division)
4055 4056
const d = 1 &lt;&lt; 3.0         // d == 8     (untyped integer constant)
const e = 1.0 &lt;&lt; 3         // e == 8     (untyped integer constant)
Robert Griesemer's avatar
Robert Griesemer committed
4057
const f = int32(1) &lt;&lt; 33   // illegal    (constant 8589934592 overflows int32)
4058
const g = float64(2) &gt;&gt; 1  // illegal    (float64(2) is a typed floating-point constant)
4059 4060
const h = "foo" &gt; "bar"    // h == true  (untyped boolean constant)
const j = true             // j == true  (untyped boolean constant)
4061
const k = 'w' + 1          // k == 'x'   (untyped rune constant)
4062 4063
const l = "hi"             // l == "hi"  (untyped string constant)
const m = string(k)        // m == "x"   (type string)
4064
const Σ = 1 - 0.707i       //            (untyped complex constant)
4065 4066
const Δ = Σ + 2.0e-4       //            (untyped complex constant)
const Φ = iota*1i - 1/1i   //            (untyped complex constant)
4067 4068
</pre>

Rob Pike's avatar
Rob Pike committed
4069
<p>
4070
Applying the built-in function <code>complex</code> to untyped
4071
integer, rune, or floating-point constants yields
4072
an untyped complex constant.
Rob Pike's avatar
Rob Pike committed
4073 4074 4075
</p>

<pre>
4076
const ic = complex(0, c)   // ic == 3.75i  (untyped complex constant)
4077
const iΘ = complex(0, Θ)   // iΘ == 1i     (type complex128)
Rob Pike's avatar
Rob Pike committed
4078 4079
</pre>

4080
<p>
4081 4082 4083
Constant expressions are always evaluated exactly; intermediate values and the
constants themselves may require precision significantly larger than supported
by any predeclared type in the language. The following are legal declarations:
4084 4085 4086
</p>

<pre>
4087 4088
const Huge = 1 &lt;&lt; 100         // Huge == 1267650600228229401496703205376  (untyped integer constant)
const Four int8 = Huge &gt;&gt; 98  // Four == 4                                (type int8)
4089
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
4090

4091 4092 4093 4094 4095 4096 4097 4098
<p>
The divisor of a constant division or remainder operation must not be zero:
</p>

<pre>
3.14 / 0.0   // illegal: division by zero
</pre>

4099
<p>
4100 4101
The values of <i>typed</i> constants must always be accurately representable as values
of the constant type. The following constant expressions are illegal:
4102 4103 4104
</p>

<pre>
4105 4106
uint(-1)     // -1 cannot be represented as a uint
int(3.14)    // 3.14 cannot be represented as an int
4107 4108 4109
int64(Huge)  // 1267650600228229401496703205376 cannot be represented as an int64
Four * 300   // operand 300 cannot be represented as an int8 (type of Four)
Four * 100   // product 400 cannot be represented as an int8 (type of Four)
4110 4111 4112
</pre>

<p>
4113
The mask used by the unary bitwise complement operator <code>^</code> matches
Rob Pike's avatar
Rob Pike committed
4114
the rule for non-constants: the mask is all 1s for unsigned constants
4115
and -1 for signed and untyped constants.
4116 4117 4118
</p>

<pre>
4119
^1         // untyped integer constant, equal to -2
4120
uint8(^1)  // illegal: same as uint8(-2), -2 cannot be represented as a uint8
4121 4122 4123
^uint8(1)  // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)
int8(^1)   // same as int8(-2)
^int8(1)   // same as -1 ^ int8(1) = -2
4124 4125
</pre>

4126 4127 4128 4129 4130 4131 4132
<p>
Implementation restriction: A compiler may use rounding while
computing untyped floating-point or complex constant expressions; see
the implementation restriction in the section
on <a href="#Constants">constants</a>.  This rounding may cause a
floating-point constant expression to be invalid in an integer
context, even if it would be integral when calculated using infinite
4133
precision, and vice versa.
4134 4135
</p>

4136

4137
<h3 id="Order_of_evaluation">Order of evaluation</h3>
4138 4139

<p>
4140
At package level, <a href="#Package_initialization">initialization dependencies</a>
4141 4142 4143 4144
determine the evaluation order of individual initialization expressions in
<a href="#Variable_declarations">variable declarations</a>.
Otherwise, when evaluating the <a href="#Operands">operands</a> of an
expression, assignment, or
4145 4146
<a href="#Return_statements">return statement</a>,
all function calls, method calls, and
4147
communication operations are evaluated in lexical left-to-right
4148 4149 4150
order.
</p>

4151
<p>
4152
For example, in the (function-local) assignment
4153 4154
</p>
<pre>
4155
y[f()], ok = g(h(), i()+x[j()], &lt;-c), k()
4156 4157
</pre>
<p>
4158 4159
the function calls and communication happen in the order
<code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>,
4160
<code>&lt;-c</code>, <code>g()</code>, and <code>k()</code>.
4161 4162 4163
However, the order of those events compared to the evaluation
and indexing of <code>x</code> and the evaluation
of <code>y</code> is not specified.
4164 4165
</p>

4166 4167
<pre>
a := 1
4168
f := func() int { a++; return a }
4169 4170 4171
x := []int{a, f()}            // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified
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
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
4172 4173
</pre>

4174 4175 4176
<p>
At package level, initialization dependencies override the left-to-right rule
for individual initialization expressions, but not for operands within each
4177
expression:
4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195
</p>

<pre>
var a, b, c = f() + v(), g(), sqr(u()) + v()

func f() int        { return c }
func g() int        { return a }
func sqr(x int) int { return x*x }

// functions u and v are independent of all other variables and functions
</pre>

<p>
The function calls happen in the order
<code>u()</code>, <code>sqr()</code>, <code>v()</code>,
<code>f()</code>, <code>v()</code>, and <code>g()</code>.
</p>

4196 4197 4198 4199 4200 4201 4202 4203
<p>
Floating-point operations within a single expression are evaluated according to
the associativity of the operators.  Explicit parentheses affect the evaluation
by overriding the default associativity.
In the expression <code>x + (y + z)</code> the addition <code>y + z</code>
is performed before adding <code>x</code>.
</p>

4204
<h2 id="Statements">Statements</h2>
4205

Rob Pike's avatar
Rob Pike committed
4206
<p>
4207
Statements control execution.
Rob Pike's avatar
Rob Pike committed
4208
</p>
4209

4210
<pre class="ebnf">
4211
Statement =
4212 4213
	Declaration | LabeledStmt | SimpleStmt |
	GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
4214 4215
	FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
	DeferStmt .
Robert Griesemer's avatar
Robert Griesemer committed
4216

4217
SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
4218
</pre>
4219

4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294
<h3 id="Terminating_statements">Terminating statements</h3>

<p>
A terminating statement is one of the following:
</p>

<ol>
<li>
	A <a href="#Return_statements">"return"</a> or
    	<a href="#Goto_statements">"goto"</a> statement.
	<!-- ul below only for regular layout -->
	<ul> </ul>
</li>

<li>
	A call to the built-in function
	<a href="#Handling_panics"><code>panic</code></a>.
	<!-- ul below only for regular layout -->
	<ul> </ul>
</li>

<li>
	A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement.
	<!-- ul below only for regular layout -->
	<ul> </ul>
</li>

<li>
	An <a href="#If_statements">"if" statement</a> in which:
	<ul>
	<li>the "else" branch is present, and</li>
	<li>both branches are terminating statements.</li>
	</ul>
</li>

<li>
	A <a href="#For_statements">"for" statement</a> in which:
	<ul>
	<li>there are no "break" statements referring to the "for" statement, and</li>
	<li>the loop condition is absent.</li>
	</ul>
</li>

<li>
	A <a href="#Switch_statements">"switch" statement</a> in which:
	<ul>
	<li>there are no "break" statements referring to the "switch" statement,</li>
	<li>there is a default case, and</li>
	<li>the statement lists in each case, including the default, end in a terminating
	    statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough"
	    statement</a>.</li>
	</ul>
</li>

<li>
	A <a href="#Select_statements">"select" statement</a> in which:
	<ul>
	<li>there are no "break" statements referring to the "select" statement, and</li>
	<li>the statement lists in each case, including the default if present,
	    end in a terminating statement.</li>
	</ul>
</li>

<li>
	A <a href="#Labeled_statements">labeled statement</a> labeling
	a terminating statement.
</li>
</ol>

<p>
All other statements are not terminating.
</p>

<p>
A <a href="#Blocks">statement list</a> ends in a terminating statement if the list
4295
is not empty and its final non-empty statement is terminating.
4296 4297
</p>

4298

4299
<h3 id="Empty_statements">Empty statements</h3>
4300

Rob Pike's avatar
Rob Pike committed
4301
<p>
4302
The empty statement does nothing.
Rob Pike's avatar
Rob Pike committed
4303
</p>
4304

4305
<pre class="ebnf">
4306
EmptyStmt = .
4307
</pre>
4308 4309


4310
<h3 id="Labeled_statements">Labeled statements</h3>
4311 4312 4313 4314 4315 4316

<p>
A labeled statement may be the target of a <code>goto</code>,
<code>break</code> or <code>continue</code> statement.
</p>

4317
<pre class="ebnf">
4318
LabeledStmt = Label ":" Statement .
4319 4320 4321 4322
Label       = identifier .
</pre>

<pre>
4323
Error: log.Panic("error encountered")
4324 4325 4326
</pre>


4327
<h3 id="Expression_statements">Expression statements</h3>
4328

Rob Pike's avatar
Rob Pike committed
4329
<p>
4330 4331 4332
With the exception of specific built-in functions,
function and method <a href="#Calls">calls</a> and
<a href="#Receive_operator">receive operations</a>
4333
can appear in statement context. Such statements may be parenthesized.
Rob Pike's avatar
Rob Pike committed
4334 4335
</p>

4336
<pre class="ebnf">
4337
ExpressionStmt = Expression .
4338
</pre>
4339

4340 4341 4342 4343 4344 4345 4346 4347 4348
<p>
The following built-in functions are not permitted in statement context:
</p>

<pre>
append cap complex imag len make new real
unsafe.Alignof unsafe.Offsetof unsafe.Sizeof
</pre>

4349
<pre>
4350 4351
h(x+y)
f.Close()
4352
&lt;-ch
4353
(&lt;-ch)
4354
len("foo")  // illegal if len is the built-in function
4355
</pre>
4356 4357


4358 4359 4360 4361
<h3 id="Send_statements">Send statements</h3>

<p>
A send statement sends a value on a channel.
4362 4363 4364
The channel expression must be of <a href="#Channel_types">channel type</a>,
the channel direction must permit send operations,
and the type of the value to be sent must be <a href="#Assignability">assignable</a>
4365 4366 4367 4368 4369 4370 4371 4372 4373 4374
to the channel's element type.
</p>

<pre class="ebnf">
SendStmt = Channel "&lt;-" Expression .
Channel  = Expression .
</pre>

<p>
Both the channel and the value expression are evaluated before communication
4375
begins. Communication blocks until the send can proceed.
4376 4377
A send on an unbuffered channel can proceed if a receiver is ready.
A send on a buffered channel can proceed if there is room in the buffer.
4378
A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>.
4379
A send on a <code>nil</code> channel blocks forever.
4380 4381 4382
</p>

<pre>
4383
ch &lt;- 3  // send value 3 to channel ch
4384 4385 4386
</pre>


4387
<h3 id="IncDec_statements">IncDec statements</h3>
4388

Rob Pike's avatar
Rob Pike committed
4389
<p>
4390
The "++" and "--" statements increment or decrement their operands
4391
by the untyped <a href="#Constants">constant</a> <code>1</code>.
4392 4393
As with an assignment, the operand must be <a href="#Address_operators">addressable</a>
or a map index expression.
Rob Pike's avatar
Rob Pike committed
4394
</p>
4395

4396
<pre class="ebnf">
4397
IncDecStmt = Expression ( "++" | "--" ) .
4398
</pre>
4399

Rob Pike's avatar
Rob Pike committed
4400
<p>
Robert Griesemer's avatar
Robert Griesemer committed
4401
The following <a href="#Assignments">assignment statements</a> are semantically
4402
equivalent:
Rob Pike's avatar
Rob Pike committed
4403
</p>
4404

Rob Pike's avatar
Rob Pike committed
4405
<pre class="grammar">
4406 4407 4408 4409
IncDec statement    Assignment
x++                 x += 1
x--                 x -= 1
</pre>
4410

4411

4412
<h3 id="Assignments">Assignments</h3>
4413

4414
<pre class="ebnf">
4415
Assignment = ExpressionList assign_op ExpressionList .
Rob Pike's avatar
Rob Pike committed
4416

4417 4418
assign_op = [ add_op | mul_op ] "=" .
</pre>
4419

Rob Pike's avatar
Rob Pike committed
4420
<p>
Rob Pike's avatar
Rob Pike committed
4421
Each left-hand side operand must be <a href="#Address_operators">addressable</a>,
4422 4423
a map index expression, or (for <code>=</code> assignments only) the
<a href="#Blank_identifier">blank identifier</a>.
4424
Operands may be parenthesized.
Rob Pike's avatar
Rob Pike committed
4425
</p>
4426

4427 4428 4429 4430
<pre>
x = 1
*p = f()
a[i] = 23
4431
(k) = &lt;-ch  // same as: k = &lt;-ch
4432
</pre>
4433

Rob Pike's avatar
Rob Pike committed
4434 4435
<p>
An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code>
4436
<code>y</code> where <i>op</i> is a binary arithmetic operation is equivalent
Rob Pike's avatar
Rob Pike committed
4437
to <code>x</code> <code>=</code> <code>x</code> <i>op</i>
4438
<code>(y)</code> but evaluates <code>x</code>
Rob Pike's avatar
Rob Pike committed
4439
only once.  The <i>op</i><code>=</code> construct is a single token.
Rob Pike's avatar
Rob Pike committed
4440
In assignment operations, both the left- and right-hand expression lists
4441 4442
must contain exactly one single-valued expression, and the left-hand
expression must not be the blank identifier.
Rob Pike's avatar
Rob Pike committed
4443
</p>
4444

4445
<pre>
Robert Griesemer's avatar
Robert Griesemer committed
4446
a[i] &lt;&lt;= 2
Rob Pike's avatar
Rob Pike committed
4447
i &amp;^= 1&lt;&lt;n
4448
</pre>
4449

Rob Pike's avatar
Rob Pike committed
4450 4451 4452 4453
<p>
A tuple assignment assigns the individual elements of a multi-valued
operation to a list of variables.  There are two forms.  In the
first, the right hand operand is a single multi-valued expression
4454 4455
such as a function call, a <a href="#Channel_types">channel</a> or
<a href="#Map_types">map</a> operation, or a <a href="#Type_assertions">type assertion</a>.
4456
The number of operands on the left
Robert Griesemer's avatar
Robert Griesemer committed
4457
hand side must match the number of values.  For instance, if
Rob Pike's avatar
Rob Pike committed
4458 4459
<code>f</code> is a function returning two values,
</p>
4460

4461 4462 4463
<pre>
x, y = f()
</pre>
4464

Rob Pike's avatar
Rob Pike committed
4465 4466
<p>
assigns the first value to <code>x</code> and the second to <code>y</code>.
4467 4468 4469 4470
In the second form, the number of operands on the left must equal the number
of expressions on the right, each of which must be single-valued, and the
<i>n</i>th expression on the right is assigned to the <i>n</i>th
operand on the left:
Rob Pike's avatar
Rob Pike committed
4471
</p>
4472

Robert Griesemer's avatar
Robert Griesemer committed
4473
<pre>
4474
one, two, three = '一', '二', '三'
Robert Griesemer's avatar
Robert Griesemer committed
4475 4476
</pre>

Rob Pike's avatar
Rob Pike committed
4477
<p>
4478 4479
The <a href="#Blank_identifier">blank identifier</a> provides a way to
ignore right-hand side values in an assignment:
4480 4481
</p>

4482 4483 4484 4485 4486
<pre>
_ = x       // evaluate x but ignore it
x, _ = f()  // evaluate f() but ignore second result value
</pre>

4487 4488
<p>
The assignment proceeds in two phases.
4489
First, the operands of <a href="#Index_expressions">index expressions</a>
4490 4491 4492 4493 4494
and <a href="#Address_operators">pointer indirections</a>
(including implicit pointer indirections in <a href="#Selectors">selectors</a>)
on the left and the expressions on the right are all
<a href="#Order_of_evaluation">evaluated in the usual order</a>.
Second, the assignments are carried out in left-to-right order.
Rob Pike's avatar
Rob Pike committed
4495
</p>
4496

4497
<pre>
Rob Pike's avatar
Rob Pike committed
4498
a, b = b, a  // exchange a and b
4499 4500 4501

x := []int{1, 2, 3}
i := 0
4502
i, x[i] = 1, 2  // set i = 1, x[0] = 2
4503 4504 4505 4506

i = 0
x[i], i = 2, 1  // set x[0] = 2, i = 1

4507
x[0], x[0] = 1, 2  // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end)
4508

4509
x[1], x[3] = 4, 5  // set x[1] = 4, then panic setting x[3] = 5.
4510 4511 4512 4513

type Point struct { x, y int }
var p *Point
x[2], p.x = 6, 7  // set x[2] = 6, then panic setting p.x = 7
4514 4515 4516 4517 4518 4519 4520

i = 2
x = []int{3, 5, 7}
for i, x[i] = range x {  // set i, x[2] = 0, x[0]
	break
}
// after this loop, i == 0 and x == []int{3, 5, 3}
4521
</pre>
Rob Pike's avatar
Rob Pike committed
4522 4523

<p>
4524 4525
In assignments, each value must be <a href="#Assignability">assignable</a>
to the type of the operand to which it is assigned, with the following special cases:
Rob Pike's avatar
Rob Pike committed
4526
</p>
4527

4528
<ol>
4529 4530 4531 4532 4533 4534
<li>
	Any typed value may be assigned to the blank identifier.
</li>

<li>
	If an untyped constant
4535
	is assigned to a variable of interface type or the blank identifier,
4536 4537 4538 4539 4540 4541 4542 4543
	the constant is first <a href="#Conversions">converted</a> to its
	 <a href="#Constants">default type</a>.
</li>

<li>
	If an untyped boolean value is assigned to a variable of interface type or
	the blank identifier, it is first converted to type <code>bool</code>.
</li>
4544
</ol>
4545

4546
<h3 id="If_statements">If statements</h3>
4547

Rob Pike's avatar
Rob Pike committed
4548 4549 4550 4551
<p>
"If" statements specify the conditional execution of two branches
according to the value of a boolean expression.  If the expression
evaluates to true, the "if" branch is executed, otherwise, if
4552
present, the "else" branch is executed.
Rob Pike's avatar
Rob Pike committed
4553
</p>
4554

4555
<pre class="ebnf">
Russ Cox's avatar
Russ Cox committed
4556
IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
4557
</pre>
4558

4559
<pre>
4560 4561
if x &gt; max {
	x = max
4562 4563
}
</pre>
4564

4565
<p>
Russ Cox's avatar
Russ Cox committed
4566 4567
The expression may be preceded by a simple statement, which
executes before the expression is evaluated.
4568
</p>
4569

4570
<pre>
4571 4572
if x := f(); x &lt; y {
	return x
4573
} else if x &gt; z {
4574
	return z
4575
} else {
4576
	return y
4577 4578
}
</pre>
4579 4580


4581
<h3 id="Switch_statements">Switch statements</h3>
4582

Rob Pike's avatar
Rob Pike committed
4583 4584
<p>
"Switch" statements provide multi-way execution.
Rob Pike's avatar
Rob Pike committed
4585 4586 4587
An expression or type specifier is compared to the "cases"
inside the "switch" to determine which branch
to execute.
Rob Pike's avatar
Rob Pike committed
4588
</p>
4589

4590
<pre class="ebnf">
4591
SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4592 4593
</pre>

Rob Pike's avatar
Rob Pike committed
4594
<p>
Rob Pike's avatar
Rob Pike committed
4595 4596 4597 4598 4599
There are two forms: expression switches and type switches.
In an expression switch, the cases contain expressions that are compared
against the value of the switch expression.
In a type switch, the cases contain types that are compared against the
type of a specially annotated switch expression.
4600
The switch expression is evaluated exactly once in a switch statement.
Rob Pike's avatar
Rob Pike committed
4601 4602
</p>

4603
<h4 id="Expression_switches">Expression switches</h4>
Rob Pike's avatar
Rob Pike committed
4604 4605 4606 4607 4608

<p>
In an expression switch,
the switch expression is evaluated and
the case expressions, which need not be constants,
4609
are evaluated left-to-right and top-to-bottom; the first one that equals the
Rob Pike's avatar
Rob Pike committed
4610
switch expression
Rob Pike's avatar
Rob Pike committed
4611 4612
triggers execution of the statements of the associated case;
the other cases are skipped.
Rob Pike's avatar
Rob Pike committed
4613 4614
If no case matches and there is a "default" case,
its statements are executed.
Rob Pike's avatar
Rob Pike committed
4615 4616
There can be at most one default case and it may appear anywhere in the
"switch" statement.
4617 4618
A missing switch expression is equivalent to the boolean value
<code>true</code>.
Rob Pike's avatar
Rob Pike committed
4619
</p>
4620

4621
<pre class="ebnf">
4622
ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
4623
ExprCaseClause = ExprSwitchCase ":" StatementList .
4624
ExprSwitchCase = "case" ExpressionList | "default" .
4625 4626
</pre>

4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647
<p>
If the switch expression evaluates to an untyped constant, it is first
<a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>;
if it is an untyped boolean value, it is first converted to type <code>bool</code>.
The predeclared untyped value <code>nil</code> cannot be used as a switch expression.
</p>

<p>
If a case expression is untyped, it is first <a href="#Conversions">converted</a>
to the type of the switch expression.
For each (possibly converted) case expression <code>x</code> and the value <code>t</code>
of the switch expression, <code>x == t</code> must be a valid <a href="#Comparison_operators">comparison</a>.
</p>

<p>
In other words, the switch expression is treated as if it were used to declare and
initialize a temporary variable <code>t</code> without explicit type; it is that
value of <code>t</code> against which each case expression <code>x</code> is tested
for equality.
</p>

Rob Pike's avatar
Rob Pike committed
4648
<p>
4649 4650 4651
In a case or default clause, the last non-empty statement
may be a (possibly <a href="#Labeled_statements">labeled</a>)
<a href="#Fallthrough_statements">"fallthrough" statement</a> to
Rob Pike's avatar
Rob Pike committed
4652
indicate that control should flow from the end of this clause to
4653
the first statement of the next clause.
Rob Pike's avatar
Rob Pike committed
4654
Otherwise control flows to the end of the "switch" statement.
4655 4656
A "fallthrough" statement may appear as the last statement of all
but the last clause of an expression switch.
Rob Pike's avatar
Rob Pike committed
4657
</p>
Robert Griesemer's avatar
Robert Griesemer committed
4658

4659
<p>
4660
The switch expression may be preceded by a simple statement, which
Russ Cox's avatar
Russ Cox committed
4661
executes before the expression is evaluated.
Rob Pike's avatar
Rob Pike committed
4662
</p>
4663

4664 4665
<pre>
switch tag {
4666 4667 4668
default: s3()
case 0, 1, 2, 3: s1()
case 4, 5, 6, 7: s2()
4669
}
4670

4671
switch x := f(); {  // missing switch expression means "true"
4672 4673
case x &lt; 0: return -x
default: return x
4674
}
4675

Robert Griesemer's avatar
Robert Griesemer committed
4676
switch {
4677 4678 4679
case x &lt; y: f1()
case x &lt; z: f2()
case x == 4: f3()
4680 4681
}
</pre>
4682

4683 4684 4685 4686 4687 4688 4689
<p>
Implementation restriction: A compiler may disallow multiple case
expressions evaluating to the same constant.
For instance, the current compilers disallow duplicate integer,
floating point, or string constants in case expressions.
</p>

4690
<h4 id="Type_switches">Type switches</h4>
Rob Pike's avatar
Rob Pike committed
4691 4692

<p>
4693
A type switch compares types rather than values. It is otherwise similar
Robert Griesemer's avatar
tweaks  
Robert Griesemer committed
4694
to an expression switch. It is marked by a special switch expression that
4695
has the form of a <a href="#Type_assertions">type assertion</a>
4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709
using the reserved word <code>type</code> rather than an actual type:
</p>

<pre>
switch x.(type) {
// cases
}
</pre>

<p>
Cases then match actual types <code>T</code> against the dynamic type of the
expression <code>x</code>. As with type assertions, <code>x</code> must be of
<a href="#Interface_types">interface type</a>, and each non-interface type
<code>T</code> listed in a case must implement the type of <code>x</code>.
4710 4711
The types listed in the cases of a type switch must all be
<a href="#Type_identity">different</a>.
Rob Pike's avatar
Rob Pike committed
4712 4713
</p>

4714
<pre class="ebnf">
4715
TypeSwitchStmt  = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
4716
TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
4717
TypeCaseClause  = TypeSwitchCase ":" StatementList .
Rob Pike's avatar
Rob Pike committed
4718 4719
TypeSwitchCase  = "case" TypeList | "default" .
TypeList        = Type { "," Type } .
Rob Pike's avatar
Rob Pike committed
4720 4721
</pre>

4722
<p>
4723 4724
The TypeSwitchGuard may include a
<a href="#Short_variable_declarations">short variable declaration</a>.
4725 4726
When that form is used, the variable is declared at the end of the
TypeSwitchCase in the <a href="#Blocks">implicit block</a> of each clause.
4727 4728 4729
In clauses with a case listing exactly one type, the variable
has that type; otherwise, the variable has the type of the expression
in the TypeSwitchGuard.
4730 4731
</p>

Rob Pike's avatar
Rob Pike committed
4732
<p>
4733
The type in a case may be <a href="#Predeclared_identifiers"><code>nil</code></a>;
4734
that case is used when the expression in the TypeSwitchGuard
Robert Griesemer's avatar
tweaks  
Robert Griesemer committed
4735
is a <code>nil</code> interface value.
4736
There may be at most one <code>nil</code> case.
4737 4738 4739
</p>

<p>
Robert Griesemer's avatar
Robert Griesemer committed
4740
Given an expression <code>x</code> of type <code>interface{}</code>,
4741
the following type switch:
Rob Pike's avatar
Rob Pike committed
4742 4743 4744
</p>

<pre>
Robert Griesemer's avatar
Robert Griesemer committed
4745
switch i := x.(type) {
4746
case nil:
4747
	printString("x is nil")                // type of i is type of x (interface{})
Rob Pike's avatar
Rob Pike committed
4748
case int:
4749
	printInt(i)                            // type of i is int
4750
case float64:
4751
	printFloat64(i)                        // type of i is float64
4752
case func(int) float64:
4753
	printFunction(i)                       // type of i is func(int) float64
4754
case bool, string:
4755
	printString("type is bool or string")  // type of i is type of x (interface{})
Rob Pike's avatar
Rob Pike committed
4756
default:
4757
	printString("don't know the type")     // type of i is type of x (interface{})
Rob Pike's avatar
Rob Pike committed
4758
}
4759
</pre>
Rob Pike's avatar
Rob Pike committed
4760

4761 4762 4763 4764 4765
<p>
could be rewritten:
</p>

<pre>
4766
v := x  // x is evaluated exactly once
4767
if v == nil {
4768
	i := v                                 // type of i is type of x (interface{})
4769
	printString("x is nil")
4770
} else if i, isInt := v.(int); isInt {
4771
	printInt(i)                            // type of i is int
4772
} else if i, isFloat64 := v.(float64); isFloat64 {
4773
	printFloat64(i)                        // type of i is float64
4774
} else if i, isFunc := v.(func(int) float64); isFunc {
4775
	printFunction(i)                       // type of i is func(int) float64
4776
} else {
4777 4778
	_, isBool := v.(bool)
	_, isString := v.(string)
4779
	if isBool || isString {
4780 4781
		i := v                         // type of i is type of x (interface{})
		printString("type is bool or string")
4782
	} else {
4783 4784
		i := v                         // type of i is type of x (interface{})
		printString("don't know the type")
4785
	}
Rob Pike's avatar
Rob Pike committed
4786 4787
}
</pre>
4788

4789
<p>
Russ Cox's avatar
Russ Cox committed
4790 4791
The type switch guard may be preceded by a simple statement, which
executes before the guard is evaluated.
Robert Griesemer's avatar
tweaks  
Robert Griesemer committed
4792
</p>
4793 4794 4795

<p>
The "fallthrough" statement is not permitted in a type switch.
Russ Cox's avatar
Russ Cox committed
4796 4797
</p>

4798
<h3 id="For_statements">For statements</h3>
4799

Rob Pike's avatar
Rob Pike committed
4800 4801 4802 4803
<p>
A "for" statement specifies repeated execution of a block. The iteration is
controlled by a condition, a "for" clause, or a "range" clause.
</p>
4804

4805
<pre class="ebnf">
4806
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
4807 4808
Condition = Expression .
</pre>
4809

Rob Pike's avatar
Rob Pike committed
4810 4811 4812 4813
<p>
In its simplest form, a "for" statement specifies the repeated execution of
a block as long as a boolean condition evaluates to true.
The condition is evaluated before each iteration.
4814 4815
If the condition is absent, it is equivalent to the boolean value
<code>true</code>.
Rob Pike's avatar
Rob Pike committed
4816
</p>
4817

4818 4819 4820 4821 4822
<pre>
for a &lt; b {
	a *= 2
}
</pre>
4823

Rob Pike's avatar
Rob Pike committed
4824
<p>
Rob Pike's avatar
Rob Pike committed
4825
A "for" statement with a ForClause is also controlled by its condition, but
Rob Pike's avatar
Rob Pike committed
4826 4827
additionally it may specify an <i>init</i>
and a <i>post</i> statement, such as an assignment,
Russ Cox's avatar
Russ Cox committed
4828
an increment or decrement statement. The init statement may be a
Robert Griesemer's avatar
Robert Griesemer committed
4829
<a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not.
4830
Variables declared by the init statement are re-used in each iteration.
Rob Pike's avatar
Rob Pike committed
4831
</p>
4832

4833
<pre class="ebnf">
4834
ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
4835 4836
InitStmt = SimpleStmt .
PostStmt = SimpleStmt .
4837
</pre>
4838

4839
<pre>
4840
for i := 0; i &lt; 10; i++ {
4841 4842 4843
	f(i)
}
</pre>
4844

4845
<p>
Rob Pike's avatar
Rob Pike committed
4846 4847 4848 4849
If non-empty, the init statement is executed once before evaluating the
condition for the first iteration;
the post statement is executed after each execution of the block (and
only if the block was executed).
4850 4851
Any element of the ForClause may be empty but the
<a href="#Semicolons">semicolons</a> are
Rob Pike's avatar
Rob Pike committed
4852
required unless there is only a condition.
4853 4854
If the condition is absent, it is equivalent to the boolean value
<code>true</code>.
Rob Pike's avatar
Rob Pike committed
4855
</p>
Robert Griesemer's avatar
Robert Griesemer committed
4856

4857
<pre>
Rob Pike's avatar
Rob Pike committed
4858 4859
for cond { S() }    is the same as    for ; cond ; { S() }
for      { S() }    is the same as    for true     { S() }
4860
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
4861

Rob Pike's avatar
Rob Pike committed
4862 4863
<p>
A "for" statement with a "range" clause
Rob Pike's avatar
Rob Pike committed
4864
iterates through all entries of an array, slice, string or map,
4865
or values received on a channel. For each entry it assigns <i>iteration values</i>
4866
to corresponding <i>iteration variables</i> if present and then executes the block.
Rob Pike's avatar
Rob Pike committed
4867
</p>
Robert Griesemer's avatar
Robert Griesemer committed
4868

4869
<pre class="ebnf">
4870
RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .
4871 4872 4873 4874
</pre>

<p>
The expression on the right in the "range" clause is called the <i>range expression</i>,
4875 4876
which may be an array, pointer to an array, slice, string, map, or channel permitting
<a href="#Receive_operator">receive operations</a>.
4877
As with an assignment, if present the operands on the left must be
4878
<a href="#Address_operators">addressable</a> or map index expressions; they
4879 4880 4881 4882
denote the iteration variables. If the range expression is a channel, at most
one iteration variable is permitted, otherwise there may be up to two.
If the last iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
the range clause is equivalent to the same clause without that identifier.
4883
</p>
4884 4885

<p>
4886
The range expression is evaluated once before beginning the loop,
4887 4888 4889 4890
with one exception: if the range expression is an array or a pointer to an array
and at most one iteration variable is present, only the range expression's
length is evaluated; if that length is constant,
<a href="#Length_and_capacity">by definition</a>
4891 4892 4893 4894
the range expression itself will not be evaluated.
</p>

<p>
4895
Function calls on the left are evaluated once per iteration.
4896 4897
For each iteration, iteration values are produced as follows
if the respective iteration variables are present:
4898 4899 4900
</p>

<pre class="grammar">
4901
Range expression                          1st value          2nd value
4902 4903

array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
4904
string          s  string type            index    i  int    see below  rune
4905
map             m  map[K]V                key      k  K      m[k]       V
4906
channel         c  chan E, &lt;-chan E       element  e  E
4907 4908 4909 4910
</pre>

<ol>
<li>
4911
For an array, pointer to array, or slice value <code>a</code>, the index iteration
4912
values are produced in increasing order, starting at element index 0.
4913
If at most one iteration variable is present, the range loop produces
4914
iteration values from 0 up to <code>len(a)-1</code> and does not index into the array
4915
or slice itself. For a <code>nil</code> slice, the number of iterations is 0.
4916 4917 4918 4919 4920 4921
</li>

<li>
For a string value, the "range" clause iterates over the Unicode code points
in the string starting at byte index 0.  On successive iterations, the index value will be the
index of the first byte of successive UTF-8-encoded code points in the string,
4922
and the second value, of type <code>rune</code>, will be the value of
Rob Pike's avatar
Rob Pike committed
4923
the corresponding code point.  If the iteration encounters an invalid
4924
UTF-8 sequence, the second value will be <code>0xFFFD</code>,
Rob Pike's avatar
Rob Pike committed
4925 4926
the Unicode replacement character, and the next iteration will advance
a single byte in the string.
4927 4928 4929
</li>

<li>
4930 4931
The iteration order over maps is not specified
and is not guaranteed to be the same from one iteration to the next.
4932
If map entries that have not yet been reached are removed during iteration,
4933
the corresponding iteration values will not be produced. If map entries are
4934 4935 4936 4937
created during iteration, that entry may be produced during the iteration or
may be skipped. The choice may vary for each entry created and from one
iteration to the next.
If the map is <code>nil</code>, the number of iterations is 0.
4938 4939 4940 4941
</li>

<li>
For channels, the iteration values produced are the successive values sent on
4942 4943
the channel until the channel is <a href="#Close">closed</a>. If the channel
is <code>nil</code>, the range expression blocks forever.
4944
</li>
Anthony Martin's avatar
Anthony Martin committed
4945
</ol>
4946

Rob Pike's avatar
Rob Pike committed
4947
<p>
4948 4949
The iteration values are assigned to the respective
iteration variables as in an <a href="#Assignments">assignment statement</a>.
4950
</p>
4951

4952
<p>
Robert Griesemer's avatar
Robert Griesemer committed
4953
The iteration variables may be declared by the "range" clause using a form of
4954 4955
<a href="#Short_variable_declarations">short variable declaration</a>
(<code>:=</code>).
4956
In this case their types are set to the types of the respective iteration values
4957
and their <a href="#Declarations_and_scope">scope</a> is the block of the "for"
4958
statement; they are re-used in each iteration.
Rob Pike's avatar
Rob Pike committed
4959 4960 4961
If the iteration variables are declared outside the "for" statement,
after execution their values will be those of the last iteration.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
4962

4963
<pre>
4964 4965 4966 4967 4968 4969 4970 4971 4972
var testdata *struct {
	a *[7]int
}
for i, _ := range testdata.a {
	// testdata.a is never evaluated; len(testdata.a) is constant
	// i ranges from 0 to 6
	f(i)
}

4973
var a [10]string
4974 4975 4976 4977 4978 4979 4980
for i, s := range a {
	// type of i is int
	// type of s is string
	// s == a[i]
	g(i, s)
}

4981
var key string
4982
var val interface {}  // value type of m is assignable to val
4983
m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}
Rob Pike's avatar
Rob Pike committed
4984 4985
for key, val = range m {
	h(key, val)
4986 4987 4988
}
// key == last map key encountered in iteration
// val == map[key]
4989 4990 4991 4992 4993

var ch chan Work = producer()
for w := range ch {
	doWork(w)
}
4994 4995 4996

// empty a channel
for range ch {}
4997
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
4998

4999

5000
<h3 id="Go_statements">Go statements</h3>
5001

Rob Pike's avatar
Rob Pike committed
5002
<p>
5003
A "go" statement starts the execution of a function call
Rob Pike's avatar
Rob Pike committed
5004 5005 5006
as an independent concurrent thread of control, or <i>goroutine</i>,
within the same address space.
</p>
5007

5008
<pre class="ebnf">
5009
GoStmt = "go" Expression .
5010
</pre>
5011

Rob Pike's avatar
Rob Pike committed
5012
<p>
5013 5014 5015 5016 5017 5018
The expression must be a function or method call; it cannot be parenthesized.
Calls of built-in functions are restricted as for
<a href="#Expression_statements">expression statements</a>.
</p>

<p>
5019 5020 5021
The function value and parameters are
<a href="#Calls">evaluated as usual</a>
in the calling goroutine, but
Rob Pike's avatar
Rob Pike committed
5022
unlike with a regular call, program execution does not wait
5023
for the invoked function to complete.
5024 5025 5026 5027 5028
Instead, the function begins executing independently
in a new goroutine.
When the function terminates, its goroutine also terminates.
If the function has any return values, they are discarded when the
function completes.
Rob Pike's avatar
Rob Pike committed
5029
</p>
5030

5031 5032
<pre>
go Server()
5033
go func(ch chan&lt;- bool) { for { sleep(10); ch &lt;- true; }} (c)
5034
</pre>
5035 5036


5037
<h3 id="Select_statements">Select statements</h3>
5038

Rob Pike's avatar
Rob Pike committed
5039
<p>
5040 5041 5042 5043 5044 5045
A "select" statement chooses which of a set of possible
<a href="#Send_statements">send</a> or
<a href="#Receive_operator">receive</a>
operations will proceed.
It looks similar to a
<a href="#Switch_statements">"switch"</a> statement but with the
5046
cases all referring to communication operations.
Rob Pike's avatar
Rob Pike committed
5047
</p>
5048

5049
<pre class="ebnf">
5050
SelectStmt = "select" "{" { CommClause } "}" .
5051
CommClause = CommCase ":" StatementList .
5052
CommCase   = "case" ( SendStmt | RecvStmt ) | "default" .
5053
RecvStmt   = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
5054
RecvExpr   = Expression .
5055
</pre>
5056

5057
<p>
5058 5059 5060 5061 5062 5063
A case with a RecvStmt may assign the result of a RecvExpr to one or
two variables, which may be declared using a
<a href="#Short_variable_declarations">short variable declaration</a>.
The RecvExpr must be a (possibly parenthesized) receive operation.
There can be at most one default case and it may appear anywhere
in the list of cases.
Rob Pike's avatar
Rob Pike committed
5064
</p>
5065

5066
<p>
5067
Execution of a "select" statement proceeds in several steps:
Rob Pike's avatar
Rob Pike committed
5068
</p>
5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106

<ol>
<li>
For all the cases in the statement, the channel operands of receive operations
and the channel and right-hand-side expressions of send statements are
evaluated exactly once, in source order, upon entering the "select" statement.
The result is a set of channels to receive from or send to,
and the corresponding values to send.
Any side effects in that evaluation will occur irrespective of which (if any)
communication operation is selected to proceed.
Expressions on the left-hand side of a RecvStmt with a short variable declaration
or assignment are not yet evaluated.
</li>

<li>
If one or more of the communications can proceed,
a single one that can proceed is chosen via a uniform pseudo-random selection.
Otherwise, if there is a default case, that case is chosen.
If there is no default case, the "select" statement blocks until
at least one of the communications can proceed.
</li>

<li>
Unless the selected case is the default case, the respective communication
operation is executed.
</li>

<li>
If the selected case is a RecvStmt with a short variable declaration or
an assignment, the left-hand side expressions are evaluated and the
received value (or values) are assigned.
</li>

<li>
The statement list of the selected case is executed.
</li>
</ol>

5107
<p>
5108 5109
Since communication on <code>nil</code> channels can never proceed,
a select with only <code>nil</code> channels and no default case blocks forever.
Rob Pike's avatar
Rob Pike committed
5110
</p>
5111

5112
<pre>
5113 5114
var a []int
var c, c1, c2, c3, c4 chan int
5115
var i1, i2 int
5116 5117
select {
case i1 = &lt;-c1:
5118
	print("received ", i1, " from c1\n")
5119
case c2 &lt;- i2:
5120
	print("sent ", i2, " to c2\n")
5121
case i3, ok := (&lt;-c3):  // same as: i3, ok := &lt;-c3
5122 5123 5124 5125 5126
	if ok {
		print("received ", i3, " from c3\n")
	} else {
		print("c3 is closed\n")
	}
5127 5128 5129 5130
case a[f()] = &lt;-c4:
	// same as:
	// case t := &lt;-c4
	//	a[f()] = t
5131
default:
5132
	print("no communication\n")
5133 5134 5135
}

for {  // send random sequence of bits to c
5136
	select {
5137 5138
	case c &lt;- 0:  // note: no statement, no fallthrough, no folding of cases
	case c &lt;- 1:
5139
	}
5140
}
5141

5142
select {}  // block forever
5143
</pre>
5144 5145


5146
<h3 id="Return_statements">Return statements</h3>
5147

Rob Pike's avatar
Rob Pike committed
5148
<p>
5149 5150 5151 5152
A "return" statement in a function <code>F</code> terminates the execution
of <code>F</code>, and optionally provides one or more result values.
Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
are executed before <code>F</code> returns to its caller.
Rob Pike's avatar
Rob Pike committed
5153
</p>
5154

5155
<pre class="ebnf">
5156
ReturnStmt = "return" [ ExpressionList ] .
5157
</pre>
5158

5159 5160 5161 5162
<p>
In a function without a result type, a "return" statement must not
specify any result values.
</p>
Rob Pike's avatar
Rob Pike committed
5163
<pre>
5164
func noResult() {
Rob Pike's avatar
Rob Pike committed
5165 5166 5167
	return
}
</pre>
5168

Rob Pike's avatar
Rob Pike committed
5169
<p>
5170 5171
There are three ways to return values from a function with a result
type:
Rob Pike's avatar
Rob Pike committed
5172
</p>
5173

5174 5175 5176
<ol>
	<li>The return value or values may be explicitly listed
		in the "return" statement. Each expression must be single-valued
5177 5178
		and <a href="#Assignability">assignable</a>
		to the corresponding element of the function's result type.
5179
<pre>
5180
func simpleF() int {
Rob Pike's avatar
Rob Pike committed
5181 5182 5183
	return 2
}

5184
func complexF1() (re float64, im float64) {
Rob Pike's avatar
Rob Pike committed
5185
	return -7.0, -4.0
5186 5187
}
</pre>
5188 5189 5190 5191 5192 5193 5194
	</li>
	<li>The expression list in the "return" statement may be a single
		call to a multi-valued function. The effect is as if each value
		returned from that function were assigned to a temporary
		variable with the type of the respective value, followed by a
		"return" statement listing these variables, at which point the
		rules of the previous case apply.
5195
<pre>
5196 5197
func complexF2() (re float64, im float64) {
	return complexF1()
5198 5199
}
</pre>
5200
	</li>
Peter Mundy's avatar
Peter Mundy committed
5201
	<li>The expression list may be empty if the function's result
5202
		type specifies names for its <a href="#Function_types">result parameters</a>.
5203
		The result parameters act as ordinary local variables
5204 5205
		and the function may assign values to them as necessary.
		The "return" statement returns the values of these variables.
5206
<pre>
5207
func complexF3() (re float64, im float64) {
5208 5209 5210
	re = 7.0
	im = 4.0
	return
5211
}
5212

Russ Cox's avatar
Russ Cox committed
5213
func (devnull) Write(p []byte) (n int, _ error) {
5214 5215
	n = len(p)
	return
5216
}
5217
</pre>
5218 5219
	</li>
</ol>
5220

5221
<p>
5222 5223
Regardless of how they are declared, all the result values are initialized to
the <a href="#The_zero_value">zero values</a> for their type upon entry to the
5224 5225
function. A "return" statement that specifies results sets the result parameters before
any deferred functions are executed.
5226 5227
</p>

5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242
<p>
Implementation restriction: A compiler may disallow an empty expression list
in a "return" statement if a different entity (constant, type, or variable)
with the same name as a result parameter is in
<a href="#Declarations_and_scope">scope</a> at the place of the return.
</p>

<pre>
func f(n int) (res int, err error) {
	if _, err := f(n-1); err != nil {
		return  // invalid return statement: err is shadowed
	}
	return
}
</pre>
5243

5244
<h3 id="Break_statements">Break statements</h3>
5245

Rob Pike's avatar
Rob Pike committed
5246 5247
<p>
A "break" statement terminates execution of the innermost
5248 5249
<a href="#For_statements">"for"</a>,
<a href="#Switch_statements">"switch"</a>, or
5250 5251
<a href="#Select_statements">"select"</a> statement
within the same function.
Rob Pike's avatar
Rob Pike committed
5252
</p>
5253

5254
<pre class="ebnf">
5255
BreakStmt = "break" [ Label ] .
5256
</pre>
5257

Rob Pike's avatar
Rob Pike committed
5258 5259
<p>
If there is a label, it must be that of an enclosing
5260 5261
"for", "switch", or "select" statement,
and that is the one whose execution terminates.
Rob Pike's avatar
Rob Pike committed
5262
</p>
5263

5264
<pre>
5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275
OuterLoop:
	for i = 0; i &lt; n; i++ {
		for j = 0; j &lt; m; j++ {
			switch a[i][j] {
			case nil:
				state = Error
				break OuterLoop
			case item:
				state = Found
				break OuterLoop
			}
Russ Cox's avatar
Russ Cox committed
5276
		}
5277
	}
5278
</pre>
5279

5280
<h3 id="Continue_statements">Continue statements</h3>
5281

Rob Pike's avatar
Rob Pike committed
5282 5283
<p>
A "continue" statement begins the next iteration of the
5284
innermost <a href="#For_statements">"for" loop</a> at its post statement.
5285
The "for" loop must be within the same function.
Rob Pike's avatar
Rob Pike committed
5286
</p>
5287

5288
<pre class="ebnf">
5289
ContinueStmt = "continue" [ Label ] .
5290
</pre>
5291

Rob Pike's avatar
Rob Pike committed
5292
<p>
5293 5294
If there is a label, it must be that of an enclosing
"for" statement, and that is the one whose execution
5295
advances.
Rob Pike's avatar
Rob Pike committed
5296
</p>
5297

5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309
<pre>
RowLoop:
	for y, row := range rows {
		for x, data := range row {
			if data == endOfRow {
				continue RowLoop
			}
			row[x] = data + bias(x, y)
		}
	}
</pre>

5310
<h3 id="Goto_statements">Goto statements</h3>
5311

Rob Pike's avatar
Rob Pike committed
5312
<p>
5313 5314
A "goto" statement transfers control to the statement with the corresponding label
within the same function.
Rob Pike's avatar
Rob Pike committed
5315
</p>
5316

5317
<pre class="ebnf">
5318
GotoStmt = "goto" Label .
5319
</pre>
5320

5321 5322 5323
<pre>
goto Error
</pre>
5324

Rob Pike's avatar
Rob Pike committed
5325 5326
<p>
Executing the "goto" statement must not cause any variables to come into
Russ Cox's avatar
Russ Cox committed
5327 5328
<a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto.
For instance, this example:
Rob Pike's avatar
Rob Pike committed
5329
</p>
5330

5331
<pre>
Russ Cox's avatar
Russ Cox committed
5332 5333
	goto L  // BAD
	v := 3
5334 5335
L:
</pre>
5336

Rob Pike's avatar
Rob Pike committed
5337 5338 5339
<p>
is erroneous because the jump to label <code>L</code> skips
the creation of <code>v</code>.
Russ Cox's avatar
Russ Cox committed
5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360
</p>

<p>
A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block.
For instance, this example:
</p>

<pre>
if n%2 == 1 {
	goto L1
}
for n &gt; 0 {
	f()
	n--
L1:
	f()
	n--
}
</pre>

<p>
5361
is erroneous because the label <code>L1</code> is inside
Russ Cox's avatar
Russ Cox committed
5362
the "for" statement's block but the <code>goto</code> is not.
Rob Pike's avatar
Rob Pike committed
5363
</p>
5364

5365
<h3 id="Fallthrough_statements">Fallthrough statements</h3>
5366

Rob Pike's avatar
Rob Pike committed
5367 5368
<p>
A "fallthrough" statement transfers control to the first statement of the
Shenghou Ma's avatar
Shenghou Ma committed
5369
next case clause in an <a href="#Expression_switches">expression "switch" statement</a>.
5370
It may be used only as the final non-empty statement in such a clause.
Rob Pike's avatar
Rob Pike committed
5371
</p>
5372

5373
<pre class="ebnf">
5374
FallthroughStmt = "fallthrough" .
5375
</pre>
5376 5377


5378
<h3 id="Defer_statements">Defer statements</h3>
Robert Griesemer's avatar
Robert Griesemer committed
5379

Rob Pike's avatar
Rob Pike committed
5380
<p>
5381 5382 5383 5384 5385
A "defer" statement invokes a function whose execution is deferred
to the moment the surrounding function returns, either because the
surrounding function executed a <a href="#Return_statements">return statement</a>,
reached the end of its <a href="#Function_declarations">function body</a>,
or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>.
Rob Pike's avatar
Rob Pike committed
5386
</p>
Robert Griesemer's avatar
Robert Griesemer committed
5387

5388
<pre class="ebnf">
5389
DeferStmt = "defer" Expression .
5390
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
5391

Rob Pike's avatar
Rob Pike committed
5392
<p>
5393 5394 5395 5396 5397 5398
The expression must be a function or method call; it cannot be parenthesized.
Calls of built-in functions are restricted as for
<a href="#Expression_statements">expression statements</a>.
</p>

<p>
5399
Each time a "defer" statement
5400 5401
executes, the function value and parameters to the call are
<a href="#Calls">evaluated as usual</a>
5402 5403
and saved anew but the actual function is not invoked.
Instead, deferred functions are invoked immediately before
5404 5405
the surrounding function returns, in the reverse order
they were deferred.
5406 5407
If a deferred function value evaluates
to <code>nil</code>, execution <a href="#Handling_panics">panics</a>
Rob Pike's avatar
Rob Pike committed
5408
when the function is invoked, not when the "defer" statement is executed.
5409 5410 5411 5412
</p>

<p>
For instance, if the deferred function is
Rob Pike's avatar
Rob Pike committed
5413
a <a href="#Function_literals">function literal</a> and the surrounding
5414 5415 5416
function has <a href="#Function_types">named result parameters</a> that
are in scope within the literal, the deferred function may access and modify
the result parameters before they are returned.
5417 5418
If the deferred function has any return values, they are discarded when
the function completes.
5419 5420 5421
(See also the section on <a href="#Handling_panics">handling panics</a>.)
</p>

5422
<pre>
5423 5424
lock(l)
defer unlock(l)  // unlocking happens before surrounding function returns
Robert Griesemer's avatar
Robert Griesemer committed
5425

5426 5427
// prints 3 2 1 0 before surrounding function returns
for i := 0; i &lt;= 3; i++ {
5428
	defer fmt.Print(i)
5429
}
5430 5431 5432 5433 5434 5435 5436 5437

// f returns 1
func f() (result int) {
	defer func() {
		result++
	}()
	return 0
}
5438
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
5439

5440
<h2 id="Built-in_functions">Built-in functions</h2>
5441 5442

<p>
Rob Pike's avatar
Rob Pike committed
5443
Built-in functions are
5444 5445 5446 5447
<a href="#Predeclared_identifiers">predeclared</a>.
They are called like any other function but some of them
accept a type instead of an expression as the first argument.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
5448

5449 5450 5451 5452 5453 5454
<p>
The built-in functions do not have standard Go types,
so they can only appear in <a href="#Calls">call expressions</a>;
they cannot be used as function values.
</p>

5455
<h3 id="Close">Close</h3>
5456

Rob Pike's avatar
Rob Pike committed
5457
<p>
5458
For a channel <code>c</code>, the built-in function <code>close(c)</code>
5459 5460 5461 5462
records that no more values will be sent on the channel.
It is an error if <code>c</code> is a receive-only channel.
Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>.
Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>.
5463
After calling <code>close</code>, and after any previously
5464
sent values have been received, receive operations will return
5465
the zero value for the channel's type without blocking.
5466 5467
The multi-valued <a href="#Receive_operator">receive operation</a>
returns a received value along with an indication of whether the channel is closed.
Rob Pike's avatar
Rob Pike committed
5468
</p>
5469

5470

5471
<h3 id="Length_and_capacity">Length and capacity</h3>
5472

Rob Pike's avatar
Rob Pike committed
5473
<p>
5474 5475 5476
The built-in functions <code>len</code> and <code>cap</code> take arguments
of various types and return a result of type <code>int</code>.
The implementation guarantees that the result always fits into an <code>int</code>.
5477 5478
</p>

5479
<pre class="grammar">
5480
Call      Argument type    Result
5481

5482 5483 5484 5485 5486
len(s)    string type      string length in bytes
          [n]T, *[n]T      array length (== n)
          []T              slice length
          map[K]T          map length (number of defined keys)
          chan T           number of elements queued in channel buffer
5487

5488 5489 5490
cap(s)    [n]T, *[n]T      array length (== n)
          []T              slice capacity
          chan T           channel buffer capacity
5491
</pre>
5492

5493 5494 5495 5496 5497
<p>
The capacity of a slice is the number of elements for which there is
space allocated in the underlying array.
At any time the following relationship holds:
</p>
5498

5499
<pre>
Anthony Martin's avatar
Anthony Martin committed
5500
0 &lt;= len(s) &lt;= cap(s)
5501
</pre>
5502

5503
<p>
5504
The length of a <code>nil</code> slice, map or channel is 0.
5505
The capacity of a <code>nil</code> slice or channel is 0.
5506 5507
</p>

5508
<p>
5509 5510 5511 5512
The expression <code>len(s)</code> is <a href="#Constants">constant</a> if
<code>s</code> is a string constant. The expressions <code>len(s)</code> and
<code>cap(s)</code> are constants if the type of <code>s</code> is an array
or pointer to an array and the expression <code>s</code> does not contain
5513
<a href="#Receive_operator">channel receives</a> or (non-constant)
5514 5515 5516
<a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated.
Otherwise, invocations of <code>len</code> and <code>cap</code> are not
constant and <code>s</code> is evaluated.
5517
</p>
5518

5519 5520 5521 5522 5523 5524
<pre>
const (
	c1 = imag(2i)                    // imag(2i) = 2.0 is a constant
	c2 = len([10]float64{2})         // [10]float64{2} contains no function calls
	c3 = len([10]float64{c1})        // [10]float64{c1} contains no function calls
	c4 = len([10]float64{imag(2i)})  // imag(2i) is a constant and no function call is issued
Shenghou Ma's avatar
Shenghou Ma committed
5525
	c5 = len([10]float64{imag(z)})   // invalid: imag(z) is a (non-constant) function call
5526 5527 5528
)
var z complex128
</pre>
5529

5530
<h3 id="Allocation">Allocation</h3>
5531

Rob Pike's avatar
Rob Pike committed
5532
<p>
Robert Griesemer's avatar
Robert Griesemer committed
5533 5534 5535 5536 5537
The built-in function <code>new</code> takes a type <code>T</code>,
allocates storage for a <a href="#Variables">variable</a> of that type
at run time, and returns a value of type <code>*T</code>
<a href="#Pointer_types">pointing</a> to it.
The variable is initialized as described in the section on
5538
<a href="#The_zero_value">initial values</a>.
Rob Pike's avatar
Rob Pike committed
5539
</p>
5540

5541
<pre class="grammar">
5542 5543
new(T)
</pre>
5544

Rob Pike's avatar
Rob Pike committed
5545
<p>
5546
For instance
Rob Pike's avatar
Rob Pike committed
5547
</p>
5548

5549
<pre>
5550
type S struct { a int; b float64 }
5551 5552
new(S)
</pre>
5553

5554
<p>
Robert Griesemer's avatar
Robert Griesemer committed
5555
allocates storage for a variable of type <code>S</code>,
Rob Pike's avatar
Rob Pike committed
5556 5557
initializes it (<code>a=0</code>, <code>b=0.0</code>),
and returns a value of type <code>*S</code> containing the address
Robert Griesemer's avatar
Robert Griesemer committed
5558
of the location.
Rob Pike's avatar
Rob Pike committed
5559
</p>
Robert Griesemer's avatar
Robert Griesemer committed
5560

5561
<h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3>
Robert Griesemer's avatar
Robert Griesemer committed
5562

Rob Pike's avatar
Rob Pike committed
5563 5564 5565 5566 5567
<p>
The built-in function <code>make</code> takes a type <code>T</code>,
which must be a slice, map or channel type,
optionally followed by a type-specific list of expressions.
It returns a value of type <code>T</code> (not <code>*T</code>).
5568 5569
The memory is initialized as described in the section on
<a href="#The_zero_value">initial values</a>.
Rob Pike's avatar
Rob Pike committed
5570
</p>
Robert Griesemer's avatar
Robert Griesemer committed
5571

5572
<pre class="grammar">
5573
Call             Type T     Result
Robert Griesemer's avatar
Robert Griesemer committed
5574

5575 5576
make(T, n)       slice      slice of type T with length n and capacity n
make(T, n, m)    slice      slice of type T with length n and capacity m
Robert Griesemer's avatar
Robert Griesemer committed
5577

5578 5579 5580
make(T)          map        map of type T
make(T, n)       map        map of type T with initial space for n elements

5581 5582
make(T)          channel    unbuffered channel of type T
make(T, n)       channel    buffered channel of type T, buffer size n
5583
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
5584 5585


Rob Pike's avatar
Rob Pike committed
5586
<p>
5587
The size arguments <code>n</code> and <code>m</code> must be of integer type or untyped.
5588 5589 5590
A <a href="#Constants">constant</a> size argument must be non-negative and
representable by a value of type <code>int</code>.
If both <code>n</code> and <code>m</code> are provided and are constant, then
5591 5592 5593
<code>n</code> must be no larger than <code>m</code>.
If <code>n</code> is negative or larger than <code>m</code> at run time,
a <a href="#Run_time_panics">run-time panic</a> occurs.
Rob Pike's avatar
Rob Pike committed
5594
</p>
Robert Griesemer's avatar
Robert Griesemer committed
5595

5596
<pre>
5597
s := make([]int, 10, 100)       // slice with len(s) == 10, cap(s) == 100
5598
s := make([]int, 1e3)           // slice with len(s) == cap(s) == 1000
5599
s := make([]int, 1&lt;&lt;63)         // illegal: len(s) is not representable by a value of type int
5600
s := make([]int, 10, 0)         // illegal: len(s) > cap(s)
5601 5602
c := make(chan int, 10)         // channel with a buffer size of 10
m := make(map[string]int, 100)  // map with initial space for 100 elements
5603
</pre>
5604

5605

Robert Griesemer's avatar
Robert Griesemer committed
5606
<h3 id="Appending_and_copying_slices">Appending to and copying slices</h3>
5607 5608

<p>
5609 5610 5611 5612
The built-in functions <code>append</code> and <code>copy</code> assist in
common slice operations.
For both functions, the result is independent of whether the memory referenced
by the arguments overlaps.
Robert Griesemer's avatar
Robert Griesemer committed
5613 5614 5615
</p>

<p>
5616 5617
The <a href="#Function_types">variadic</a> function <code>append</code>
appends zero or more values <code>x</code>
5618 5619
to <code>s</code> of type <code>S</code>, which must be a slice type, and
returns the resulting slice, also of type <code>S</code>.
5620 5621 5622 5623
The values <code>x</code> are passed to a parameter of type <code>...T</code>
where <code>T</code> is the <a href="#Slice_types">element type</a> of
<code>S</code> and the respective
<a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply.
5624 5625 5626 5627
As a special case, <code>append</code> also accepts a first argument
assignable to type <code>[]byte</code> with a second argument of
string type followed by <code>...</code>. This form appends the
bytes of the string.
Robert Griesemer's avatar
Robert Griesemer committed
5628 5629 5630
</p>

<pre class="grammar">
5631
append(s S, x ...T) S  // T is the element type of S
Robert Griesemer's avatar
Robert Griesemer committed
5632 5633 5634 5635
</pre>

<p>
If the capacity of <code>s</code> is not large enough to fit the additional
5636 5637 5638
values, <code>append</code> allocates a new, sufficiently large underlying
array that fits both the existing slice elements and the additional values.
Otherwise, <code>append</code> re-uses the underlying array.
Robert Griesemer's avatar
Robert Griesemer committed
5639 5640 5641 5642
</p>

<pre>
s0 := []int{0, 0}
5643 5644 5645 5646
s1 := append(s0, 2)                // append a single element     s1 == []int{0, 0, 2}
s2 := append(s1, 3, 5, 7)          // append multiple elements    s2 == []int{0, 0, 2, 3, 5, 7}
s3 := append(s2, s0...)            // append a slice              s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
s4 := append(s3[3:6], s3[2:]...)   // append overlapping slice    s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
5647 5648

var t []interface{}
5649
t = append(t, 42, 3.1415, "foo")   //                             t == []interface{}{42, 3.1415, "foo"}
5650 5651

var b []byte
5652
b = append(b, "bar"...)            // append string contents      b == []byte{'b', 'a', 'r' }
Robert Griesemer's avatar
Robert Griesemer committed
5653 5654 5655 5656
</pre>

<p>
The function <code>copy</code> copies slice elements from
5657
a source <code>src</code> to a destination <code>dst</code> and returns the
5658
number of elements copied.
5659
Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be
5660
<a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>.
5661
The number of elements copied is the minimum of
5662
<code>len(src)</code> and <code>len(dst)</code>.
5663 5664 5665
As a special case, <code>copy</code> also accepts a destination argument assignable
to type <code>[]byte</code> with a source argument of a string type.
This form copies the bytes from the string into the byte slice.
5666 5667 5668 5669
</p>

<pre class="grammar">
copy(dst, src []T) int
5670
copy(dst []byte, src string) int
5671 5672 5673 5674 5675 5676 5677
</pre>

<p>
Examples:
</p>

<pre>
5678 5679
var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7}
var s = make([]int, 6)
5680 5681 5682 5683
var b = make([]byte, 5)
n1 := copy(s, a[0:])            // n1 == 6, s == []int{0, 1, 2, 3, 4, 5}
n2 := copy(s, s[2:])            // n2 == 4, s == []int{2, 3, 4, 5, 4, 5}
n3 := copy(b, "Hello, World!")  // n3 == 5, b == []byte("Hello")
5684 5685
</pre>

5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700

<h3 id="Deletion_of_map_elements">Deletion of map elements</h3>

<p>
The built-in function <code>delete</code> removes the element with key
<code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The
type of <code>k</code> must be <a href="#Assignability">assignable</a>
to the key type of <code>m</code>.
</p>

<pre class="grammar">
delete(m, k)  // remove element m[k] from map m
</pre>

<p>
5701 5702
If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code>
does not exist, <code>delete</code> is a no-op.
5703 5704 5705
</p>


5706
<h3 id="Complex_numbers">Manipulating complex numbers</h3>
Rob Pike's avatar
Rob Pike committed
5707 5708 5709

<p>
Three functions assemble and disassemble complex numbers.
5710
The built-in function <code>complex</code> constructs a complex
Rob Pike's avatar
Rob Pike committed
5711 5712 5713 5714 5715 5716
value from a floating-point real and imaginary part, while
<code>real</code> and <code>imag</code>
extract the real and imaginary parts of a complex value.
</p>

<pre class="grammar">
5717
complex(realPart, imaginaryPart floatT) complexT
Rob Pike's avatar
Rob Pike committed
5718 5719 5720 5721 5722 5723
real(complexT) floatT
imag(complexT) floatT
</pre>

<p>
The type of the arguments and return value correspond.
5724
For <code>complex</code>, the two arguments must be of the same
Rob Pike's avatar
Rob Pike committed
5725 5726
floating-point type and the return type is the complex type
with the corresponding floating-point constituents:
5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748
<code>complex64</code> for <code>float32</code> arguments, and
<code>complex128</code> for <code>float64</code> arguments.
If one of the arguments evaluates to an untyped constant, it is first
<a href="#Conversions">converted</a> to the type of the other argument.
If both arguments evaluate to untyped constants, they must be non-complex
numbers or their imaginary parts must be zero, and the return value of
the function is an untyped complex constant.
</p>

<p>
For <code>real</code> and <code>imag</code>, the argument must be
of complex type, and the return type is the corresponding floating-point
type: <code>float32</code> for a <code>complex64</code> argument, and
<code>float64</code> for a <code>complex128</code> argument.
If the argument evaluates to an untyped constant, it must be a number,
and the return value of the function is an untyped floating-point constant.
</p>

<p>
The <code>real</code> and <code>imag</code> functions together form the inverse of
<code>complex</code>, so for a value <code>z</code> of a complex type <code>Z</code>,
<code>z&nbsp;==&nbsp;Z(complex(real(z),&nbsp;imag(z)))</code>.
Rob Pike's avatar
Rob Pike committed
5749 5750 5751 5752 5753 5754 5755 5756
</p>

<p>
If the operands of these functions are all constants, the return
value is a constant.
</p>

<pre>
5757
var a = complex(2, -2)             // complex128
5758
const b = complex(1.0, -1.4)       // untyped complex constant 1 - 1.4i
5759 5760
x := float32(math.Cos(math.Pi/2))  // float32
var c64 = complex(5, -x)           // complex64
5761 5762
var s uint = complex(1, 0)         // untyped complex constant 1 + 0i can be converted to uint
_ = complex(1, 2&lt;&lt;s)               // illegal: 2 assumes floating-point type, cannot shift
5763
var rl = real(c64)                 // float32
5764 5765
var im = imag(a)                   // float64
const c = imag(b)                  // untyped constant -1.4
5766
_ = imag(3 &lt;&lt; s)                   // illegal: 3 assumes complex type, cannot shift
Rob Pike's avatar
Rob Pike committed
5767 5768
</pre>

Rob Pike's avatar
Rob Pike committed
5769 5770 5771 5772
<h3 id="Handling_panics">Handling panics</h3>

<p> Two built-in functions, <code>panic</code> and <code>recover</code>,
assist in reporting and handling <a href="#Run_time_panics">run-time panics</a>
5773
and program-defined error conditions.
Rob Pike's avatar
Rob Pike committed
5774 5775 5776 5777 5778 5779 5780 5781
</p>

<pre class="grammar">
func panic(interface{})
func recover() interface{}
</pre>

<p>
5782 5783 5784
While executing a function <code>F</code>,
an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a>
terminates the execution of <code>F</code>.
5785
Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
5786 5787 5788 5789
are then executed as usual.
Next, any deferred functions run by <code>F's</code> caller are run,
and so on up to any deferred by the top-level function in the executing goroutine.
At that point, the program is terminated and the error
5790 5791
condition is reported, including the value of the argument to <code>panic</code>.
This termination sequence is called <i>panicking</i>.
Rob Pike's avatar
Rob Pike committed
5792 5793
</p>

5794 5795 5796 5797 5798 5799
<pre>
panic(42)
panic("unreachable")
panic(Error("cannot parse"))
</pre>

Rob Pike's avatar
Rob Pike committed
5800 5801
<p>
The <code>recover</code> function allows a program to manage behavior
5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817
of a panicking goroutine.
Suppose a function <code>G</code> defers a function <code>D</code> that calls
<code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code>
is executing.
When the running of deferred functions reaches <code>D</code>,
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>.
If <code>D</code> returns normally, without starting a new
<code>panic</code>, the panicking sequence stops. In that case,
the state of functions called between <code>G</code> and the call to <code>panic</code>
is discarded, and normal execution resumes.
Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s
execution terminates by returning to its caller.
</p>

<p>
The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds:
Rob Pike's avatar
Rob Pike committed
5818
</p>
5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829
<ul>
<li>
<code>panic</code>'s argument was <code>nil</code>;
</li>
<li>
the goroutine is not panicking;
</li>
<li>
<code>recover</code> was not called directly by a deferred function.
</li>
</ul>
Rob Pike's avatar
Rob Pike committed
5830 5831

<p>
5832 5833 5834
The <code>protect</code> function in the example below invokes
the function argument <code>g</code> and protects callers from
run-time panics raised by <code>g</code>.
Rob Pike's avatar
Rob Pike committed
5835 5836 5837
</p>

<pre>
5838
func protect(g func()) {
Rob Pike's avatar
Rob Pike committed
5839
	defer func() {
5840
		log.Println("done")  // Println executes normally even if there is a panic
Rob Pike's avatar
Rob Pike committed
5841
		if x := recover(); x != nil {
5842
			log.Printf("run time panic: %v", x)
Rob Pike's avatar
Rob Pike committed
5843
		}
5844
	}()
5845 5846
	log.Println("start")
	g()
Rob Pike's avatar
Rob Pike committed
5847 5848 5849
}
</pre>

5850

5851 5852
<h3 id="Bootstrapping">Bootstrapping</h3>

5853
<p>
5854 5855 5856
Current implementations provide several built-in functions useful during
bootstrapping. These functions are documented for completeness but are not
guaranteed to stay in the language. They do not return a result.
5857 5858
</p>

5859
<pre class="grammar">
5860
Function   Behavior
5861 5862 5863 5864 5865 5866

print      prints all arguments; formatting of arguments is implementation-specific
println    like print but prints spaces between arguments and a newline at the end
</pre>


5867
<h2 id="Packages">Packages</h2>
5868

Rob Pike's avatar
Rob Pike committed
5869 5870
<p>
Go programs are constructed by linking together <i>packages</i>.
5871 5872 5873 5874 5875
A package in turn is constructed from one or more source files
that together declare constants, types, variables and functions
belonging to the package and which are accessible in all files
of the same package. Those elements may be
<a href="#Exported_identifiers">exported</a> and used in another package.
Rob Pike's avatar
Rob Pike committed
5876 5877
</p>

5878
<h3 id="Source_file_organization">Source file organization</h3>
Rob Pike's avatar
Rob Pike committed
5879 5880 5881 5882 5883 5884

<p>
Each source file consists of a package clause defining the package
to which it belongs, followed by a possibly empty set of import
declarations that declare packages whose contents it wishes to use,
followed by a possibly empty set of declarations of functions,
Robert Griesemer's avatar
Robert Griesemer committed
5885
types, variables, and constants.
Rob Pike's avatar
Rob Pike committed
5886
</p>
5887

5888
<pre class="ebnf">
5889
SourceFile       = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
5890
</pre>
5891

5892
<h3 id="Package_clause">Package clause</h3>
Rob Pike's avatar
Rob Pike committed
5893

5894
<p>
Rob Pike's avatar
Rob Pike committed
5895 5896 5897
A package clause begins each source file and defines the package
to which the file belongs.
</p>
5898

5899
<pre class="ebnf">
Robert Griesemer's avatar
Robert Griesemer committed
5900 5901
PackageClause  = "package" PackageName .
PackageName    = identifier .
Rob Pike's avatar
Rob Pike committed
5902
</pre>
5903

Robert Griesemer's avatar
Robert Griesemer committed
5904 5905 5906 5907
<p>
The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>.
</p>

Rob Pike's avatar
Rob Pike committed
5908 5909
<pre>
package math
5910
</pre>
5911

Rob Pike's avatar
Rob Pike committed
5912 5913 5914 5915
<p>
A set of files sharing the same PackageName form the implementation of a package.
An implementation may require that all source files for a package inhabit the same directory.
</p>
5916

5917
<h3 id="Import_declarations">Import declarations</h3>
Rob Pike's avatar
Rob Pike committed
5918 5919

<p>
5920 5921 5922
An import declaration states that the source file containing the declaration
depends on functionality of the <i>imported</i> package
(<a href="#Program_initialization_and_execution">§Program initialization and execution</a>)
5923
and enables access to <a href="#Exported_identifiers">exported</a> identifiers
5924 5925
of that package.
The import names an identifier (PackageName) to be used for access and an ImportPath
Rob Pike's avatar
Rob Pike committed
5926
that specifies the package to be imported.
Rob Pike's avatar
Rob Pike committed
5927
</p>
5928

5929
<pre class="ebnf">
5930
ImportDecl       = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
5931
ImportSpec       = [ "." | PackageName ] ImportPath .
5932
ImportPath       = string_lit .
5933
</pre>
5934

5935
<p>
Rob Pike's avatar
Rob Pike committed
5936
The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a>
5937
to access exported identifiers of the package within the importing source file.
Rob Pike's avatar
Rob Pike committed
5938 5939
It is declared in the <a href="#Blocks">file block</a>.
If the PackageName is omitted, it defaults to the identifier specified in the
Robert Griesemer's avatar
Robert Griesemer committed
5940
<a href="#Package_clause">package clause</a> of the imported package.
Rob Pike's avatar
Rob Pike committed
5941
If an explicit period (<code>.</code>) appears instead of a name, all the
5942 5943
package's exported identifiers declared in that package's
<a href="#Blocks">package block</a> will be declared in the importing source
5944
file's file block and must be accessed without a qualifier.
Rob Pike's avatar
Rob Pike committed
5945 5946 5947 5948 5949 5950
</p>

<p>
The interpretation of the ImportPath is implementation-dependent but
it is typically a substring of the full file name of the compiled
package and may be relative to a repository of installed packages.
Rob Pike's avatar
Rob Pike committed
5951
</p>
Russ Cox's avatar
Russ Cox committed
5952

5953 5954 5955
<p>
Implementation restriction: A compiler may restrict ImportPaths to
non-empty strings using only characters belonging to
5956
<a href="http://www.unicode.org/versions/Unicode6.3.0/">Unicode's</a>
5957
L, M, N, P, and S general categories (the Graphic characters without
5958 5959 5960
spaces) and may also exclude the characters
<code>!"#$%&amp;'()*,:;&lt;=&gt;?[\]^`{|}</code>
and the Unicode replacement character U+FFFD.
5961 5962
</p>

5963
<p>
Rob Pike's avatar
Rob Pike committed
5964 5965 5966
Assume we have compiled a package containing the package clause
<code>package math</code>, which exports function <code>Sin</code>, and
installed the compiled package in the file identified by
Rob Pike's avatar
Rob Pike committed
5967
<code>"lib/math"</code>.
5968
This table illustrates how <code>Sin</code> is accessed in files
Rob Pike's avatar
Rob Pike committed
5969 5970
that import the package after the
various types of import declaration.
Rob Pike's avatar
Rob Pike committed
5971
</p>
5972

Rob Pike's avatar
Rob Pike committed
5973
<pre class="grammar">
5974
Import declaration          Local name of Sin
Rob Pike's avatar
Rob Pike committed
5975 5976

import   "lib/math"         math.Sin
5977
import m "lib/math"         m.Sin
Rob Pike's avatar
Rob Pike committed
5978
import . "lib/math"         Sin
5979
</pre>
5980

5981
<p>
Rob Pike's avatar
Rob Pike committed
5982 5983
An import declaration declares a dependency relation between
the importing and imported package.
5984 5985
It is illegal for a package to import itself, directly or indirectly,
or to directly import a package without
5986 5987 5988 5989 5990 5991 5992 5993 5994 5995
referring to any of its exported identifiers. To import a package solely for
its side-effects (initialization), use the <a href="#Blank_identifier">blank</a>
identifier as explicit package name:
</p>

<pre>
import _ "lib/math"
</pre>


5996
<h3 id="An_example_package">An example package</h3>
Rob Pike's avatar
Rob Pike committed
5997 5998 5999 6000

<p>
Here is a complete Go package that implements a concurrent prime sieve.
</p>
6001

6002 6003 6004
<pre>
package main

Rob Pike's avatar
Rob Pike committed
6005 6006
import "fmt"

6007
// Send the sequence 2, 3, 4, … to channel 'ch'.
6008
func generate(ch chan&lt;- int) {
6009
	for i := 2; ; i++ {
6010
		ch &lt;- i  // Send 'i' to channel 'ch'.
6011
	}
6012 6013
}

Fazlul Shahriar's avatar
Fazlul Shahriar committed
6014
// Copy the values from channel 'src' to channel 'dst',
6015
// removing those divisible by 'prime'.
6016
func filter(src &lt;-chan int, dst chan&lt;- int, prime int) {
6017
	for i := range src {  // Loop over values received from 'src'.
6018
		if i%prime != 0 {
6019
			dst &lt;- i  // Send 'i' to channel 'dst'.
6020 6021
		}
	}
6022 6023 6024 6025
}

// The prime sieve: Daisy-chain filter processes together.
func sieve() {
6026 6027
	ch := make(chan int)  // Create a new channel.
	go generate(ch)       // Start generate() as a subprocess.
6028
	for {
6029 6030 6031 6032 6033
		prime := &lt;-ch
		fmt.Print(prime, "\n")
		ch1 := make(chan int)
		go filter(ch, ch1, prime)
		ch = ch1
6034
	}
6035
}
6036

6037
func main() {
6038
	sieve()
6039 6040
}
</pre>
6041

6042
<h2 id="Program_initialization_and_execution">Program initialization and execution</h2>
6043

6044
<h3 id="The_zero_value">The zero value</h3>
Rob Pike's avatar
Rob Pike committed
6045
<p>
Robert Griesemer's avatar
Robert Griesemer committed
6046 6047 6048 6049 6050 6051
When storage is allocated for a <a href="#Variables">variable</a>,
either through a declaration or a call of <code>new</code>, or when
a new value is created, either through a composite literal or a call
of <code>make</code>,
and no explicit initialization is provided, the variable or value is
given a default value.  Each element of such a variable or value is
6052
set to the <i>zero value</i> for its type: <code>false</code> for booleans,
Rob Pike's avatar
Rob Pike committed
6053
<code>0</code> for integers, <code>0.0</code> for floats, <code>""</code>
6054
for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps.
Rob Pike's avatar
Rob Pike committed
6055
This initialization is done recursively, so for instance each element of an
Rob Pike's avatar
Rob Pike committed
6056 6057
array of structs will have its fields zeroed if no value is specified.
</p>
6058
<p>
6059
These two simple declarations are equivalent:
Rob Pike's avatar
Rob Pike committed
6060
</p>
6061

6062
<pre>
6063 6064
var i int
var i int = 0
6065
</pre>
6066

Rob Pike's avatar
Rob Pike committed
6067
<p>
6068
After
Rob Pike's avatar
Rob Pike committed
6069
</p>
6070

6071
<pre>
6072
type T struct { i int; f float64; next *T }
6073
t := new(T)
6074
</pre>
6075

Rob Pike's avatar
Rob Pike committed
6076
<p>
6077
the following holds:
Rob Pike's avatar
Rob Pike committed
6078
</p>
6079

6080 6081 6082 6083 6084
<pre>
t.i == 0
t.f == 0.0
t.next == nil
</pre>
6085

Rob Pike's avatar
Rob Pike committed
6086 6087 6088 6089 6090 6091 6092 6093
<p>
The same would also be true after
</p>

<pre>
var t T
</pre>

6094
<h3 id="Package_initialization">Package initialization</h3>
6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111

<p>
Within a package, package-level variables are initialized in
<i>declaration order</i> but after any of the variables
they <i>depend</i> on.
</p>

<p>
More precisely, a package-level variable is considered <i>ready for
initialization</i> if it is not yet initialized and either has
no <a href="#Variable_declarations">initialization expression</a> or
its initialization expression has no dependencies on uninitialized variables.
Initialization proceeds by repeatedly initializing the next package-level
variable that is earliest in declaration order and ready for initialization,
until there are no variables ready for initialization.
</p>

6112
<p>
6113 6114 6115 6116 6117 6118 6119 6120 6121 6122
If any variables are still uninitialized when this
process ends, those variables are part of one or more initialization cycles,
and the program is not valid.
</p>

<p>
The declaration order of variables declared in multiple files is determined
by the order in which the files are presented to the compiler: Variables
declared in the first file are declared before any of the variables declared
in the second file, and so on.
6123 6124 6125 6126 6127
</p>

<p>
Dependency analysis does not rely on the actual values of the
variables, only on lexical <i>references</i> to them in the source,
6128 6129 6130
analyzed transitively. For instance, if a variable <code>x</code>'s
initialization expression refers to a function whose body refers to
variable <code>y</code> then <code>x</code> depends on <code>y</code>.
6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142
Specifically:
</p>

<ul>
<li>
A reference to a variable or function is an identifier denoting that
variable or function.
</li>

<li>
A reference to a method <code>m</code> is a
<a href="#Method_values">method value</a> or
6143
<a href="#Method_expressions">method expression</a> of the form
6144 6145 6146 6147 6148 6149 6150 6151
<code>t.m</code>, where the (static) type of <code>t</code> is
not an interface type, and the method <code>m</code> is in the
<a href="#Method_sets">method set</a> of <code>t</code>.
It is immaterial whether the resulting function value
<code>t.m</code> is invoked.
</li>

<li>
6152
A variable, function, or method <code>x</code> depends on a variable
6153 6154 6155 6156 6157 6158
<code>y</code> if <code>x</code>'s initialization expression or body
(for functions and methods) contains a reference to <code>y</code>
or to a function or method that depends on <code>y</code>.
</li>
</ul>

Rob Pike's avatar
Rob Pike committed
6159
<p>
6160 6161 6162
Dependency analysis is performed per package; only references referring
to variables, functions, and methods declared in the current package
are considered.
Rob Pike's avatar
Rob Pike committed
6163
</p>
6164 6165 6166 6167 6168

<p>
For example, given the declarations
</p>

Rob Pike's avatar
Rob Pike committed
6169
<pre>
6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180
var (
	a = c + b
	b = f()
	c = f()
	d = 3
)

func f() int {
	d++
	return d
}
Rob Pike's avatar
Rob Pike committed
6181
</pre>
6182

Rob Pike's avatar
Rob Pike committed
6183
<p>
6184
the initialization order is <code>d</code>, <code>b</code>, <code>c</code>, <code>a</code>.
Rob Pike's avatar
Rob Pike committed
6185
</p>
6186

6187
<p>
6188 6189
Variables may also be initialized using functions named <code>init</code>
declared in the package block, with no arguments and no result parameters.
6190
</p>
6191 6192 6193 6194 6195

<pre>
func init() { … }
</pre>

6196
<p>
6197 6198 6199 6200
Multiple such functions may be defined per package, even within a single
source file. In the package block, the <code>init</code> identifier can
be used only to declare <code>init</code> functions, yet the identifier
itself is not <a href="#Declarations_and_scope">declared</a>. Thus
6201 6202
<code>init</code> functions cannot be referred to from anywhere
in a program.
Rob Pike's avatar
Rob Pike committed
6203
</p>
6204

6205
<p>
6206 6207
A package with no imports is initialized by assigning initial values
to all its package-level variables followed by calling all <code>init</code>
6208 6209
functions in the order they appear in the source, possibly in multiple files,
as presented to the compiler.
6210
If a package has imports, the imported packages are initialized
6211
before initializing the package itself. If multiple packages import
6212 6213 6214
a package, the imported package will be initialized only once.
The importing of packages, by construction, guarantees that there
can be no cyclic initialization dependencies.
Rob Pike's avatar
Rob Pike committed
6215
</p>
6216

6217
<p>
6218 6219 6220 6221 6222 6223 6224 6225
Package initialization&mdash;variable initialization and the invocation of
<code>init</code> functions&mdash;happens in a single goroutine,
sequentially, one package at a time.
An <code>init</code> function may launch other goroutines, which can run
concurrently with the initialization code. However, initialization
always sequences
the <code>init</code> functions: it will not invoke the next one
until the previous one has returned.
Rob Pike's avatar
Rob Pike committed
6226
</p>
6227

6228 6229 6230 6231 6232 6233
<p>
To ensure reproducible initialization behavior, build systems are encouraged
to present multiple files belonging to the same package in lexical file name
order to a compiler.
</p>

6234 6235

<h3 id="Program_execution">Program execution</h3>
6236
<p>
6237 6238 6239 6240
A complete program is created by linking a single, unimported package
called the <i>main package</i> with all the packages it imports, transitively.
The main package must
have package name <code>main</code> and
6241
declare a function <code>main</code> that takes no
6242
arguments and returns no value.
Rob Pike's avatar
Rob Pike committed
6243
</p>
6244

6245
<pre>
6246
func main() { … }
6247
</pre>
6248

Rob Pike's avatar
Rob Pike committed
6249
<p>
6250 6251
Program execution begins by initializing the main package and then
invoking the function <code>main</code>.
6252
When that function invocation returns, the program exits.
6253
It does not wait for other (non-<code>main</code>) goroutines to complete.
Rob Pike's avatar
Rob Pike committed
6254
</p>
6255

Russ Cox's avatar
Russ Cox committed
6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277
<h2 id="Errors">Errors</h2>

<p>
The predeclared type <code>error</code> is defined as
</p>

<pre>
type error interface {
	Error() string
}
</pre>

<p>
It is the conventional interface for representing an error condition,
with the nil value representing no error.
For instance, a function to read data from a file might be defined:
</p>

<pre>
func Read(f *File, b []byte) (n int, err error)
</pre>

Evan Shaw's avatar
Evan Shaw committed
6278
<h2 id="Run_time_panics">Run-time panics</h2>
Rob Pike's avatar
Rob Pike committed
6279 6280 6281 6282 6283 6284

<p>
Execution errors such as attempting to index an array out
of bounds trigger a <i>run-time panic</i> equivalent to a call of
the built-in function <a href="#Handling_panics"><code>panic</code></a>
with a value of the implementation-defined interface type <code>runtime.Error</code>.
6285
That type satisfies the predeclared interface type
Russ Cox's avatar
Russ Cox committed
6286 6287 6288
<a href="#Errors"><code>error</code></a>.
The exact error values that
represent distinct run-time error conditions are unspecified.
Rob Pike's avatar
Rob Pike committed
6289 6290 6291 6292 6293 6294
</p>

<pre>
package runtime

type Error interface {
Russ Cox's avatar
Russ Cox committed
6295 6296
	error
	// and perhaps other methods
Rob Pike's avatar
Rob Pike committed
6297 6298 6299
}
</pre>

6300
<h2 id="System_considerations">System considerations</h2>
6301

6302
<h3 id="Package_unsafe">Package <code>unsafe</code></h3>
6303

6304
<p>
Rob Pike's avatar
Rob Pike committed
6305 6306 6307
The built-in package <code>unsafe</code>, known to the compiler,
provides facilities for low-level programming including operations
that violate the type system. A package using <code>unsafe</code>
6308 6309
must be vetted manually for type safety and may not be portable.
The package provides the following interface:
6310
</p>
6311

Rob Pike's avatar
Rob Pike committed
6312
<pre class="grammar">
6313
package unsafe
6314

6315 6316
type ArbitraryType int  // shorthand for an arbitrary Go type; it is not a real type
type Pointer *ArbitraryType
6317

6318
func Alignof(variable ArbitraryType) uintptr
Hong Ruiqi's avatar
Hong Ruiqi committed
6319
func Offsetof(selector ArbitraryType) uintptr
6320
func Sizeof(variable ArbitraryType) uintptr
6321
</pre>
6322

6323
<p>
6324 6325
A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code>
value may not be <a href="#Address_operators">dereferenced</a>.
6326 6327 6328
Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to
a <code>Pointer</code> type and vice versa.
The effect of converting between <code>Pointer</code> and <code>uintptr</code> is implementation-defined.
6329
</p>
6330 6331 6332 6333 6334 6335 6336

<pre>
var f float64
bits = *(*uint64)(unsafe.Pointer(&amp;f))

type ptr unsafe.Pointer
bits = *(*uint64)(ptr(&amp;f))
6337 6338

var p ptr = nil
6339 6340
</pre>

6341
<p>
6342 6343 6344
The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code>
of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code>
as if <code>v</code> was declared via <code>var v = x</code>.
6345
</p>
6346
<p>
6347
The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a>
6348 6349 6350 6351
<code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code>
or <code>*s</code>, and returns the field offset in bytes relative to the struct's address.
If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable
without pointer indirections through fields of the struct.
Rob Pike's avatar
Rob Pike committed
6352
For a struct <code>s</code> with field <code>f</code>:
6353
</p>
6354

6355
<pre>
6356
uintptr(unsafe.Pointer(&amp;s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&amp;s.f))
6357
</pre>
6358

6359
<p>
6360 6361 6362 6363 6364 6365 6366
Computer architectures may require memory addresses to be <i>aligned</i>;
that is, for addresses of a variable to be a multiple of a factor,
the variable's type's <i>alignment</i>.  The function <code>Alignof</code>
takes an expression denoting a variable of any type and returns the
alignment of the (type of the) variable in bytes.  For a variable
<code>x</code>:
</p>
6367

6368
<pre>
6369
uintptr(unsafe.Pointer(&amp;x)) % unsafe.Alignof(x) == 0
6370
</pre>
6371

6372 6373
<p>
Calls to <code>Alignof</code>, <code>Offsetof</code>, and
6374
<code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>.
Rob Pike's avatar
Rob Pike committed
6375
</p>
6376

6377
<h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3>
6378

6379
<p>
6380
For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed:
6381
</p>
6382

Rob Pike's avatar
Rob Pike committed
6383
<pre class="grammar">
6384
type                                 size in bytes
6385

6386 6387 6388 6389 6390
byte, uint8, int8                     1
uint16, int16                         2
uint32, int32, float32                4
uint64, int64, float64, complex64     8
complex128                           16
6391
</pre>
6392

6393
<p>
6394
The following minimal alignment properties are guaranteed:
Rob Pike's avatar
Rob Pike committed
6395
</p>
6396
<ol>
6397
<li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1.
6398
</li>
6399

6400
<li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of
6401
   all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1.
6402
</li>
6403

6404 6405
<li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as
   <code>unsafe.Alignof(x[0])</code>, but at least 1.
6406
</li>
6407
</ol>
6408

6409 6410 6411
<p>
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.
</p>