go_spec.html 121 KB
Newer Older
1 2


3
<!--
4
Open issues:
5 6
[ ] Semantics of type declaration:
	- creating a new type (status quo), or only a new type name?
7 8
	- declaration "type T S" strips methods of S. why/why not?
	- no mechanism to declare a local type name: type T P.T
9 10

Todo's:
Robert Griesemer's avatar
Robert Griesemer committed
11
[ ] document illegality of package-external tuple assignments to structs
12
	w/ private fields: P.T(1, 2) illegal since same as P.T(a: 1, b: 2) for
Robert Griesemer's avatar
Robert Griesemer committed
13
	a T struct { a b int }.
14 15
[ ] should probably write something about evaluation order of statements even
	though obvious
16
[ ] document T.m mechanism to obtain a function from a method
17 18
-->

19

20
<h2>Introduction</h2>
21

22
<p>
Rob Pike's avatar
Rob Pike committed
23 24 25 26
This is a reference manual for the Go programming language. For
more information and other documents, see <a
href="/">the Go home page</a>.
</p>
27

28
<p>
Rob Pike's avatar
Rob Pike committed
29 30 31 32 33 34 35
Go is a general-purpose language designed with systems programming
in mind. It is strongly typed and garbage-collected, and has explicit
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>
36

37
<p>
Rob Pike's avatar
Rob Pike committed
38 39 40
The grammar is compact and regular, allowing for easy analysis by
automatic tools such as integrated development environments.
</p>
Rob Pike's avatar
Rob Pike committed
41
<hr/>
42
<h2>Notation</h2>
Rob Pike's avatar
Rob Pike committed
43
<p>
44
The syntax is specified using Extended Backus-Naur Form (EBNF):
Rob Pike's avatar
Rob Pike committed
45
</p>
46

Rob Pike's avatar
Rob Pike committed
47
<pre class="grammar">
Robert Griesemer's avatar
Robert Griesemer committed
48
Production  = production_name "=" Expression "." .
Rob Pike's avatar
Rob Pike committed
49
Expression  = Alternative { "|" Alternative } .
50
Alternative = Term { Term } .
Rob Pike's avatar
Rob Pike committed
51 52
Term        = production_name | token [ "..." token ] | Group | Option | Repetition .
Group       = "(" Expression ")" .
53
Option      = "[" Expression "]" .
Rob Pike's avatar
Rob Pike committed
54
Repetition  = "{" Expression "}" .
55
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
56

Rob Pike's avatar
Rob Pike committed
57 58 59 60
<p>
Productions are expressions constructed from terms and the following
operators, in increasing precedence:
</p>
Rob Pike's avatar
Rob Pike committed
61
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
62 63 64 65
|   alternation
()  grouping
[]  option (0 or 1 times)
{}  repetition (0 to n times)
66
</pre>
67

68
<p>
Rob Pike's avatar
Rob Pike committed
69 70
Lower-case production names are used to identify lexical tokens.
Non-terminals are in CamelCase. Lexical symbols are enclosed in
71 72
double quotes <code>""</code> (the double quote symbol is written as
<code>'"'</code>).
Rob Pike's avatar
Rob Pike committed
73 74
</p>

75
<p>
76 77
The form <code>"a ... b"</code> represents the set of characters from
<code>a</code> through <code>b</code> as alternatives.
Rob Pike's avatar
Rob Pike committed
78 79
</p>

Rob Pike's avatar
Rob Pike committed
80
<hr/>
Robert Griesemer's avatar
Robert Griesemer committed
81

82
<h2>Source code representation</h2>
83

84
<p>
Rob Pike's avatar
Rob Pike committed
85 86 87 88 89 90
Source code is Unicode text encoded in UTF-8. The text is not
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
will use the term <i>character</i> to refer to a Unicode code point.
</p>
91
<p>
Rob Pike's avatar
Rob Pike committed
92 93 94
Each code point is distinct; for instance, upper and lower case letters
are different characters.
</p>
95

96
<h3>Characters</h3>
97

98
<p>
Rob Pike's avatar
Rob Pike committed
99 100
The following terms are used to denote specific Unicode character classes:
</p>
101
<ul>
Rob Pike's avatar
Rob Pike committed
102 103 104 105
	<li>unicode_char      an arbitrary Unicode code point</li>
	<li>unicode_letter    a Unicode code point classified as "Letter"</li>
	<li>capital_letter    a Unicode code point classified as "Letter, uppercase"</li>
	<li>unicode_digit     a Unicode code point classified as "Digit"</li>
106
</ul>
107

108
(The Unicode Standard, Section 4.5 General Category - Normative.)
109

110
<h3>Letters and digits</h3>
Rob Pike's avatar
Rob Pike committed
111 112

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

<h2>Lexical elements</h2>
124

Rob Pike's avatar
Rob Pike committed
125
<h3>Comments</h3>
126

Rob Pike's avatar
Rob Pike committed
127 128
<p>
There are two forms of comments.  The first starts at the character
129 130 131
sequence <code>//</code> and continues through the next newline.  The
second starts at the character sequence <code>/*</code> and continues
through the character sequence <code>*/</code>.  Comments do not nest.
Rob Pike's avatar
Rob Pike committed
132 133 134
</p>

<h3>Tokens</h3>
135

Rob Pike's avatar
Rob Pike committed
136 137 138 139 140 141 142 143 144 145
<p>
Tokens form the vocabulary of the Go language.
There are four classes: identifiers, keywords, operators
and delimiters, and literals.  <i>White space</i>, formed from
blanks, tabs, and newlines, is ignored except as it separates tokens
that would otherwise combine into a single token.  Comments
behave as white space.  While breaking the input into tokens,
the next token is the longest sequence of characters that form a
valid token.
</p>
146

147
<h3>Identifiers</h3>
148

Rob Pike's avatar
Rob Pike committed
149 150 151 152 153 154 155
<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>
<pre class="grammar">
identifier    = letter { letter | unicode_digit } .
156 157 158 159 160 161 162
</pre>
<pre>
a
_x9
ThisVariableIsExported
αβ
</pre>
163
Some identifiers are predeclared (§Predeclared identifiers).
164

Rob Pike's avatar
Rob Pike committed
165
<h3>Keywords</h3>
166

Rob Pike's avatar
Rob Pike committed
167 168 169 170 171 172 173 174 175 176
<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>
177

Rob Pike's avatar
Rob Pike committed
178 179 180 181 182 183 184 185 186 187 188
<h3>Operators and Delimiters</h3>

<p>
The following character sequences represent operators, delimiters, and other special tokens:
</p>
<pre class="grammar">
+    &amp;     +=    &amp;=     &amp;&amp;    ==    !=    (    )
-    |     -=    |=     ||    &lt;     &lt;=    [    ]
*    ^     *=    ^=     &lt;-    &gt;     &gt;=    {    }
/    <<    /=    <<=    ++    =     :=    ,    ;
%    >>    %=    >>=    --    !     ...   .    :
Rob Pike's avatar
Rob Pike committed
189
     &amp;^          &amp;^=
Rob Pike's avatar
Rob Pike committed
190 191 192 193 194 195 196
</pre>

<h3>Integer literals</h3>

<p>
An integer literal is a sequence of one or more digits in the
corresponding base, which may be 8, 10, or 16.  An optional prefix
197 198 199
sets a non-decimal base: <code>0</code> for octal, <code>0x</code> or
<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
200 201 202 203 204 205
</p>
<pre class="grammar">
int_lit       = decimal_lit | octal_lit | hex_lit .
decimal_lit   = ( "1" ... "9" ) { decimal_digit } .
octal_lit     = "0" { octal_digit } .
hex_lit       = "0" ( "x" | "X" ) hex_digit { hex_digit } .
206 207 208 209 210 211 212 213
</pre>

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

Rob Pike's avatar
Rob Pike committed
215 216 217 218 219
<h3>Floating-point literals</h3>
<p>
A floating-point literal is a decimal representation of a floating-point
number.  It has an integer part, a decimal point, a fractional part,
and an exponent part.  The integer and fractional part comprise
220
decimal digits; the exponent part is an <code>e</code> or <code>E</code>
Rob Pike's avatar
Rob Pike committed
221 222 223 224 225 226 227 228
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>
<pre class="grammar">
float_lit    = decimals "." [ decimals ] [ exponent ] |
               decimals exponent |
               "." decimals [ exponent ] .
229 230 231 232 233 234 235 236 237 238 239 240 241
decimals = decimal_digit { decimal_digit } .
exponent = ( "e" | "E" ) [ "+" | "-" ] decimals .
</pre>

<pre>
0.
2.71828
1.e+0
6.67428e-11
1E6
.25
.12345E+5
</pre>
242

Rob Pike's avatar
Rob Pike committed
243 244
<h3>Ideal numbers</h3>

245
<p>
Rob Pike's avatar
Rob Pike committed
246 247 248
Integer literals represent values of arbitrary precision, or <i>ideal
integers</i>.  Similarly, floating-point literals represent values
of arbitrary precision, or <i>ideal floats</i>.  These <i>ideal
249
numbers</i> have no size or named type and cannot overflow.  However,
Rob Pike's avatar
Rob Pike committed
250 251 252
when (used in an expression) assigned to a variable or typed constant,
the destination must be able to represent the assigned value.
</p>
253
<p>
254
Implementation restriction: A compiler may implement ideal numbers
Rob Pike's avatar
Rob Pike committed
255 256
by choosing an internal representation with at least twice the precision
of any machine type.
Rob Pike's avatar
Rob Pike committed
257
</p>
258

Rob Pike's avatar
Rob Pike committed
259
<h3>Character literals</h3>
260

Rob Pike's avatar
Rob Pike committed
261
<p>
Rob Pike's avatar
Rob Pike committed
262 263 264 265 266 267
A character literal represents an integer value, typically a
Unicode code point, as one or more characters enclosed in single
quotes.  Within the quotes, any character may appear except single
quote and newline. A single quoted character represents itself,
while multi-character sequences beginning with a backslash encode
values in various formats.
Rob Pike's avatar
Rob Pike committed
268
</p>
269
<p>
Rob Pike's avatar
Rob Pike committed
270 271 272
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
273 274 275 276
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
277
</p>
278
<p>
Rob Pike's avatar
Rob Pike committed
279 280
Several backslash escapes allow arbitrary values to be represented
as ASCII text.  There are four ways to represent the integer value
281 282 283 284
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
285 286 287
In each case the value of the literal is the value represented by
the digits in the corresponding base.
</p>
288
<p>
Rob Pike's avatar
Rob Pike committed
289 290 291
Although these representations all result in an integer, they have
different valid ranges.  Octal escapes must represent a value between
0 and 255 inclusive.  (Hexadecimal escapes satisfy this condition
292
by construction). The `Unicode' escapes <code>\u</code> and <code>\U</code>
Rob Pike's avatar
Rob Pike committed
293
represent Unicode code points so within them some values are illegal,
294
in particular those above <code>0x10FFFF</code> and surrogate halves.
Rob Pike's avatar
Rob Pike committed
295
</p>
296
<p>
Rob Pike's avatar
Rob Pike committed
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
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
\'   U+0027 single quote  (valid escape only within character literals)
\"   U+0022 double quote  (valid escape only within string literals)
</pre>
<p>
All other sequences are illegal inside character literals.
</p>
<pre class="grammar">
char_lit         = "'" ( unicode_value | byte_value ) "'" .
unicode_value    = unicode_char | little_u_value | big_u_value | escaped_char .
byte_value       = octal_byte_value | hex_byte_value .
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
                           hex_digit hex_digit hex_digit hex_digit .
escaped_char     = "\" ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | "\" | "'" | """ ) .
</pre>
325 326 327 328 329 330 331 332 333 334 335 336 337
<pre>
'a'
'ä'
'本'
'\t'
'\000'
'\007'
'\377'
'\x07'
'\xff'
'\u12e4'
'\U00101234'
</pre>
338

Rob Pike's avatar
Rob Pike committed
339 340 341 342
<p>
The value of a character literal is an ideal integer, just as with
integer literals.
</p>
343

Rob Pike's avatar
Rob Pike committed
344 345 346
<h3>String literals</h3>

<p>
347 348 349
String literals represent <i>ideal string</i> values. Ideal strings don't
have a named type but they are compatible with type <code>string</code>
(§Type identity and compatibility).
Rob Pike's avatar
Rob Pike committed
350 351 352 353 354
There are two forms: raw string literals and interpreted string
literals.
</p>
<p>
Raw string literals are character sequences between back quotes
355
<code>``</code>.  Within the quotes, any character is legal except
Rob Pike's avatar
Rob Pike committed
356 357 358 359 360 361
newline and back quote. The value of a raw string literal is the
string composed of the uninterpreted bytes between the quotes;
in particular, backslashes have no special meaning.
</p>
<p>
Interpreted string literals are character sequences between double
362
quotes <code>&quot;&quot;</code>. The text between the quotes forms the
Rob Pike's avatar
Rob Pike committed
363
value of the literal, with backslash escapes interpreted as they
364 365 366
are in character literals (except that <code>\'</code> is illegal and
<code>\"</code> is legal).  The three-digit octal (<code>\000</code>)
and two-digit hexadecimal (<code>\x00</code>) escapes represent individual
Rob Pike's avatar
Rob Pike committed
367 368
<i>bytes</i> of the resulting string; all other escapes represent
the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
369 370 371 372
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
the two bytes <code>0xc3 0xbf</code> of the UTF-8 encoding of character
Rob Pike's avatar
Rob Pike committed
373 374 375 376 377 378
U+00FF.
</p>

<pre class="grammar">
string_lit             = raw_string_lit | interpreted_string_lit .
raw_string_lit         = "`" { unicode_char } "`" .
379 380
interpreted_string_lit = """ { unicode_value | byte_value } """ .
</pre>
381

382 383 384 385 386 387 388 389 390 391 392
<pre>
`abc`
`\n`
"hello, world\n"
"\n"
""
"Hello, world!\n"
"日本語"
"\u65e5本\U00008a9e"
"\xff\u00FF"
</pre>
393

Rob Pike's avatar
Rob Pike committed
394
<p>
395
These examples all represent the same string:
Rob Pike's avatar
Rob Pike committed
396
</p>
397

398
<pre>
Rob Pike's avatar
Rob Pike committed
399 400 401 402
"日本語"                                 // UTF-8 input text
`日本語`                                 // UTF-8 input text as a raw literal
"\u65e5\u672c\u8a9e"                    // The explicit Unicode code points
"\U000065e5\U0000672c\U00008a9e"        // The explicit Unicode code points
403 404
"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"  // The explicit UTF-8 bytes
</pre>
405

406
<p>
407 408 409 410 411
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
an error if placed in a character literal (it is not a single code
point), and will appear as two code points if placed in a string
literal.
Rob Pike's avatar
Rob Pike committed
412 413
</p>
<hr/>
414

415
<h2>Types</h2>
416

417
<p>
Robert Griesemer's avatar
Robert Griesemer committed
418 419 420 421
A type determines the set of values and operations specific to values of that
type.  A type may be specified by a (possibly qualified) <i>type name</i>
(§Qualified identifier, §Type declarations) or a <i>type literal</i>,
which composes a new type from previously declared types.
Rob Pike's avatar
Rob Pike committed
422
</p>
423

Rob Pike's avatar
Rob Pike committed
424
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
425 426 427 428
Type      = TypeName | TypeLit | "(" Type ")" .
TypeName  = QualifiedIdent.
TypeLit   = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
	    SliceType | MapType | ChannelType .
429
</pre>
430

431
<p>
Rob Pike's avatar
Rob Pike committed
432 433 434
<i>Basic types</i> such as <code>int</code> are predeclared (§Predeclared identifiers).
Other types may be constructed from these, recursively,
including arrays, structs, pointers, functions, interfaces, slices, maps, and
435
channels.
Rob Pike's avatar
Rob Pike committed
436
</p>
437

438
<p>
Rob Pike's avatar
Rob Pike committed
439
At any point in the source code, a type may be <i>complete</i> or
Rob Pike's avatar
Rob Pike committed
440 441 442 443 444 445
<i>incomplete</i>.  An incomplete type is one whose size is not
yet known, such as a struct whose fields are not yet fully
defined or a forward declared type (§Forward declarations).
Most types are always complete; for instance, a pointer
type is always complete even if it points to an incomplete type
because the size of the pointer itself is always known.
Russ Cox's avatar
Russ Cox committed
446 447
(TODO: Need to figure out how forward declarations of
interface fit in here.)
Rob Pike's avatar
Rob Pike committed
448 449
</p>
<p>
Robert Griesemer's avatar
Robert Griesemer committed
450 451 452 453 454 455 456 457 458 459
A type may have a method set associated with it
(§Interface types, §Method declarations).
The method set of an interface type (§Interface types) is its interface.
The method set of any other named type <code>T</code>
consists of all methods with receiver
type <code>T</code>.
The method set of the corresponding pointer type <code>*T</code>
is the set of all methods with receiver <code>*T</code> or <code>T</code>
(that is, it also contains the method set of <code>T</code>).
Any other type has an empty method set.
Rob Pike's avatar
Rob Pike committed
460 461 462 463 464 465 466
</p>
<p>
The <i>static type</i> (or just <i>type</i>) of a variable is the
type defined by its declaration.  Variables of interface type
(§Interface types) also have a distinct <i>dynamic type</i>, which
is the actual type of the value stored in the variable at run-time.
The dynamic type may vary during execution but is always compatible
Robert Griesemer's avatar
Robert Griesemer committed
467
with the static type of the interface variable.  For non-interface
Rob Pike's avatar
Rob Pike committed
468 469
types, the dynamic type is always the static type.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
470

471
<h3>Basic types</h3>
472

Rob Pike's avatar
Rob Pike committed
473
<p>
474
Basic types include traditional numeric types, booleans, and strings. All are predeclared.
Rob Pike's avatar
Rob Pike committed
475
</p>
476

477
<h3>Numeric types</h3>
478

Rob Pike's avatar
Rob Pike committed
479 480 481
<p>
The architecture-independent numeric types are:
</p>
482

Rob Pike's avatar
Rob Pike committed
483
<pre class="grammar">
484 485 486 487
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)
488

489 490 491 492
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)
493

494 495
float32  the set of all valid IEEE-754 32-bit floating point numbers
float64  the set of all valid IEEE-754 64-bit floating point numbers
Rob Pike's avatar
Rob Pike committed
496 497

byte     familiar alias for uint8
498
</pre>
499

Rob Pike's avatar
Rob Pike committed
500
<p>
501 502 503
Integer types are represented in the usual binary format; the value of
an n-bit integer is n bits wide. A negative signed integer is represented
as the two's complement of its absolute value.
Rob Pike's avatar
Rob Pike committed
504
</p>
505

Rob Pike's avatar
Rob Pike committed
506 507 508 509
<p>
There is also a set of architecture-independent basic numeric types
whose size depends on the architecture:
</p>
510

511 512 513 514 515 516 517
<pre class="grammar">
uint     at least 32 bits, at most the size of the largest uint type
int      at least 32 bits, at most the size of the largest int type
float    at least 32 bits, at most the size of the largest float type
uintptr  smallest uint type large enough to store the uninterpreted
		 bits of a pointer value
</pre>
518

519
<p>
520 521 522
To avoid portability issues all numeric types are distinct except
<code>byte</code>, which is an alias for <code>uint8</code>.
Conversions
523
are required when incompatible numeric types are mixed in an expression
Rob Pike's avatar
Rob Pike committed
524
or assignment. For instance, <code>int32</code> and <code>int</code>
525
are not the same type even though they may have the same size on a
Rob Pike's avatar
Rob Pike committed
526
particular architecture.
527

528

529
<h3>Booleans</h3>
530

Rob Pike's avatar
Rob Pike committed
531 532 533
The type <code>bool</code> comprises the Boolean truth values
represented by the predeclared constants <code>true</code>
and <code>false</code>.
534

535

536
<h3>Strings</h3>
537

538
<p>
539
The <code>string</code> type represents the set of string values.
Rob Pike's avatar
Rob Pike committed
540 541 542 543 544 545 546 547 548 549
Strings behave like arrays of bytes but are immutable: once created,
it is impossible to change the contents of a string.

<p>
The elements of strings have type <code>byte</code> and may be
accessed using the usual indexing operations (§Indexes).  It is
illegal to take the address of such an element, that is, even if
<code>s[i]</code> is the <code>i</code><sup>th</sup> byte of a
string, <code>&amp;s[i]</code> is invalid.  The length of a string
can be computed by the function <code>len(s1)</code>.
550
</p>
551

Rob Pike's avatar
Rob Pike committed
552
<p>
Rob Pike's avatar
Rob Pike committed
553
A sequence of string literals is concatenated into a single string.
Rob Pike's avatar
Rob Pike committed
554 555
</p>
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
556
StringLit   = string_lit { string_lit } .
Rob Pike's avatar
Rob Pike committed
557
</pre>
558

559
<pre>
Rob Pike's avatar
Rob Pike committed
560 561
"Alea iacta est."
"Alea " /* The die */ `iacta est` /* is cast */ "."
562
</pre>
563

Russ Cox's avatar
Russ Cox committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
<h3>Array types</h3>

<p>
An array is a numbered sequence of elements of a single
type, called the element type, which must be complete
(§Types). The number of elements is called the length and is never
negative.
</p>

<pre class="grammar">
ArrayType   = "[" ArrayLength "]" ElementType .
ArrayLength = Expression .
ElementType = CompleteType .
</pre>

<p>
The length is part of the array's type and must must be a constant
expression (§Constant expressions) that evaluates to a non-negative
integer value.  The length of array <code>a</code> can be discovered
using the built-in function <code>len(a)</code>, which is a
compile-time constant.  The elements can be indexed by integer
indices 0 through the <code>len(a)-1</code> (§Indexes).
</p>

<pre>
[32]byte
[2*N] struct { x, y int32 }
[1000]*float64
</pre>

<h3>Slice types</h3>

<p>
A slice is a reference to a contiguous segment of an array and
contains a numbered sequence of elements from that array.  A slice
type denotes the set of all slices of arrays of its element type.
A slice value may be <code>nil</code>.
</p>

<pre class="grammar">
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
<code>len(s)</code>; unlike with arrays it may change during
execution.  The elements can be addressed by integer indices 0
through <code>len(s)-1</code> (§Indexes).  The slice index of a
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
array that holds its elements.  A slice therfore shares storage
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.
624
The <i>capacity</i> is a measure of that extent: it is the sum of
Russ Cox's avatar
Russ Cox committed
625 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
the length of the slice and the length of the array beyond the slice;
a slice of length up to that capacity can be created by `slicing' a new
one from the original slice (§Slices).
The capacity of a slice <code>a</code> can be discovered using the
built-in function
</p>

<pre>
cap(s)
</pre>

<p>
and the relationship between <code>len()</code> and <code>cap()</code> is:
</p>

<pre>
0 <= len(a) <= cap(a)
</pre>

<p>
The value of an uninitialized slice is <code>nil</code>.
The length and capacity of a <code>nil</code> slice
are 0. A new, initialized slice value for a given element type <code>T</code> is
made using the built-in function <code>make</code>, which takes a slice type
and parameters specifying the length and optionally the capacity:
</p>

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

Russ Cox's avatar
Russ Cox committed
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
<p>
The <code>make()</code> call allocates a new, hidden array to which the returned
slice value refers. That is, calling <code>make</code>
</p>

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

<p>
produces the same slice as allocating an array and slicing it, so these two examples
result in the same slice:
</p>

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


677
<h3>Struct types</h3>
678

Rob Pike's avatar
Rob Pike committed
679 680 681
<p>
A struct is a sequence of named
elements, called fields, with various types. A struct type declares
682
an identifier and type for each field. Within a struct, field identifiers
Rob Pike's avatar
Rob Pike committed
683 684
must be unique and  field types must be complete (§Types).
</p>
685

Rob Pike's avatar
Rob Pike committed
686
<pre class="grammar">
Russ Cox's avatar
Russ Cox committed
687
StructType = "struct" "{" [ FieldDeclList ] "}" .
688 689 690
FieldDeclList = FieldDecl { ";" FieldDecl } [ ";" ] .
FieldDecl = (IdentifierList CompleteType | [ "*" ] TypeName) [ Tag ] .
Tag = StringLit .
691
</pre>
692

693
<pre>
694 695
// An empty struct.
struct {}
696

697 698 699 700 701 702
// A struct with 5 fields.
struct {
	x, y int;
	u float;
	A *[]int;
	F func();
703 704
}
</pre>
705

Rob Pike's avatar
Rob Pike committed
706 707 708
<p>
A field declared with a type but no field identifier is an <i>anonymous field</i>.
Such a field type must be specified as
709 710
a type name <code>T</code> or as a pointer to a type name <code>*T</code>,
and <code>T</code> itself, may not be
711
a pointer or interface type. The unqualified type name acts as the field identifier.
Rob Pike's avatar
Rob Pike committed
712
</p>
713

714 715 716 717 718
<pre>
// A struct with four anonymous fields of type T1, *T2, P.T3 and *P.T4
struct {
	T1;        // the field name is T1
	*T2;       // the field name is T2
719 720
	P.T3;      // the field name is T3
	*P.T4;     // the field name is T4
721
	x, y int;
722
}
723 724
</pre>

Rob Pike's avatar
Rob Pike committed
725
<p>
726 727 728
The unqualified type name of an anonymous field must not conflict with the
field identifier (or unqualified type name for an anonymous field) of any
other field within the struct. The following declaration is illegal:
Rob Pike's avatar
Rob Pike committed
729
</p>
730

731
<pre>
732 733 734 735 736
struct {
	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
}
737
</pre>
738

739
<p>
Rob Pike's avatar
Rob Pike committed
740 741
Fields and methods (§Method declarations) of an anonymous field are
promoted to be ordinary fields and methods of the struct (§Selectors).
Robert Griesemer's avatar
Robert Griesemer committed
742 743
The following rules apply for a struct type named <code>S</code> and
a type named <code>T</code>:
Rob Pike's avatar
Rob Pike committed
744
</p>
Robert Griesemer's avatar
Robert Griesemer committed
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
<ul>
	<li>If <code>S</code> contains an anonymous field <code>T</code>, the
	    method set of <code>S</code> includes the method set of <code>T</code>.
	</li>

	<li>If <code>S</code> contains an anonymous field <code>*T</code>, the
	    method set of <code>S</code> includes the method set of <code>*T</code>
	    (which itself includes the method set of <code>T</code>).
	</li>

	<li>If <code>S</code> contains an anonymous field <code>T</code> or
	    <code>*T</code>, the method set of <code>*S</code> includes the
	    method set of <code>*T</code> (which itself includes the method
	    set of <code>T</code>).
	</li>
</ul>
Rob Pike's avatar
Rob Pike committed
761
<p>
Robert Griesemer's avatar
Robert Griesemer committed
762 763
A field declaration may be followed by an optional string literal <i>tag</i>,
which becomes an attribute for all the identifiers in the corresponding
Rob Pike's avatar
Rob Pike committed
764 765 766 767
field declaration. The tags are made
visible through a reflection library (TODO: reference?)
but are otherwise ignored.
</p>
768

769
<pre>
770
// A struct corresponding to the EventIdMessage protocol buffer.
Rob Pike's avatar
Rob Pike committed
771
// The tag strings define the protocol buffer field numbers.
772
struct {
Rob Pike's avatar
Rob Pike committed
773 774 775
	time_usec uint64 "field 1";
	server_ip uint32 "field 2";
	process_id uint32 "field 3";
776
}
777
</pre>
778

779
<h3>Pointer types</h3>
780

Rob Pike's avatar
Rob Pike committed
781
<p>
782
A pointer type denotes the set of all pointers to variables of a given
783
type, called the <i>base type</i> of the pointer.
Rob Pike's avatar
Rob Pike committed
784
A pointer value may be <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
785
</p>
786

Rob Pike's avatar
Rob Pike committed
787
<pre class="grammar">
788 789
PointerType = "*" BaseType .
BaseType = Type .
790
</pre>
791

792
<pre>
793
*int
Rob Pike's avatar
Rob Pike committed
794
*map[string] *chan int
795
</pre>
796

797
<h3>Function types</h3>
798

Rob Pike's avatar
Rob Pike committed
799
<p>
800
A function type denotes the set of all functions with the same parameter
Rob Pike's avatar
Rob Pike committed
801 802 803
and result types.
A function value may be <code>nil</code>.
</p>
804 805

<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
806 807 808 809 810 811
FunctionType   = "func" Signature .
Signature      = Parameters [ Result ] .
Result         = Parameters | CompleteType .
Parameters     = "(" [ ParameterList ] ")" .
ParameterList  = ParameterDecl { "," ParameterDecl } .
ParameterDecl  = [ IdentifierList ] ( CompleteType | "..." ) .
812 813 814
</pre>

<p>
Rob Pike's avatar
Rob Pike committed
815 816 817 818 819 820 821 822 823 824 825 826
Within a list of parameters or results, the names (IdentifierList)
must either all be present or all be absent. If present, each name
stands for one item (parameter or result) of the specified type; if absent, each
type stands for one item of that type.  Parameter and result
lists are always parenthesized except that if there is exactly
one unnamed result that is not a function type it may writen as an unparenthesized type.
The types of parameters and results must be complete.
(TODO: is completeness necessary?)
</p>
<p>
For the last parameter only, instead of a type one may write
<code>...</code> to indicate that the function may be invoked with
827
zero or more additional arguments of any
Rob Pike's avatar
Rob Pike committed
828 829 830
type. If parameters of such a function are named, the final identifier
list must be a single name, that of the <code>...</code> parameter.
</p>
831 832

<pre>
833 834 835 836 837 838 839 840 841
func ()
func (x int)
func () int
func (string, float, ...)
func (a, b int, z float) bool
func (a, b int, z float) (bool)
func (a, b int, z float, opt ...) (success bool)
func (int, int, float) (float, *[]int)
func (n int) (func (p* T))
842 843 844
</pre>


845
<h3>Interface types</h3>
846

Rob Pike's avatar
Rob Pike committed
847
<p>
Robert Griesemer's avatar
Robert Griesemer committed
848 849 850 851
An interface type specifies a method set called its <i>interface</i>.
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
<i>implement the interface</i>. An interface value may be <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
852
</p>
853 854

<pre class="grammar">
Russ Cox's avatar
Russ Cox committed
855
InterfaceType      = "interface" "{" [ MethodSpecList ] "}" .
Rob Pike's avatar
Rob Pike committed
856 857 858
MethodSpecList     = MethodSpec { ";" MethodSpec } [ ";" ] .
MethodSpec         = IdentifierList Signature | InterfaceTypeName .
InterfaceTypeName  = TypeName .
859
</pre>
860 861

<pre>
Rob Pike's avatar
Rob Pike committed
862
// A simple File interface
863 864 865
interface {
	Read, Write	(b Buffer) bool;
	Close		();
866 867
}
</pre>
868

Rob Pike's avatar
Rob Pike committed
869
<p>
Robert Griesemer's avatar
Robert Griesemer committed
870
More than one type may implement an interface.
Rob Pike's avatar
Rob Pike committed
871
For instance, if two types <code>S1</code> and <code>S2</code>
Robert Griesemer's avatar
Robert Griesemer committed
872
have the method set
Rob Pike's avatar
Rob Pike committed
873
</p>
874

875
<pre>
876 877 878
func (p T) Read(b Buffer) bool { return ... }
func (p T) Write(b Buffer) bool { return ... }
func (p T) Close() { ... }
879
</pre>
880

Rob Pike's avatar
Rob Pike committed
881 882 883 884 885 886
<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>
887

Rob Pike's avatar
Rob Pike committed
888 889 890 891 892
<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>
893

894
<pre>
Rob Pike's avatar
Rob Pike committed
895
interface { }
896
</pre>
897

Rob Pike's avatar
Rob Pike committed
898 899 900 901 902
<p>
Similarly, consider this interface specification,
which appears within a type declaration (§Type declarations)
to define an interface called <code>Lock</code>:
</p>
903 904 905 906 907

<pre>
type Lock interface {
	Lock, Unlock	();
}
908
</pre>
909

Rob Pike's avatar
Rob Pike committed
910 911 912
<p>
If <code>S1</code> and <code>S2</code> also implement
</p>
Robert Griesemer's avatar
Robert Griesemer committed
913

914 915 916 917 918
<pre>
func (p T) Lock() { ... }
func (p T) Unlock() { ... }
</pre>

919
<p>
Rob Pike's avatar
Rob Pike committed
920 921 922 923 924 925 926 927 928 929
they implement the <code>Lock</code> interface as well
as the <code>File</code> interface.
</p>
<p>
An interface may contain an interface type name <code>T</code>
in place of a method specification.
In this notation, <code>T</code> must denote a different, complete interface type
and the effect is equivalent to enumerating the methods of <code>T</code> explicitly
in the interface.
</p>
930

931 932 933 934
<pre>
type ReadWrite interface {
	Read, Write	(b Buffer) bool;
}
935

936 937 938 939 940 941
type File interface {
	ReadWrite;  // same as enumerating the methods in ReadWrite
	Lock;       // same as enumerating the methods in Lock
	Close();
}
</pre>
942

943
<h3>Map types</h3>
944

Rob Pike's avatar
Rob Pike committed
945 946 947 948 949 950 951 952 953
<p>
A map is an unordered group of elements of one type, called the
value type, indexed by a set of unique <i>keys</i> of another type,
called the key type.  Both key and value types must be complete.
(§Types).
(TODO: is completeness necessary here?)
A map value may be <code>nil</code>.

</p>
954

Rob Pike's avatar
Rob Pike committed
955
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
956 957 958
MapType     = "map" "[" KeyType "]" ValueType .
KeyType     = CompleteType .
ValueType   = CompleteType .
959
</pre>
960

961
<p>
Rob Pike's avatar
Rob Pike committed
962 963 964 965 966 967 968 969
The comparison operators <code>==</code> and <code>!=</code>
(§Comparison operators) must be fully defined for operands of the
key type; thus the key type must be a basic, pointer, interface,
map, or channel type. If the key type is an interface type, these
comparison operators must be defined for the dynamic key values;
failure will cause a run-time error.

</p>
970

971
<pre>
972 973 974
map [string] int
map [*T] struct { x, y float }
map [string] interface {}
975
</pre>
976

Rob Pike's avatar
Rob Pike committed
977 978 979 980
<p>
The number of elements is called the length and is never negative.
The length of a map <code>m</code> can be discovered using the
built-in function <code>len(m)</code> and may change during execution.
981
The value of an uninitialized map is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
982 983 984 985 986 987
</p>
<p>
Upon creation, a map is empty.  Values may be added and removed
during execution using special forms of assignment (§Assignments).
A new, empty map value is made using the built-in
function <code>make</code>, which takes the map type and an optional
988
capacity hint as arguments:
Rob Pike's avatar
Rob Pike committed
989
</p>
990

991
<pre>
992 993
make(map[string] int)
make(map[string] int, 100)
994
</pre>
995

996 997 998 999 1000 1001
<p>
The initial capacity does not bound its size:
maps grow to accommodate the number of items
stored in them.
</p>

1002
<h3>Channel types</h3>
1003

Rob Pike's avatar
Rob Pike committed
1004
<p>
1005
A channel provides a mechanism for two concurrently executing functions
Rob Pike's avatar
Rob Pike committed
1006 1007 1008 1009 1010
to synchronize execution and communicate by passing a value of a
specified element type. The element type must be complete (§Types).
(TODO: is completeness necessary here?)
A channel value may be <code>nil</code>.
</p>
1011

1012
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
1013 1014 1015 1016
ChannelType   = Channel | SendChannel | RecvChannel .
Channel       = "chan" ValueType .
SendChannel   = "chan" "&lt;-" ValueType .
RecvChannel   = "&lt;-" "chan" ValueType .
1017
</pre>
1018

Rob Pike's avatar
Rob Pike committed
1019 1020
<p>
Upon creation, a channel can be used both to send and to receive values.
1021
By conversion or assignment, a channel may be constrained only to send or
Rob Pike's avatar
Rob Pike committed
1022 1023 1024
to receive. This constraint is called a channel's <i>direction</i>; either
<i>send</i>, <i>receive</i>, or <i>bi-directional</i> (unconstrained).
</p>
1025

1026
<pre>
Rob Pike's avatar
Rob Pike committed
1027
chan T         // can be used to send and receive values of type T
1028
chan &lt;- float  // can only be used to send floats
Rob Pike's avatar
Rob Pike committed
1029
&lt;-chan int     // can only be used to receive ints
1030
</pre>
1031

Rob Pike's avatar
Rob Pike committed
1032 1033 1034
<p>
The value of an uninitialized channel is <code>nil</code>. A new, initialized channel
value is made using the built-in function <code>make</code>,
1035
which takes the channel type and an optional capacity as arguments:
Rob Pike's avatar
Rob Pike committed
1036
</p>
1037

1038

1039
<pre>
1040
make(chan int, 100)
1041
</pre>
1042

Rob Pike's avatar
Rob Pike committed
1043 1044
<p>
The capacity, in number of elements, sets the size of the buffer in the channel. If the
1045
capacity is greater than zero, the channel is asynchronous and, provided the
Rob Pike's avatar
Rob Pike committed
1046 1047 1048
buffer is not full, sends can succeed without blocking. If the capacity is zero
or absent, the communication succeeds only when both a sender and receiver are ready.
</p>
1049

1050 1051 1052 1053 1054 1055 1056 1057 1058
<p>
For a channel <code>c</code>, the predefined function <code>close(c)</code>
marks the channel as unable to accept more
values through a send operation.  After any previously
sent values have been received, receives will return
the zero value for the channel's type.  After at least one such zero value has been
received, <code>closed(c)</code> returns true.
</p>

Rob Pike's avatar
Rob Pike committed
1059
<h2>General properties of types and values</h2>
1060 1061

<p>
1062 1063 1064 1065 1066 1067 1068
Two types may be <i>identical</i>, <i>compatible</i>, or <i>incompatible</i>.
Two identical types are always compatible, but two compatible types may not be identical.
Go is <i>type safe</i>: a value of one type cannot be assigned to a variable of an
incompatible type, and two values of incompatible types cannot be mixed in
binary operations.</p>

<h3>Type identity and compatibility</h3>
Rob Pike's avatar
Rob Pike committed
1069

1070
<h4>Type identity</h4>
Rob Pike's avatar
Rob Pike committed
1071

1072
<p>
1073 1074 1075 1076 1077
Two named types are identical if their type names originate in the same
type declaration (§Declarations and Scope). A named and an unnamed type
are never identical. Two unnamed types are identical if the corresponding
type literals have the same literal structure and corresponding components have
identical types. In detail:
1078
</p>
Rob Pike's avatar
Rob Pike committed
1079

1080
<ul>
1081 1082
	<li>Two array types are identical if they have identical element types and
	    the same array length.</li>
1083

1084
	<li>Two slice types are identical if they have identical element types.</li>
1085

1086 1087
	<li>Two struct types are identical if they have the same sequence of fields,
	    and if corresponding fields have the same names and identical types.
Robert Griesemer's avatar
Robert Griesemer committed
1088
	    Two anonymous fields are considered to have the same name.</li>
1089

1090
	<li>Two pointer types are identical if they have identical base types.</li>
1091

1092 1093 1094 1095
	<li>Two function types are identical if they have the same number of parameters
	    and result values and if corresponding parameter and result types are
	    identical. All "..." parameters have identical type.
	    Parameter and result names are not required to match.</li>
1096

1097 1098 1099
	<li>Two interface types are identical if they have the same set of methods
	    with the same names and identical function types. The order
	    of the methods is irrelevant.</li>
1100

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

1103 1104
	<li>Two channel types are identical if they have identical value types and
	    the same direction.</li>
1105 1106
</ul>

1107 1108
<h4>Type compatibility</h4>

1109
<p>
1110 1111 1112 1113 1114
Type compatibility is less stringent than type identity: a named and an unnamed
type are compatible if the respective type literals are compatible.
In all other respects, the definition of type compatibility is the
same as for type identity listed above but with ``compatible''
substituted for ``identical''.
1115
</p>
1116

1117
<p>
Rob Pike's avatar
Rob Pike committed
1118 1119
Given the declarations
</p>
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129

<pre>
type (
	T0 []string;
	T1 []string
	T2 struct { a, b int };
	T3 struct { a, c int };
	T4 func (int, float) *T0
	T5 func (x int, y float) *[]string
)
1130
</pre>
1131

Rob Pike's avatar
Rob Pike committed
1132
<p>
1133
these types are identical:
Rob Pike's avatar
Rob Pike committed
1134
</p>
1135

1136
<pre>
1137
T0 and T0
1138 1139 1140
[]int and []int
struct { a, b *T5 } and struct { a, b *T5 }
func (x int, y float) *[]string and func (int, float) (result *[]string)
1141
</pre>
1142

Rob Pike's avatar
Rob Pike committed
1143
<p>
1144 1145
<code>T0</code> and <code>T1</code> are neither identical nor compatible
because they are named types with distinct declarations.
Russ Cox's avatar
Russ Cox committed
1146 1147 1148
</p>

<p>
1149
These types are compatible:
Rob Pike's avatar
Rob Pike committed
1150
</p>
1151

1152
<pre>
1153
T0 and T0
1154 1155 1156
T0 and []string
T3 and struct { a int; c int }
T4 and func (x int, y float) *[]string
1157
</pre>
1158

Rob Pike's avatar
Rob Pike committed
1159
<p>
1160 1161
<code>T2</code> and <code>struct { a, c int }</code> are incompatible because
they have different field names.
Rob Pike's avatar
Rob Pike committed
1162
</p>
1163

Rob Pike's avatar
Rob Pike committed
1164 1165 1166 1167
<h3>Assignment compatibility</h3>

<p>
Values of any type may always be assigned to variables
1168 1169
of compatible static type. Some types and values have conditions under which they may
be assigned to otherwise incompatible types:
Rob Pike's avatar
Rob Pike committed
1170 1171 1172 1173 1174 1175
</p>
<ul>
<li>
The predeclared constant <code>nil</code> can be assigned to any
pointer, function, slice, map, channel, or interface variable.
<li>
1176
A pointer to an array can be assigned to a slice variable with compatible element type.
Russ Cox's avatar
Russ Cox committed
1177
The slice variable then refers to the original array; the data is not copied.
Rob Pike's avatar
Rob Pike committed
1178 1179
</li>
<li>
1180
A value can be assigned to an interface variable if the static
Rob Pike's avatar
Rob Pike committed
1181 1182 1183 1184
type of the value implements the interface.
</li>
<li>
A value of bidirectional channel type can be assigned to any channel
1185
variable of compatible channel value type.
Rob Pike's avatar
Rob Pike committed
1186 1187 1188 1189 1190 1191
</li>
</ul>

<h3>Comparison compatibility</h3>

<p>
1192
Values of any type may be compared to other values of compatible static
Rob Pike's avatar
Rob Pike committed
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
type.  Values of numeric and string type may be compared using the
full range of comparison operators as described in §Comparison operators;
booleans may be compared only for equality or inequality.
</p>

<p>
Values of composite type may be
compared for equality or inequality using the <code>==</code> and
<code>!=</code> operators, with the following provisos:
</p>
<ul>
<li>
Arrays and structs may not be compared to anything.
</li>
<li>
1208 1209
A slice value may only be compared explicitly against <code>nil</code>.
A slice value is equal to <code>nil</code> if it has been assigned the explicit
Rob Pike's avatar
Rob Pike committed
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
value <code>nil</code> or if it is a variable (or array element,
field, etc.) that has not been modified since it was created
uninitialized.
</li>
<li>
Similarly, an interface value is equal to <code>nil</code> if it has
been assigned the explicit value <code>nil</code> or if it is a
variable (or array element, field, etc.) that has not been modified
since it was created uninitialized.
</li>
<li>
For types that can be compared to <code>nil</code>,
two values of the same type are equal if they both equal <code>nil</code>,
unequal if one equals <code>nil</code> and one does not.
</li>
<li>
Pointer values are equal if they point to the same location.
</li>
<li>
1229
Function values are equal if they refer to the same function.
Rob Pike's avatar
Rob Pike committed
1230 1231
</li>
<li>
1232
Channel and map values are equal if they were created by the same call to <code>make</code>
Rob Pike's avatar
Rob Pike committed
1233 1234 1235
(§Making slices, maps, and channels).
</li>
<li>
1236
Interface values may be compared if they have compatible static types.
1237
They will be equal only if they have the same dynamic type and the underlying values are equal.
Rob Pike's avatar
Rob Pike committed
1238 1239
</li>
</ul>
1240
<hr/>
1241 1242


1243 1244 1245 1246 1247 1248 1249
<h2>Declarations and Scope</h2>

<p>
A declaration binds an identifier to a language entity such as
a variable or function and specifies properties such as its type.
Every identifier in a program must be declared.
</p>
1250

Rob Pike's avatar
Rob Pike committed
1251
<pre class="grammar">
1252
Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
1253
</pre>
1254

1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
<p>
The <i>scope</i> of an identifier is the extent of source text within which the
identifier denotes the bound entity. No identifier may be declared twice in a
single scope, but inner blocks can declare a new entity with the same
identifier, in which case the scope created by the outer declaration excludes
that created by the inner.
</p>
<p>
There are levels of scoping in effect before each source file is compiled.
In order from outermost to innermost:
</p>
<ol>
	<li>The <i>universe</i> scope contains all predeclared identifiers.</li>
	<li>An implicit scope contains only the package name.</li>
	<li>The <i>package-level</i> scope surrounds all declarations at the
	    top level of the file, that is, outside the body of any
	    function or method.  That scope is shared across all
	    source files within the package (§Packages), allowing
	    package-level identifiers to be shared between source
	    files.</li>
</ol>
1276

1277 1278 1279
<p>
The scope of an identifier depends on the entity declared:
</p>
1280

1281 1282
<ol>
	<li> The scope of predeclared identifiers is the universe scope.</li>
1283

1284
	<li> The scope of an identifier denoting a type, function or package
1285 1286
	     extends from the point of the identifier in the declaration
	     to the end of the innermost surrounding block.</li>
1287

1288
	<li> The scope of a constant or variable extends textually from
1289
	     the end of its declaration to the end of the innermost
1290
	     surrounding block. If the variable is declared in the
1291
	     <i>init</i> statement of an <code>if</code>,  <code>for</code>,
1292 1293 1294
	     or  <code>switch </code> statement, the
	     innermost surrounding block is the block associated
	     with that statement.</li>
1295

1296 1297
	<li> The scope of a parameter or result is the body of the
	     corresponding function.</li>
1298

1299 1300
	<li> The scope of a field or method is selectors for the
	     corresponding type containing the field or method (§Selectors).</li>
1301

1302
	<li> The scope of a label is a special scope emcompassing
1303
	     the body of the innermost surrounding function, excluding
Rob Pike's avatar
Rob Pike committed
1304
	     nested functions.  Labels do not conflict with non-label identifiers.</li>
1305
</ol>
1306

1307
<h3>Predeclared identifiers</h3>
1308

1309 1310 1311 1312 1313
<p>
The following identifiers are implicitly declared in the outermost scope:
</p>
<pre class="grammar">
Basic types:
1314 1315
	bool byte float32 float64 int8 int16 int32 int64
	string uint8 uint16 uint32 uint64
1316

Rob Pike's avatar
Rob Pike committed
1317
Architecture-specific convenience types:
1318
	float int uint uintptr
1319

1320 1321
Constants:
	true false iota nil
1322

1323
Functions:
1324
	cap len make new panic panicln print println
1325

1326
Packages:
1327
	unsafe
1328
</pre>
1329

1330
<h3>Exported identifiers</h3>
Robert Griesemer's avatar
Robert Griesemer committed
1331

1332
<p>
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
By default, identifiers are visible only within the package in which they are declared.
Some identifiers are <i>exported</i> and can be referenced using
<i>qualified identifiers</i> in other packages (§Qualified identifiers).
If an identifier satisfies these two conditions:
</p>
<ol>
<li>the first character of the identifier's name is a Unicode upper case letter;
<li>the identifier is declared at the package level or is a field or method of a type
declared at the top level;
</ol>
1343
<p>
1344 1345
it will be exported automatically.
</p>
1346

1347
<h3>Const declarations</h3>
1348

1349 1350 1351 1352 1353 1354 1355 1356
<p>
A constant declaration binds a list of identifiers (the names of
the constants) to the values of a list of constant expressions
(§Constant expressions).  The number of identifiers must be equal
to the number of expressions, and the n<sup>th</sup> identifier on
the left is bound to value of the n<sup>th</sup> expression on the
right.
</p>
1357

Rob Pike's avatar
Rob Pike committed
1358
<pre class="grammar">
1359 1360
ConstDecl      = "const" ( ConstSpec | "(" [ ConstSpecList ] ")" ) .
ConstSpecList  = ConstSpec { ";" ConstSpec } [ ";" ] .
Russ Cox's avatar
Russ Cox committed
1361
ConstSpec      = IdentifierList [ [ CompleteType ] "=" ExpressionList ] .
1362

1363 1364
IdentifierList = identifier { "," identifier } .
ExpressionList = Expression { "," Expression } .
1365

1366
CompleteType = Type .
1367
</pre>
1368

1369 1370 1371
<p>
If the type (CompleteType) is omitted, the constants take the
individual types of the corresponding expressions, which may be
1372
<i>ideal integer</i> or <i>ideal float</i> (§Ideal number).  If the type
1373 1374 1375 1376
is present, all constants take the type specified, and the types
of all the expressions must be assignment-compatible
with that type.
</p>
1377

1378
<pre>
1379 1380 1381 1382 1383 1384 1385 1386
const Pi float64 = 3.14159265358979323846
const E = 2.718281828
const (
	size int64 = 1024;
	eof = -1;
)
const a, b, c = 3, 4, "foo"  // a = 3, b = 4, c = "foo"
const u, v float = 0, 3      // u = 0.0, v = 3.0
1387
</pre>
1388

1389 1390 1391 1392
<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
Russ Cox's avatar
Russ Cox committed
1393
first preceding non-empty expression list, and its type if any.
1394 1395 1396 1397
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.
Together with the <code>iota</code> constant generator
1398 1399
(§Iota) this mechanism permits light-weight declaration of sequential values:
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1400

1401
<pre>
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
const (
	Sunday = iota;
	Monday;
	Tuesday;
	Wednesday;
	Thursday;
	Friday;
	Partyday;
	numberOfDays;  // this constant is not exported
)
1412
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
1413 1414


1415
<h3>Iota</h3>
1416

1417
<p>
1418 1419 1420 1421 1422 1423
Within a constant declaration, the predeclared pseudo-constant
<code>iota</code> represents successive integers. It is reset to 0
whenever the reserved word <code>const</code> appears in the source
and increments with each semicolon. It can be used to construct a
set of related constants:
</p>
1424

1425
<pre>
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
const (            // iota is reset to 0
	c0 = iota;  // c0 == 0
	c1 = iota;  // c1 == 1
	c2 = iota   // c2 == 2
)

const (
	a = 1 << iota;  // a == 1 (iota has been reset)
	b = 1 << iota;  // b == 2
	c = 1 << iota;  // c == 4
)

const (
	u       = iota * 42;  // u == 0     (ideal integer)
	v float = iota * 42;  // v == 42.0  (float)
	w       = iota * 42;  // w == 84    (ideal integer)
)

const x = iota;  // x == 0 (iota has been reset)
const y = iota;  // y == 0 (iota has been reset)
1446
</pre>
1447

1448
<p>
1449 1450 1451
Within an ExpressionList, the value of each <code>iota</code> is the same because
it is only incremented at a semicolon:
</p>
1452

1453
<pre>
1454 1455 1456 1457 1458
const (
	bit0, mask0 = 1 << iota, 1 << iota - 1;  // bit0 == 1, mask0 == 0
	bit1, mask1;                             // bit1 == 2, mask1 == 1
	bit2, mask2;                             // bit2 == 4, mask2 == 3
)
1459
</pre>
1460

1461
<p>
1462 1463 1464
This last example exploits the implicit repetition of the
last non-empty expression list.
</p>
1465 1466


1467
<h3>Type declarations</h3>
1468

1469 1470 1471 1472
<p>
A type declaration binds an identifier, the <i>type name</i>,
to a new type.  <font color=red>TODO: what exactly is a "new type"?</font>
</p>
1473

Rob Pike's avatar
Rob Pike committed
1474
<pre class="grammar">
1475 1476
TypeDecl     = "type" ( TypeSpec | "(" [ TypeSpecList ] ")" ) .
TypeSpecList = TypeSpec { ";" TypeSpec } [ ";" ] .
Russ Cox's avatar
Russ Cox committed
1477
TypeSpec     = identifier ( Type | "struct" | "interface" ) .
1478
</pre>
1479

1480
<pre>
1481
type IntArray [16] int
1482

1483 1484 1485 1486
type (
	Point struct { x, y float };
	Polar Point
)
1487

Russ Cox's avatar
Russ Cox committed
1488 1489
type Comparable interface

1490 1491
type TreeNode struct {
	left, right *TreeNode;
Russ Cox's avatar
Russ Cox committed
1492
	value *Comparable;
1493 1494 1495 1496 1497
}

type Comparable interface {
	cmp(Comparable) int
}
1498
</pre>
1499

1500 1501 1502 1503 1504
<h3>Variable declarations</h3>

<p>
A variable declaration creates a variable, binds an identifier to it and
gives it a type and optionally an initial value.
Rob Pike's avatar
Rob Pike committed
1505
The type must be complete (§Types).
1506 1507 1508 1509 1510 1511
</p>
<pre class="grammar">
VarDecl     = "var" ( VarSpec | "(" [ VarSpecList ] ")" ) .
VarSpecList = VarSpec { ";" VarSpec } [ ";" ] .
VarSpec     = IdentifierList ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
</pre>
1512

1513
<pre>
1514 1515 1516 1517 1518 1519 1520 1521
var i int
var U, V, W float
var k = 0
var x, y float = -1.0, -2.0
var (
	i int;
	u, v, s = 2.0, 3.0, "bar"
)
1522
</pre>
1523

1524
<p>
1525 1526 1527 1528
If there are expressions, their number must be equal
to the number of identifiers, and the n<sup>th</sup> variable
is initialized to the value of the n<sup>th</sup> expression.
Otherwise, each variable is initialized to the <i>zero</i>
Rob Pike's avatar
Rob Pike committed
1529
of the type (§The zero value).
1530 1531
The expressions can be general expressions; they need not be constants.
</p>
1532
<p>
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544
Either the type or the expression list must be present.  If the
type is present, it sets the type of each variable and the expressions
(if any) must be assignment-compatible to that type.  If the type
is absent, the variables take the types of the corresponding
expressions.
</p>
<p>
If the type is absent and the corresponding expression is a constant
expression of ideal integer or ideal float type, the type of the
declared variable is <code>int</code> or <code>float</code>
respectively:
</p>
1545

1546 1547 1548 1549
<pre>
var i = 0       // i has type int
var f = 3.1415  // f has type float
</pre>
1550

1551
<h3>Short variable declarations</h3>
1552

1553
A <i>short variable declaration</i> uses the syntax
1554

Rob Pike's avatar
Rob Pike committed
1555
<pre class="grammar">
1556
SimpleVarDecl = IdentifierList ":=" ExpressionList .
1557
</pre>
1558

1559
and is shorthand for the declaration syntax
1560

1561 1562
<pre class="grammar">
"var" IdentifierList = ExpressionList .
1563
</pre>
1564

1565
<pre>
1566 1567
i, j := 0, 10;
f := func() int { return 7; }
1568
ch := make(chan int);
1569
</pre>
1570

1571
<p>
1572 1573 1574
Unlike regular variable declarations, short variable declarations
can be used, by analogy with tuple assignment (§Assignments), to
receive the individual elements of a multi-valued expression such
Rob Pike's avatar
Rob Pike committed
1575
as a call to a multi-valued function.  In this form, the ExpressionList
1576 1577 1578 1579
must be a single such multi-valued expression, the number of
identifiers must equal the number of values, and the declared
variables will be assigned the corresponding values.
</p>
1580

1581
<pre>
1582
r, w := os.Pipe(fd);  // os.Pipe() returns two values
1583
</pre>
1584

Rob Pike's avatar
Rob Pike committed
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
<p>
A short variable declaration may redeclare variables provided they
were originally declared in the same block with the same type, and at
least one of the 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.
</p>

<pre>
field1, offset := nextField(str, 0);
field2, offset := nextField(str, offset);  // redeclares offset
</pre>

Rob Pike's avatar
Rob Pike committed
1599
<p>
1600 1601 1602 1603
Short variable declarations may appear only inside functions.
In some contexts such as the initializers for <code>if</code>,
<code>for</code>, or <code>switch</code> statements,
they can be used to declare local temporary variables (§Statements).
Rob Pike's avatar
Rob Pike committed
1604
</p>
1605

1606
<h3>Function declarations</h3>
1607

1608 1609 1610
<p>
A function declaration binds an identifier to a function (§Function types).
</p>
1611

1612 1613 1614
<pre class="grammar">
FunctionDecl = "func" identifier Signature [ Block ] .
</pre>
1615

1616 1617 1618 1619 1620 1621 1622 1623
<pre>
func min(x int, y int) int {
	if x &lt; y {
		return x;
	}
	return y;
}
</pre>
1624

1625 1626 1627 1628
<p>
A function must be declared or forward-declared before it can be invoked (§Forward declarations).
Implementation restriction: Functions can only be declared at the package level.
</p>
1629

1630
<h3>Method declarations</h3>
1631

1632
<p>
1633 1634
A method declaration binds an identifier to a method,
which is a function with a <i>receiver</i>.
Rob Pike's avatar
Rob Pike committed
1635
</p>
1636 1637 1638 1639 1640
<pre class="grammar">
MethodDecl = "func" Receiver identifier Signature [ Block ] .
Receiver = "(" [ identifier ] [ "*" ] TypeName ")" .
</pre>

1641
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1642 1643 1644 1645
The receiver type must be of the form <code>T</code> or <code>*T</code> where
<code>T</code> is a type name. <code>T</code> is called the
<i>receiver base type</i> or just <i>base type</i>.
The base type must not be a pointer or interface type and must be
1646 1647 1648 1649
declared in the same source file as the method.
The method is said to be <i>bound</i> to the base type
and is visible only within selectors for that type
(§Type declarations, §Selectors).
Rob Pike's avatar
Rob Pike committed
1650
</p>
1651

1652 1653 1654
<p>
Given type <code>Point</code>, the declarations
</p>
1655

1656 1657 1658 1659
<pre>
func (p *Point) Length() float {
	return Math.sqrt(p.x * p.x + p.y * p.y);
}
1660

1661 1662 1663 1664 1665
func (p *Point) Scale(factor float) {
	p.x = p.x * factor;
	p.y = p.y * factor;
}
</pre>
1666

1667 1668 1669 1670
<p>
bind the methods <code>Length</code> and <code>Scale</code>
to the base type <code>Point</code>.
</p>
1671

1672
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1673
If the receiver's value is not referenced inside the the body of the method,
1674 1675 1676
its identifier may be omitted in the declaration. The same applies in
general to parameters of functions and methods.
</p>
1677

1678 1679 1680 1681 1682 1683
<p>
Methods can be declared
only after their base type is declared or forward-declared, and invoked
only after their own declaration or forward-declaration (§Forward declarations).
Implementation restriction: They can only be declared at package level.
</p>
1684

Rob Pike's avatar
Rob Pike committed
1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
<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>
(p *Point, factor float)
</pre>

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

1698
<h3>Forward declarations</h3>
1699

1700
<p>
Rob Pike's avatar
Rob Pike committed
1701
Mutually-recursive types require that one be
1702 1703 1704 1705
<i>forward declared</i> so that it may be named in the other.
A forward declaration of a type omits the block containing the fields
or methods of the type.
</p>
1706

1707
<pre>
1708 1709 1710 1711 1712 1713 1714 1715
type List struct  // forward declaration of List
type Item struct {
	value int;
	next *List;
}
type List struct {
	head, tail *Item
}
1716
</pre>
1717 1718 1719
<p>
A forward-declared type is incomplete (§Types)
until it is fully declared. The full declaration must follow
1720 1721
before the end of the block containing the forward declaration;
it cannot be contained in an inner block.
1722 1723 1724 1725
</p>
<p>
Functions and methods may similarly be forward-declared by omitting their body.
</p>
1726
<pre>
1727 1728 1729 1730 1731 1732 1733 1734
func F(a int) int  // forward declaration of F
func G(a, b int) int {
	return F(a) + F(b)
}
func F(a int) int {
	if a <= 0 { return 0 }
	return G(a-1, b+1)
}
1735
</pre>
1736

Rob Pike's avatar
Rob Pike committed
1737
<hr/>
1738

1739
<h2>Expressions</h2>
1740

1741
<p>
Rob Pike's avatar
Rob Pike committed
1742
An expression specifies the computation of a value by applying
Robert Griesemer's avatar
Robert Griesemer committed
1743 1744
operators and functions to operands. An expression has a value
and a type.
Rob Pike's avatar
Rob Pike committed
1745
</p>
1746

1747
<h3>Operands</h3>
1748 1749 1750

Operands denote the elementary values in an expression.

Rob Pike's avatar
Rob Pike committed
1751
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
1752 1753 1754 1755
Operand    = Literal | QualifiedIdent | "(" Expression ")" .
Literal    = BasicLit | CompositeLit | FunctionLit .
BasicLit   = int_lit | float_lit | char_lit | StringLit .
StringLit  = string_lit { string_lit } .
1756
</pre>
1757 1758


1759
<h3>Constants</h3>
Robert Griesemer's avatar
Robert Griesemer committed
1760

Rob Pike's avatar
Rob Pike committed
1761
<p>
1762 1763 1764 1765 1766 1767
A <i>constant</i> is a literal of a basic type
(including the predeclared constants <code>true</code>, <code>false</code>
and <code>nil</code>
and values denoted by <code>iota</code>)
or a constant expression (§Constant expressions).
Constants have values that are known at compile time.
Rob Pike's avatar
Rob Pike committed
1768
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1769

1770
<h3>Qualified identifiers</h3>
1771

1772
<p>
Rob Pike's avatar
Rob Pike committed
1773 1774
A qualified identifier is an identifier qualified by a package name prefix.
</p>
1775

Rob Pike's avatar
Rob Pike committed
1776
<pre class="grammar">
1777
QualifiedIdent = [ ( LocalPackageName | PackageName ) "." ] identifier .
Rob Pike's avatar
Rob Pike committed
1778
LocalPackageName = identifier .
1779 1780
PackageName = identifier .
</pre>
1781

Rob Pike's avatar
Rob Pike committed
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
<p>
A qualified identifier accesses an identifier in
a separate package.  The identifier must be exported by that package, which
means that it must begin with a Unicode upper case letter (§Exported identifiers).
</p>
<p>
The LocalPackageName is that of the package in which the qualified identifier
appears and is only necessary to access names hidden by intervening declarations
of a package-level identifier.
</p>

<pre>
Math.Sin
mypackage.hiddenName
mypackage.Math.Sin  // if Math is declared in an intervening scope
</pre>
1798

1799 1800 1801
TODO: 6g does not implement LocalPackageName.  Is this new?
Is it needed?

1802
<h3>Composite literals</h3>
1803

Rob Pike's avatar
Rob Pike committed
1804 1805 1806 1807
<p>
Composite literals construct values for structs, arrays, slices, and maps
and create a new value each time they are evaluated.
They consist of the type of the value
1808 1809
followed by a brace-bound list of composite elements. An element may be
a single expression or a key-value pair.
Rob Pike's avatar
Rob Pike committed
1810
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1811

Rob Pike's avatar
Rob Pike committed
1812
<pre class="grammar">
1813
CompositeLit  = LiteralType "{" [ ElementList ] "}" .
Rob Pike's avatar
Rob Pike committed
1814 1815
LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
                SliceType | MapType | TypeName .
1816 1817 1818 1819
ElementList   = Element { "," Element } [ "," ] .
Element       = [ Key ":" ] Value .
Key           = Expression .
Value         = Expression .
1820
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
1821

Rob Pike's avatar
Rob Pike committed
1822
<p>
1823 1824 1825
The LiteralType must be a struct, array, slice, or map type
(the grammar enforces this constraint except when the type is given
as a TypeName).
1826 1827 1828
The types of the expressions must be assignment compatible to
the respective field, element, and key types of the LiteralType;
there is no additional conversion.
1829 1830 1831 1832 1833
The key is interpreted as a field name for struct literals,
an index for array and slice literals, and a key for map literals.
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
1834
</p>
1835

1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
<p>
For struct literals the following rules apply:
<ul>
	<li>A literal which does not contain any keys must
	    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>
	<li>A literal which contains keys does not need to
	    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
		to the zero value for its type.
	</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>

<p>
Given the declarations
</p>
1861
<pre>
1862 1863
type Point struct { x, y, z float }
type Line struct { p, q Point }
1864
</pre>
1865

Rob Pike's avatar
Rob Pike committed
1866 1867 1868
<p>
one may write
</p>
1869

1870
<pre>
1871 1872
origin := Point{};                            // zero value for Point
line := Line{origin, Point{y: -4, z: 12.3}};  // zero value for line.q.x
1873 1874
</pre>

1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
<p>For array and slice literals the following rules apply:
<ul>
	<li>Each element has an associated integer index marking
	    its position in the array.
	</li>
	<li>An element with a key uses the key as its index; the
	    key must be a constant integer expression.
	</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>
</p>

1889
<p>
Rob Pike's avatar
Rob Pike committed
1890 1891
Taking the address of a composite literal (§Address operators)
generates a unique pointer to an instance of the literal's value.
1892 1893
</p>
<pre>
1894
var pointer *Point = &amp;Point{y: 1000};
1895
</pre>
1896

Rob Pike's avatar
Rob Pike committed
1897
<p>
1898 1899
The length of an array literal is the length specified in the LiteralType.
If fewer elements than the length are provided in the literal, the missing
Rob Pike's avatar
Rob Pike committed
1900
elements are set to the zero value for the array element type.
1901 1902 1903
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
1904
</p>
1905

1906
<pre>
1907
buffer := [10]string{};               // len(buffer) == 10
1908
intSet := [6]int{1, 2, 3, 5};         // len(intSet) == 6
1909
days := [...]string{"Sat", "Sun"};    // len(days) == 2
1910
</pre>
1911

Rob Pike's avatar
Rob Pike committed
1912 1913
<p>
A slice literal describes the entire underlying array literal.
1914 1915
Thus, the length and capacity of a slice literal is the maximum
element index plus one. A slice literal has the form
Rob Pike's avatar
Rob Pike committed
1916
</p>
1917

1918
<pre>
1919
[]T{x1, x2, ... xn}
1920
</pre>
1921

Rob Pike's avatar
Rob Pike committed
1922 1923 1924
<p>
and is a shortcut for a slice operation applied to an array literal:
</p>
1925

1926
<pre>
1927
[n]T{x1, x2, ... xn}[0 : n]
1928
</pre>
1929

1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
<p>
A parsing ambiguity arises when a composite literal using the
TypeName form of the LiteralType appears in the condition of an
"if", "for", or "switch" statement, because the braces surrounding
the expressions in the literal are confused with those introducing
a block of statements. To resolve the ambiguity in this rare case,
the composite literal must appear within
parentheses.
</p>

<pre>
if x == (T{a,b,c}[i]) { ... }
if (x == T{a,b,c}[i]) { ... }
</pre>

1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
<p>
Examples of valid array, slice, and map literals:
</p>

<pre>
// list of prime numbers
primes := []int{2, 3, 5, 7, 9, 11, 13, 17, 19, 991};

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

// the array [10]float{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1};
filter := [10]float{-1, 4: -0.1, -0.1, 9: -1};

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


1967
<h3>Function literals</h3>
1968

Rob Pike's avatar
Rob Pike committed
1969 1970 1971 1972
<p>
A function literal represents an anonymous function.
It consists of a specification of the function type and a function body.
</p>
1973

Rob Pike's avatar
Rob Pike committed
1974
<pre class="grammar">
1975
FunctionLit   = FunctionType Block .
1976
Block         = "{" StatementList "}" .
1977
</pre>
1978

1979
<pre>
Rob Pike's avatar
Rob Pike committed
1980
func (a, b int, z float) bool { return a*b &lt; int(z) }
1981
</pre>
1982

Rob Pike's avatar
Rob Pike committed
1983 1984 1985
<p>
A function literal can be assigned to a variable or invoked directly.
</p>
1986

1987
<pre>
Rob Pike's avatar
Rob Pike committed
1988 1989
f := func(x, y int) int { return x + y }
func(ch chan int) { ch &lt;- ACK } (reply_chan)
1990
</pre>
1991

Rob Pike's avatar
Rob Pike committed
1992 1993
<p>
Function literals are <i>closures</i>: they may refer to variables
1994 1995
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
1996 1997
as they are accessible.
</p>
1998

1999

2000
<h3>Primary expressions</h3>
2001

Rob Pike's avatar
Rob Pike committed
2002
<pre class="grammar">
2003 2004 2005 2006 2007
PrimaryExpr =
	Operand |
	PrimaryExpr Selector |
	PrimaryExpr Index |
	PrimaryExpr Slice |
2008
	PrimaryExpr TypeAssertion |
2009 2010
	PrimaryExpr Call .

2011 2012 2013 2014 2015
Selector       = "." identifier .
Index          = "[" Expression "]" .
Slice          = "[" Expression ":" Expression "]" .
TypeAssertion  = "." "(" Type ")" .
Call           = "(" [ ExpressionList ] ")" .
2016 2017 2018 2019 2020 2021 2022 2023
</pre>


<pre>
x
2
(s + ".txt")
f(3.1415, true)
2024
Point{1, 2}
2025 2026 2027 2028 2029 2030 2031 2032 2033
m["foo"]
s[i : j + 1]
obj.color
Math.sin
f.p[i].x()
</pre>


<h3>Selectors</h3>
2034

Rob Pike's avatar
Rob Pike committed
2035
<p>
Robert Griesemer's avatar
Robert Griesemer committed
2036
A primary expression of the form
Rob Pike's avatar
Rob Pike committed
2037
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2038

2039 2040 2041
<pre>
x.f
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2042

2043
<p>
Rob Pike's avatar
Rob Pike committed
2044 2045 2046 2047 2048 2049 2050
denotes the field or method <code>f</code> of the value denoted by <code>x</code>
(or of <code>*x</code> if
<code>x</code> is of pointer type). The identifier <code>f</code>
is called the (field or method)
<i>selector</i>.
The type of the expression is the type of <code>f</code>.
</p>
2051
<p>
Rob Pike's avatar
Rob Pike committed
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
A selector <code>f</code> may denote a field or method <code>f</code> of
a type <code>T</code>, or it may refer
to a field or method <code>f</code> of a nested anonymous field of
<code>T</code>.
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>
2064
<p>
2065
The following rules apply to selectors:
Rob Pike's avatar
Rob Pike committed
2066 2067 2068 2069 2070 2071 2072 2073 2074
</p>
<ol>
<li>
For a value <code>x</code> of type <code>T</code> or <code>*T</code>
where <code>T</code> is not an interface type,
<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>.
If there is not exactly one <code>f</code> with shallowest depth, the selector
2075
expression is illegal.
Rob Pike's avatar
Rob Pike committed
2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
</li>
<li>
For a variable <code>x</code> of type <code>I</code> or <code>*I</code>
where <code>I</code> is an interface type,
<code>x.f</code> denotes the actual method with name <code>f</code> of the value assigned
to <code>x</code> if there is such a method.
If no value or <code>nil</code> was assigned to <code>x</code>, <code>x.f</code> is illegal.
</li>
<li>
In all other cases, <code>x.f</code> is illegal.
</ol>
2087
<p>
Rob Pike's avatar
Rob Pike committed
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
Selectors automatically dereference pointers as necessary.
If <code>x</code> is of pointer type, <code>x.y</code>
is shorthand for <code>(*x).y</code>; if <code>y</code>
is also of pointer type, <code>x.y.z</code> is shorthand
for <code>(*(*x).y).z</code>, and so on.
If <code>*x</code> is of pointer type, dereferencing
must be explicit;
only one level of automatic dereferencing is provided.
For an <code>x</code> of type <code>T</code> containing an
anonymous field declared as <code>*A</code>,
<code>x.f</code> is a shortcut for <code>(*x.A).f</code>.
</p>
2100
<p>
Rob Pike's avatar
Rob Pike committed
2101 2102
For example, given the declarations:
</p>
2103

2104 2105 2106 2107
<pre>
type T0 struct {
	x int;
}
2108

2109
func (recv *T0) M0()
2110

2111 2112 2113
type T1 struct {
	y int;
}
2114

2115
func (recv T1) M1()
2116

2117 2118 2119 2120 2121
type T2 struct {
	z int;
	T1;
	*T0;
}
Robert Griesemer's avatar
Robert Griesemer committed
2122

2123
func (recv *T2) M2()
Robert Griesemer's avatar
Robert Griesemer committed
2124

2125 2126
var p *T2;  // with p != nil and p.T1 != nil
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2127

Rob Pike's avatar
Rob Pike committed
2128 2129 2130
<p>
one may write:
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2131

2132 2133 2134 2135
<pre>
p.z         // (*p).z
p.y         // ((*p).T1).y
p.x         // (*(*p).T0).x
Robert Griesemer's avatar
Robert Griesemer committed
2136

2137 2138 2139 2140
p.M2        // (*p).M2
p.M1        // ((*p).T1).M1
p.M0        // ((*p).T0).M0
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2141 2142


2143
<font color=red>
2144
TODO: Specify what happens to receivers.
2145
</font>
Robert Griesemer's avatar
Robert Griesemer committed
2146

2147

2148
<h3>Indexes</h3>
2149

Rob Pike's avatar
Rob Pike committed
2150
<p>
Robert Griesemer's avatar
Robert Griesemer committed
2151
A primary expression of the form
Rob Pike's avatar
Rob Pike committed
2152
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2153

2154 2155 2156
<pre>
a[x]
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2157

Rob Pike's avatar
Rob Pike committed
2158
<p>
Rob Pike's avatar
Rob Pike committed
2159 2160 2161
denotes the array or map element of <code>a</code> indexed by <code>x</code>.
The value <code>x</code> is called the
<i>array index</i> or <i>map key</i>, respectively. The following
Robert Griesemer's avatar
Robert Griesemer committed
2162
rules apply:
Rob Pike's avatar
Rob Pike committed
2163
</p>
2164
<p>
Rob Pike's avatar
Rob Pike committed
2165 2166
For <code>a</code> of type <code>A</code> or <code>*A</code>
where <code>A</code> is an array type (§Array types):
Rob Pike's avatar
Rob Pike committed
2167
</p>
2168
<ul>
Rob Pike's avatar
Rob Pike committed
2169 2170 2171
	<li><code>x</code> must be an integer value and <code>0 &lt;= x &lt; len(a)</code>
	<li><code>a[x]</code> is the array element at index <code>x</code> and the type of
	  <code>a[x]</code> is the element type of <code>A</code>
2172 2173
</ul>
<p>
Rob Pike's avatar
Rob Pike committed
2174 2175
For <code>a</code> of type <code>M</code> or <code>*M</code>
where <code>M</code> is a map type (§Map types):
Rob Pike's avatar
Rob Pike committed
2176
</p>
2177
<ul>
2178
	<li><code>x</code>'s type must be compatible with the key type of <code>M</code>
Rob Pike's avatar
Rob Pike committed
2179 2180 2181
	  and the map must contain an entry with key <code>x</code> (but see special forms below)
	<li><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>
2182
</ul>
Robert Griesemer's avatar
Robert Griesemer committed
2183

2184
<p>
Rob Pike's avatar
Rob Pike committed
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213
Otherwise <code>a[x]</code> is illegal.  If the index or key is out of range evaluating
an otherwise legal index expression, a run-time exception occurs.
</p>

<p>
However, if an index expression on a map <code>a</code> of type <code>map[K] V</code>
is used in an assignment of one of the special forms
</p>

<pre>
r, ok = a[x]
r, ok := a[x]
</pre>

<p>
the result of the index expression is a pair of values with types
<code>(K, bool)</code>.
If the key is present in the map,
the expression returns the pair <code>(a[x], true)</code>;
otherwise it returns <code>(Z, false)</code> where <code>Z</code> is
the zero value for <code>V</code> (§The zero value).
No run-time exception occurs in this case.
The index expression in this construct thus acts like a function call
returning a value and a boolean indicating success.  (§Assignments)
</p>

<p>
Similarly, if an assignment to a map has the special form
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2214

Rob Pike's avatar
Rob Pike committed
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
<pre>
a[x] = r, ok
</pre>

<p>
and boolean <code>ok</code> has the value <code>false</code>,
the entry for key <code>x</code> is deleted from the map; if
<code>ok</code> is <code>true</code>, the construct acts like
a regular assignment to an element of the map.
</p>
2225

2226
<h3>Slices</h3>
2227

Rob Pike's avatar
Rob Pike committed
2228
<p>
Rob Pike's avatar
Rob Pike committed
2229
Strings, arrays, and slices can be <i>sliced</i> to construct substrings or descriptors
Robert Griesemer's avatar
Robert Griesemer committed
2230 2231
of subarrays. The index expressions in the slice select which elements appear
in the result.  The result has indexes starting at 0 and length equal to the
Rob Pike's avatar
Rob Pike committed
2232 2233
difference in the index values in the slice.  After slicing the array <code>a</code>
</p>
2234

2235
<pre>
2236
a := [4]int{1, 2, 3, 4};
2237 2238
s := a[1:3];
</pre>
2239

Rob Pike's avatar
Rob Pike committed
2240
<p>
2241
the slice <code>s</code> has type <code>[]int</code>, length 2, capacity 3, and elements
Rob Pike's avatar
Rob Pike committed
2242
</p>
2243

2244 2245 2246 2247
<pre>
s[0] == 2
s[1] == 3
</pre>
2248

Rob Pike's avatar
Rob Pike committed
2249
<p>
Rob Pike's avatar
Rob Pike committed
2250
The slice length must be non-negative.
2251
For arrays or strings, the indexes
Rob Pike's avatar
Rob Pike committed
2252 2253
<code>lo</code> and <code>hi</code> must satisfy
0 &lt;= <code>lo</code> &lt;= <code>hi</code> &lt;= length;
2254
for slices, the upper bound is the capacity rather than the length.
2255
<p>
Rob Pike's avatar
Rob Pike committed
2256
If the sliced operand is a string, the result of the slice operation is another, new
Robert Griesemer's avatar
Robert Griesemer committed
2257 2258
string (§String types). If the sliced operand is an array or slice, the result
of the slice operation is a slice (§Slice types).
Rob Pike's avatar
Rob Pike committed
2259
</p>
2260 2261


2262
<h3>Type assertions</h3>
2263

Rob Pike's avatar
Rob Pike committed
2264 2265 2266
<p>
For an expression <code>x</code> and a type <code>T</code>, the primary expression
</p>
2267

2268 2269 2270
<pre>
x.(T)
</pre>
2271

2272
<p>
Russ Cox's avatar
Russ Cox committed
2273 2274
asserts that <code>x</code> is not the zero interface value
and that the value stored in <code>x</code> is of type <code>T</code>.
2275 2276
The notation <code>x.(T)</code> is called a <i>type assertion</i>.
The type of <code>x</code> must be an interface type.
Rob Pike's avatar
Rob Pike committed
2277 2278
</p>
<p>
2279
More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
Rob Pike's avatar
Rob Pike committed
2280
that the dynamic type of <code>x</code> is identical to the type <code>T</code>
2281
(§Type identity and compatibility).
2282
If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
Rob Pike's avatar
Rob Pike committed
2283 2284
of <code>T</code> implements the interface <code>T</code> (§Interface types).
</p>
2285
<p>
2286 2287
If the type assertion holds, the value of the expression is the value
stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false, a run-time
Rob Pike's avatar
Rob Pike committed
2288
exception occurs. In other words, even though the dynamic type of <code>x</code>
2289
is known only at run-time, the type of <code>x.(T)</code> is
Rob Pike's avatar
Rob Pike committed
2290 2291
known to be <code>T</code> in a correct program.
</p>
2292
<p>
2293
If a type assertion is used in an assignment of one of the special forms,
Rob Pike's avatar
Rob Pike committed
2294
</p>
2295

2296 2297 2298 2299
<pre>
v, ok = x.(T)
v, ok := x.(T)
</pre>
2300

2301
<p>
2302 2303
the result of the assertion is a pair of values with types <code>(T, bool)</code>.
If the assertion holds, the expression returns the pair <code>(x.(T), true)</code>;
Rob Pike's avatar
Rob Pike committed
2304 2305 2306
otherwise, the expression returns <code>(Z, false)</code> where <code>Z</code>
is the zero value for type <code>T</code> (§The zero value).
No run-time exception occurs in this case.
2307
The type assertion in this construct thus acts like a function call
Rob Pike's avatar
Rob Pike committed
2308 2309
returning a value and a boolean indicating success.  (§Assignments)
</p>
2310

2311

2312
<h3>Calls</h3>
2313

2314
<p>
Rob Pike's avatar
Rob Pike committed
2315 2316
Given an expression <code>f</code> of function type
<code>F</code>,
Rob Pike's avatar
Rob Pike committed
2317
</p>
2318

2319
<pre>
Rob Pike's avatar
Rob Pike committed
2320
f(a1, a2, ... an)
2321
</pre>
2322

2323
<p>
Rob Pike's avatar
Rob Pike committed
2324 2325 2326
calls <code>f</code> with arguments <code>a1, a2, ... an</code>.
The arguments must be single-valued expressions
assignment compatible with the parameters of
Rob Pike's avatar
Rob Pike committed
2327 2328 2329 2330 2331 2332 2333
<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>
2334

2335
<pre>
Rob Pike's avatar
Rob Pike committed
2336 2337 2338
Atan2(x, y)    // function call
var pt *Point;
pt.Scale(3.5)  // method call with receiver pt
2339
</pre>
2340

Rob Pike's avatar
Rob Pike committed
2341
<p>
Robert Griesemer's avatar
Robert Griesemer committed
2342 2343 2344 2345 2346 2347
A method call <code>x.m()</code> is valid if the method set of
(the type of) <code>x</code> contains <code>m</code> (and the
argument list is compatible with the parameter list of <code>m</code>).
If <code>x</code> is addressable and <code>&amp;x</code>'s method
set contains <code>m</code>, <code>x.m()</code> is shorthand
for <code>(&amp;x).m()</code>:
Rob Pike's avatar
Rob Pike committed
2348
</p>
2349

2350
<pre>
Rob Pike's avatar
Rob Pike committed
2351 2352
var p Point;
p.Scale(3.5)
2353
</pre>
2354

2355
<p>
2356
There is no distinct method type and there are no method literals.
Rob Pike's avatar
Rob Pike committed
2357
</p>
2358

Rob Pike's avatar
Rob Pike committed
2359
<h3>Passing arguments to <code>...</code> parameters</h3>
2360

Rob Pike's avatar
Rob Pike committed
2361 2362 2363 2364 2365 2366 2367 2368
<p>
When a function <code>f</code> has a <code>...</code> parameter,
it is always the last formal parameter. Within calls to <code>f</code>,
the arguments before the <code>...</code> are treated normally.
After those, an arbitrary number (including zero) of trailing
arguments may appear in the call and are bound to the <code>...</code>
parameter.
</p>
2369

2370
<p>
Rob Pike's avatar
Rob Pike committed
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380
Within <code>f</code>, the <code>...</code> parameter has static
type <code>interface{}</code> (the empty interface). For each call,
its dynamic type is a structure whose sequential fields are the
trailing arguments of the call.  That is, the actual arguments
provided for a <code>...</code> parameter are wrapped into a struct
that is passed to the function instead of the actual arguments.
Using the reflection library (TODO: reference), <code>f</code> may
unpack the elements of the dynamic type to recover the actual
arguments.
</p>
2381

Rob Pike's avatar
Rob Pike committed
2382 2383 2384
<p>
Given the function and call
</p>
2385
<pre>
Rob Pike's avatar
Rob Pike committed
2386
func Fprintf(f io.Writer, format string, args ...)
Rob Pike's avatar
Rob Pike committed
2387
Fprintf(os.Stdout, "%s %d", "hello", 23);
2388
</pre>
2389

Rob Pike's avatar
Rob Pike committed
2390 2391 2392 2393 2394
<p>
Within <code>Fprintf</code>, the dynamic type of <code>args</code> for this
call will be, schematically,
<code> struct { string; int }</code>.
</p>
2395 2396


Rob Pike's avatar
Rob Pike committed
2397 2398 2399 2400 2401
<p>
As a special case, if a function passes its own <code>...</code> parameter as the argument
for a <code>...</code> in a call to another function with a <code>...</code> parameter,
the parameter is not wrapped again but passed directly. In short, a formal <code>...</code>
parameter is passed unchanged as an actual <code>...</code> parameter.
2402

2403
<h3>Operators</h3>
2404

Rob Pike's avatar
Rob Pike committed
2405
<p>
2406
Operators combine operands into expressions.
Rob Pike's avatar
Rob Pike committed
2407
</p>
2408

Rob Pike's avatar
Rob Pike committed
2409
<pre class="grammar">
2410
Expression = UnaryExpr | Expression binary_op UnaryExpr .
Rob Pike's avatar
Rob Pike committed
2411
UnaryExpr  = PrimaryExpr | unary_op UnaryExpr .
2412

Rob Pike's avatar
Rob Pike committed
2413 2414 2415 2416 2417
binary_op  = log_op | com_op | rel_op | add_op | mul_op .
log_op     = "||" | "&amp;&amp;" .
com_op     = "&lt;-" .
rel_op     = "==" | "!=" | "&lt;" | "&lt;=" | ">" | ">=" .
add_op     = "+" | "-" | "|" | "^" .
Rob Pike's avatar
Rob Pike committed
2418
mul_op     = "*" | "/" | "%" | "&lt;&lt;" | ">>" | "&amp;" | "&amp;^" .
2419

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

2423
<p>
2424
The operand types in binary operations must be compatible, with the following exceptions:
Rob Pike's avatar
Rob Pike committed
2425
</p>
2426
<ul>
Rob Pike's avatar
Rob Pike committed
2427
	<li>Except in shift expressions, if one operand has numeric type and the other operand is
2428
	  an ideal number, the ideal number is converted to match the type of
Rob Pike's avatar
Rob Pike committed
2429
	  the other operand (§Expressions).</li>
2430

2431
	<li>If both operands are ideal numbers, the conversion is to ideal floats
Rob Pike's avatar
Rob Pike committed
2432 2433
	  if one of the operands is an ideal float
	  (relevant for <code>/</code> and <code>%</code>).</li>
2434

Rob Pike's avatar
Rob Pike committed
2435 2436 2437 2438
	<li>The right operand in a shift operation must be always be of unsigned integer type
	  or an ideal number that can be safely converted into an unsigned integer type
	  (§Arithmetic operators).</li>

2439
	<li>The operands in channel sends differ in type: one is always a channel and the
Rob Pike's avatar
Rob Pike committed
2440
	other is a variable or value of the channel's element type.</li>
2441

2442
	<li>When comparing two operands of channel type, the channel value types
2443
	  must be compatible but the channel direction is ignored.</li>
2444
</ul>
2445

2446
<p>
Rob Pike's avatar
Rob Pike committed
2447 2448 2449 2450 2451 2452 2453 2454 2455
Unary operators have the highest precedence. They are evaluated from
right to left. As the  <code>++</code> and <code>--</code> operators form
statements, not expressions, they fall
outside the unary operator hierarchy and apply
to the operand on the left.
As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>.
<p>
There are six precedence levels for binary operators.
Multiplication operators bind strongest, followed by addition
2456
operators, comparison operators, communication operators,
Rob Pike's avatar
Rob Pike committed
2457 2458
<code>&amp;&amp;</code> (logical and), and finally <code>||</code> (logical or):
</p>
2459

Rob Pike's avatar
Rob Pike committed
2460
<pre class="grammar">
2461
Precedence    Operator
Rob Pike's avatar
Rob Pike committed
2462
    6             *  /  %  &lt;&lt;  >>  &amp;  &amp;^
2463 2464 2465 2466 2467 2468
    5             +  -  |  ^
    4             ==  !=  &lt;  &lt;=  >  >=
    3             &lt;-
    2             &amp;&amp;
    1             ||
</pre>
2469

Rob Pike's avatar
Rob Pike committed
2470
<p>
2471
Binary operators of the same precedence associate from left to right.
Rob Pike's avatar
Rob Pike committed
2472 2473
For instance, <code>x / y / z</code> is the same as <code>(x / y) / z</code>.
</p>
2474
<p>
Rob Pike's avatar
Rob Pike committed
2475 2476
Examples:
</p>
2477

2478 2479 2480 2481 2482 2483 2484 2485
<pre>
+x
23 + 3*x[i]
x &lt;= f()
^a >> b
f() || g()
x == y + 1 &amp;&amp; &lt;-chan_ptr > 0
</pre>
2486 2487


2488 2489
<h3>Arithmetic operators</h3>
<p>
2490
Arithmetic operators apply to numeric types and yield a result of the same
Rob Pike's avatar
Rob Pike committed
2491 2492 2493 2494 2495
type as the first operand. The four standard arithmetic operators (<code>+</code>,
<code>-</code>,  <code>*</code>, <code>/</code>) apply both to integer and
floating point types, while <code>+</code> applies also
to strings; all other arithmetic operators apply to integers only.
</p>
2496

Rob Pike's avatar
Rob Pike committed
2497
<pre class="grammar">
2498 2499 2500 2501 2502
+    sum                    integers, floats, strings
-    difference             integers, floats
*    product                integers, floats
/    quotient               integers, floats
%    remainder              integers
2503

2504 2505 2506 2507
&amp;    bitwise and            integers
|    bitwise or             integers
^    bitwise xor            integers
&amp;^   bit clear (and not)    integers
2508

2509 2510
<<   left shift             integer << unsigned integer
>>   right shift            integer >> unsigned integer
2511
</pre>
2512

Rob Pike's avatar
Rob Pike committed
2513 2514 2515 2516
<p>
Strings can be concatenated using the <code>+</code> operator
or the <code>+=</code> assignment operator:
</p>
2517

2518
<pre>
Rob Pike's avatar
Rob Pike committed
2519 2520
s := "hi" + string(c);
s += " and good bye";
2521
</pre>
2522

2523
<p>
Rob Pike's avatar
Rob Pike committed
2524 2525 2526 2527 2528
String addition creates a new string by concatenating the operands.
</p>
<p>
For integer values, <code>/</code> and <code>%</code> satisfy the following relationship:
</p>
2529

2530 2531 2532
<pre>
(a / b) * b + a % b == a
</pre>
2533

Rob Pike's avatar
Rob Pike committed
2534 2535
<p>
with <code>(a / b)</code> truncated towards zero.
2536
Examples:
Rob Pike's avatar
Rob Pike committed
2537
</p>
2538

2539 2540 2541 2542 2543 2544 2545
<pre>
 x     y     x / y     x % y
 5     3       1         2
-5     3      -1        -2
 5    -3      -1         2
-5    -3       1        -2
</pre>
2546

Rob Pike's avatar
Rob Pike committed
2547 2548
<p>
If the dividend is positive and the divisor is a constant power of 2,
2549 2550
the division may be replaced by a left shift, and computing the remainder may
be replaced by a bitwise "and" operation:
Rob Pike's avatar
Rob Pike committed
2551
</p>
2552

2553 2554 2555 2556 2557
<pre>
 x     x / 4     x % 4     x >> 2     x &amp; 3
 11      2         3         2          3
-11     -2        -3        -3          1
</pre>
2558

Rob Pike's avatar
Rob Pike committed
2559
<p>
2560 2561
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
Rob Pike's avatar
Rob Pike committed
2562 2563 2564 2565 2566 2567 2568 2569
integer and logical shifts if it is an unsigned integer. The shift count must
be an unsigned integer. There is no upper limit on the shift count. Shifts behave
as if the left operand is shifted <code>n</code> times by 1 for a shift
count of <code>n</code>.
As a result, <code>x << 1</code> is the same as <code>x*2</code>
and <code>x >> 1</code> is the same as
<code>x/2</code> truncated towards negative infinity.
</p>
2570

Rob Pike's avatar
Rob Pike committed
2571 2572 2573
<p>
For integer operands, the unary operators
<code>+</code>, <code>-</code>, and <code>^</code> are defined as
Robert Griesemer's avatar
Robert Griesemer committed
2574
follows:
Rob Pike's avatar
Rob Pike committed
2575
</p>
2576

Rob Pike's avatar
Rob Pike committed
2577
<pre class="grammar">
2578 2579
+x                          is 0 + x
-x    negation              is 0 - x
Russ Cox's avatar
Russ Cox committed
2580 2581
^x    bitwise complement    is m ^ x  with m = "all bits set to 1" for unsigned x
                                      and  m = -1 for signed x
2582
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2583

2584 2585 2586 2587 2588
<p>
For floating point numbers,
<code>+x</code> is the same as <code>x</code>,
while <code>-x</code> is the negation of <code>x</code>.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2589

2590
<h3>Integer overflow</h3>
Robert Griesemer's avatar
Robert Griesemer committed
2591

Rob Pike's avatar
Rob Pike committed
2592 2593 2594 2595 2596
<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
the unsigned integer's type
2597
(§Numeric types). Loosely speaking, these unsigned integer operations
Robert Griesemer's avatar
Robert Griesemer committed
2598
discard high bits upon overflow, and programs may rely on ``wrap around''.
Rob Pike's avatar
Rob Pike committed
2599
</p>
2600
<p>
Rob Pike's avatar
Rob Pike committed
2601 2602
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
2603 2604
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
2605
No exception is raised as a result of overflow. A
Robert Griesemer's avatar
Robert Griesemer committed
2606
compiler may not optimize code under the assumption that overflow does
Rob Pike's avatar
Rob Pike committed
2607 2608
not occur. For instance, it may not assume that <code>x &lt; x + 1</code> is always true.
</p>
2609 2610


2611
<h3>Comparison operators</h3>
2612

Rob Pike's avatar
Rob Pike committed
2613
<p>
2614
Comparison operators yield a boolean result. All comparison operators apply
Rob Pike's avatar
Rob Pike committed
2615 2616 2617 2618
to basic types except bools.
The operators <code>==</code> and <code>!=</code> apply, at least in some cases,
to all types except arrays and structs.
</p>
2619

Rob Pike's avatar
Rob Pike committed
2620
<pre class="grammar">
2621 2622 2623 2624 2625 2626 2627
==    equal
!=    not equal
<     less
<=    less or equal
>     greater
>=    greater or equal
</pre>
2628

Rob Pike's avatar
Rob Pike committed
2629 2630 2631 2632
<p>
Numeric basic types are compared in the usual way.
</p>
<p>
2633
Strings are compared byte-wise (lexically).
Rob Pike's avatar
Rob Pike committed
2634
</p>
2635
<p>
2636
Booleans are equal if they are either both "true" or both "false".
Rob Pike's avatar
Rob Pike committed
2637
</p>
2638
<p>
Rob Pike's avatar
Rob Pike committed
2639 2640 2641
The rules for comparison of composite types are described in the
section on §Comparison compatibility.
</p>
2642

2643

2644
<h3>Logical operators</h3>
2645

Rob Pike's avatar
Rob Pike committed
2646
<p>
2647 2648
Logical operators apply to boolean operands and yield a boolean result.
The right operand is evaluated conditionally.
Rob Pike's avatar
Rob Pike committed
2649
</p>
2650

Rob Pike's avatar
Rob Pike committed
2651
<pre class="grammar">
2652 2653 2654 2655
&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"
</pre>
2656 2657


2658
<h3>Address operators</h3>
2659

Rob Pike's avatar
Rob Pike committed
2660
<p>
Rob Pike's avatar
Rob Pike committed
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
The unary prefix address-of operator <code>&amp;</code> generates the address of its operand, which must be a variable,
pointer indirection, field selector, or array or slice indexing operation. It is illegal to take the address of a function
result variable.
Given an operand of pointer type, the unary prefix pointer indirection operator <code>*</code> retrieves the value pointed
to by the operand.
</p>

<pre>
&amp;x
&amp;a[f(2)]
*p
*pf(x)
</pre>

2675 2676
<p>
<font color=red>TODO: This text needs to be cleaned up and go elsewhere, there are no address
2677
operators involved.
2678
</font>
Rob Pike's avatar
Rob Pike committed
2679
</p>
2680
<p>
Rob Pike's avatar
Rob Pike committed
2681
Methods are a form of function and a method ``value'' has a function type.
2682
Consider the type T with method M:
Rob Pike's avatar
Rob Pike committed
2683
</p>
2684

2685 2686 2687 2688 2689 2690 2691
<pre>
type T struct {
	a int;
}
func (tp *T) M(a int) int;
var t *T;
</pre>
2692

Rob Pike's avatar
Rob Pike committed
2693
<p>
2694
To construct the value of method M, one writes
Rob Pike's avatar
Rob Pike committed
2695
</p>
2696

2697 2698 2699
<pre>
t.M
</pre>
2700

Rob Pike's avatar
Rob Pike committed
2701
<p>
2702
using the variable t (not the type T).
2703
<font color=red>TODO: It makes perfect sense to be able to say T.M (in fact, it makes more
2704 2705
sense then t.M, since only the type T is needed to find the method M, i.e.,
its address). TBD.
2706
</font>
Rob Pike's avatar
Rob Pike committed
2707
</p>
2708

Rob Pike's avatar
Rob Pike committed
2709
<p>
2710
The expression t.M is a function value with type
Rob Pike's avatar
Rob Pike committed
2711
</p>
2712

2713 2714 2715
<pre>
func (t *T, a int) int
</pre>
2716

Rob Pike's avatar
Rob Pike committed
2717
<p>
2718
and may be invoked only as a function, not as a method:
Rob Pike's avatar
Rob Pike committed
2719
</p>
2720

2721 2722 2723 2724 2725
<pre>
var f func (t *T, a int) int;
f = t.M;
x := f(t, 7);
</pre>
2726

Rob Pike's avatar
Rob Pike committed
2727
<p>
2728
Note that one does not write t.f(7); taking the value of a method demotes
2729
it to a function.
Rob Pike's avatar
Rob Pike committed
2730
</p>
2731

Rob Pike's avatar
Rob Pike committed
2732
<p>
2733
In general, given type T with method M and variable t of type T,
2734
the method invocation
Rob Pike's avatar
Rob Pike committed
2735
</p>
2736

2737 2738 2739
<pre>
t.M(args)
</pre>
2740

Rob Pike's avatar
Rob Pike committed
2741
<p>
2742
is equivalent to the function call
Rob Pike's avatar
Rob Pike committed
2743
</p>
2744

2745 2746 2747
<pre>
(t.M)(t, args)
</pre>
2748

Rob Pike's avatar
Rob Pike committed
2749
<p>
2750
<font color=red>
2751 2752
TODO: should probably describe the effect of (t.m) under §Expressions if t.m
denotes a method: Effect is as described above, converts into function.
2753
</font>
Rob Pike's avatar
Rob Pike committed
2754
</p>
2755
<p>
2756
If T is an interface type, the expression t.M does not determine which
2757
underlying type's M is called until the point of the call itself. Thus given
2758
T1 and T2, both implementing interface I with method M, the sequence
Rob Pike's avatar
Rob Pike committed
2759
</p>
2760

2761 2762 2763 2764 2765 2766 2767
<pre>
var t1 *T1;
var t2 *T2;
var i I = t1;
m := i.M;
m(t2, 7);
</pre>
2768

Rob Pike's avatar
Rob Pike committed
2769
<p>
2770
will invoke t2.M() even though m was constructed with an expression involving
2771
t1. Effectively, the value of m is a function literal
Rob Pike's avatar
Rob Pike committed
2772
</p>
2773

2774 2775 2776 2777 2778
<pre>
func (recv I, a int) {
	recv.M(a);
}
</pre>
2779

Rob Pike's avatar
Rob Pike committed
2780
<p>
2781
that is automatically created.
Rob Pike's avatar
Rob Pike committed
2782
</p>
2783 2784
<p>
<font color=red>
2785
TODO: Document implementation restriction: It is illegal to take the address
2786
of a result parameter (e.g.: func f() (x int, p *int) { return 2, &amp;x }).
2787
(TBD: is it an implementation restriction or fact?)
2788
</font>
Rob Pike's avatar
Rob Pike committed
2789
</p>
2790

2791
<h3>Communication operators</h3>
2792

2793
<p>
Rob Pike's avatar
Rob Pike committed
2794 2795
The term <i>channel</i> means "variable of channel type" (§Channel types).
</p>
2796 2797
<p>
The send operation uses the binary operator "&lt;-", which operates on
2798
a channel and a value (expression):
Rob Pike's avatar
Rob Pike committed
2799
</p>
2800

2801 2802 2803
<pre>
ch <- 3
</pre>
2804

Rob Pike's avatar
Rob Pike committed
2805 2806 2807 2808 2809 2810 2811 2812
<p>
The send operation sends the value on the channel.  Both the channel
and the expression are evaluated before communication begins.
Communication blocks until the send can proceed, at which point the
value is transmitted on the channel.  A send can proceed if the
channel is asynchronous and there is room in its buffer or the
channel is synchronous and a receiver is ready.
</p>
2813
<p>
2814 2815 2816
If the send operation appears in an expression context, the value
of the expression is a boolean and the operation is non-blocking.
The value of the boolean reports true if the communication succeeded,
Rob Pike's avatar
Rob Pike committed
2817 2818 2819 2820
false if it did not. (The channel and
the expression to be sent are evaluated regardless.)
These two examples are equivalent:
</p>
2821

2822 2823 2824
<pre>
ok := ch <- 3;
if ok { print("sent") } else { print("not sent") }
2825

2826 2827
if ch <- 3 { print("sent") } else { print("not sent") }
</pre>
2828

Rob Pike's avatar
Rob Pike committed
2829
<p>
2830 2831 2832 2833
In other words, if the program tests the value of a send operation,
the send is non-blocking and the value of the expression is the
success of the operation.  If the program does not test the value,
the operation blocks until it succeeds.
Rob Pike's avatar
Rob Pike committed
2834
</p>
2835 2836
<p>
The receive operation uses the prefix unary operator "&lt;-".
Rob Pike's avatar
Rob Pike committed
2837 2838 2839
The value of the expression is the value received, whose type
is the element type of the channel.
</p>
2840

2841 2842 2843
<pre>
<-ch
</pre>
2844

Rob Pike's avatar
Rob Pike committed
2845
<p>
2846
The expression blocks until a value is available, which then can
Rob Pike's avatar
Rob Pike committed
2847 2848 2849 2850
be assigned to a variable or used like any other expression.
If the receive expression does not save the value, the value is
discarded.
</p>
2851

2852 2853 2854 2855 2856 2857
<pre>
v1 := <-ch
v2 = <-ch
f(<-ch)
<-strobe  // wait until clock pulse
</pre>
2858

Rob Pike's avatar
Rob Pike committed
2859
<p>
2860
If a receive expression is used in a tuple assignment of the form
Rob Pike's avatar
Rob Pike committed
2861
</p>
2862

2863 2864 2865
<pre>
x, ok = <-ch;  // or: x, ok := <-ch
</pre>
2866

Rob Pike's avatar
Rob Pike committed
2867 2868 2869 2870 2871 2872 2873 2874 2875
<p>
the receive operation becomes non-blocking.
If the operation can proceeed, the boolean variable
<code>ok</code> will be set to <code>true</code>
and the value stored in <code>x</code>; otherwise
<code>ok</code> is set
to <code>false</code> and <code>x</code> is set to the
zero value for its type (§The zero value).
</p>
2876

Rob Pike's avatar
Rob Pike committed
2877 2878 2879 2880
<p>
<font color=red>TODO: Probably in a separate section, communication semantices
need to be presented regarding send, receive, select, and goroutines.</font>
</p>
2881

2882
<h3>Constant expressions</h3>
Robert Griesemer's avatar
Robert Griesemer committed
2883

2884 2885 2886 2887 2888 2889 2890 2891
<p>
Constant expressions may contain only constants, <code>iota</code>,
numeric literals, string literals, and
some constant-valued built-in functions such as <code>unsafe.Sizeof</code>
and <code>len</code> applied to an array.
In practice, constant expressions are those that can be evaluated at compile time.
<p>
The type of a constant expression is determined by the type of its
Rob Pike's avatar
Rob Pike committed
2892
elements.  If it contains only numeric literals, its type is <i>ideal
2893 2894
integer</i> or <i>ideal float</i> (§Ideal number).  Whether a literal
is an integer or float depends on the syntax of the literals (123 vs. 123.0).
2895
The nature of the arithmetic
2896 2897 2898 2899
operations within the expression depends, elementwise, on the values;
for example, 3/2 is an integer division yielding 1, while 3./2. is
a floating point division yielding 1.5.  Thus
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2900

2901
<pre>
2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919
const x = 3./2. + 3/2;
</pre>

<p>
yields a floating point constant of ideal float value 2.5 (1.5 +
1); its constituent expressions are evaluated using distinct rules
for division.
</p>

<p>
Intermediate values and the constants themselves
may require precision significantly larger than any concrete type
in the language.  The following are legal declarations:
</p>

<pre>
const Huge = 1 << 100;
const Four int8 = Huge >> 98;
2920
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2921

2922
<p>
2923 2924
A constant expression may appear in any context, such as assignment
to a variable of any numeric type, as long as the value of the
Rob Pike's avatar
Rob Pike committed
2925
expression can be represented accurately in that context.
2926
It is erroneous to assign a value with a non-zero fractional part
Rob Pike's avatar
Rob Pike committed
2927 2928 2929 2930 2931 2932 2933 2934
to an integer, or if the assignment would overflow or underflow,
or in general if the value cannot be represented by the type of
the variable.
For
instance, <code>3</code> can be assigned to any integer variable but also to any
floating point variable, while <code>-1e12</code> can be assigned to a
<code>float32</code>, <code>float64</code>, or even <code>int64</code>
but not <code>uint64</code> or <code>string</code>.
2935
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2936

2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947
<p>
If a typed constant expression evaluates to a value that is not
representable by that type, the compiler reports an error.
</p>

<pre>
uint8(-1)         // error, out of range
uint8(100) * 100  // error, out of range
</pre>

<p>
Russ Cox's avatar
Russ Cox committed
2948 2949 2950
The mask used by the unary bitwise complement operator matches
the rule for non-constants: the mask is the all 1s for unsigned constants
and -1 for signed and ideal constants.
2951 2952 2953 2954 2955 2956 2957
</p>

<pre>
^1          // ideal constant, equal to -2
uint8(^1)   // error, same as uint8(-2), out of range
^uint8(1)   // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)
int8(^1)    // same as int8(-2)
Russ Cox's avatar
Russ Cox committed
2958
^int8(1)    // same as -1 ^ int8(1) = -2
2959 2960 2961 2962 2963 2964 2965 2966
</pre>

<p>
TODO: perhaps ^ should be disallowed on non-uints instead of assuming twos complement.
Also it may be possible to make typed constants more like variables, at the cost of fewer
overflow etc. errors being caught.
</p>

2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
<h3>Order of evaluation</h3>

<p>
When evaluating the elements of an assignment or expression,
all function calls, method calls and
communication operations are evaluated in lexical left-to-right
order.  Otherwise, the order of evaluation is unspecified.
</p>

<p>
2977
For example, in the assignment
2978 2979
</p>
<pre>
2980
y[f()], ok = g(h(), i() + x[j()], <-c), k()
2981 2982
</pre>
<p>
2983 2984 2985 2986 2987 2988
the function calls and communication happen in the order
<code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>,
<code><-c</code>, <code>g()</code>, and <code>k()</code>.
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.
2989 2990
</p>

Rob Pike's avatar
Rob Pike committed
2991
<hr/>
Robert Griesemer's avatar
Robert Griesemer committed
2992

2993
<h2>Statements</h2>
2994

Rob Pike's avatar
Rob Pike committed
2995
<p>
2996
Statements control execution.
Rob Pike's avatar
Rob Pike committed
2997
</p>
2998

Rob Pike's avatar
Rob Pike committed
2999
<pre class="grammar">
3000
Statement =
3001 3002 3003 3004
	Declaration | EmptyStmt | LabeledStmt |
	SimpleStmt | GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
	FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
	DeferStmt .
Robert Griesemer's avatar
Robert Griesemer committed
3005

3006
SimpleStmt = ExpressionStmt | IncDecStmt | Assignment | SimpleVarDecl .
3007

Rob Pike's avatar
Rob Pike committed
3008 3009
StatementList = Statement { Separator Statement } .
Separator     = [ ";" ]
3010
</pre>
3011

3012
<p>
Rob Pike's avatar
Rob Pike committed
3013 3014
Elements of a list of statements are separated by semicolons,
which may be omitted only if the previous statement:
Rob Pike's avatar
Rob Pike committed
3015
</p>
3016
<ul>
Rob Pike's avatar
Rob Pike committed
3017 3018
	<li>ends with the closing parenthesis ")" of a list of declarations
	    (§Declarations and Scope); or</li>
3019
	<li>ends with a closing brace "}" that is not part of an expression.
3020
</ul>
3021

3022

3023
<h3>Empty statements</h3>
3024

Rob Pike's avatar
Rob Pike committed
3025
<p>
3026
The empty statement does nothing.
Rob Pike's avatar
Rob Pike committed
3027
</p>
3028

Rob Pike's avatar
Rob Pike committed
3029
<pre class="grammar">
3030
EmptyStmt = .
3031
</pre>
3032

Rob Pike's avatar
Rob Pike committed
3033 3034 3035 3036 3037
<p>
A statement list can always in effect be terminated with a semicolon by
adding an empty statement.
</p>

3038

3039 3040 3041 3042 3043 3044 3045 3046
<h3>Labeled statements</h3>

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

<pre class="grammar">
3047
LabeledStmt = Label ":" Statement .
3048 3049 3050 3051 3052 3053 3054 3055
Label       = identifier .
</pre>

<pre>
Error: log.Fatal("error encountered")
</pre>


3056
<h3>Expression statements</h3>
3057

Rob Pike's avatar
Rob Pike committed
3058 3059 3060 3061 3062 3063
<p>
Function calls, method calls, and channel operations
can appear in statement context.
</p>


Rob Pike's avatar
Rob Pike committed
3064
<pre class="grammar">
3065
ExpressionStmt = Expression .
3066
</pre>
3067

3068 3069
<pre>
f(x+y)
Rob Pike's avatar
Rob Pike committed
3070
<-ch
3071
</pre>
3072 3073


3074
<h3>IncDec statements</h3>
3075

Rob Pike's avatar
Rob Pike committed
3076
<p>
3077
The "++" and "--" statements increment or decrement their operands
Rob Pike's avatar
Rob Pike committed
3078 3079 3080
by the ideal numeric value 1.  As with an assignment, the operand
must be a variable, pointer indirection, field selector or index expression.
</p>
3081

Rob Pike's avatar
Rob Pike committed
3082
<pre class="grammar">
3083
IncDecStmt = Expression ( "++" | "--" ) .
3084
</pre>
3085

Rob Pike's avatar
Rob Pike committed
3086
<p>
3087 3088
The following assignment statements (§Assignments) are semantically
equivalent:
Rob Pike's avatar
Rob Pike committed
3089
</p>
3090

Rob Pike's avatar
Rob Pike committed
3091
<pre class="grammar">
3092 3093 3094 3095
IncDec statement    Assignment
x++                 x += 1
x--                 x -= 1
</pre>
3096

3097
<h3>Assignments</h3>
3098

Rob Pike's avatar
Rob Pike committed
3099
<pre class="grammar">
3100
Assignment = ExpressionList assign_op ExpressionList .
Rob Pike's avatar
Rob Pike committed
3101

3102 3103
assign_op = [ add_op | mul_op ] "=" .
</pre>
3104

Rob Pike's avatar
Rob Pike committed
3105 3106 3107 3108
<p>
Each left-hand side operand must be a variable, pointer indirection,
field selector, or index expression.
</p>
3109

3110 3111 3112 3113 3114
<pre>
x = 1
*p = f()
a[i] = 23
k = <-ch
3115
i &amp;^= 1&lt;&lt;n
3116
</pre>
3117

Rob Pike's avatar
Rob Pike committed
3118 3119 3120 3121 3122 3123 3124
<p>
An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code>
<code>y</code> where <i>op</i> is a binary arithmetic operation is equivalent
to <code>x</code> <code>=</code> <code>x</code> <i>op</i>
<code>y</code> but evalutates <code>x</code>
only once.  The <i>op</i><code>=</code> construct is a single token.
</p>
3125

3126
<pre>
Rob Pike's avatar
Rob Pike committed
3127
a[i] <<= 2
3128
</pre>
3129

Rob Pike's avatar
Rob Pike committed
3130 3131 3132 3133 3134
<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
such as a function evaluation or channel or map operation (§Channel
3135 3136
operations, §Map operations) or a type assertion (§Type assertions).
The number of operands on the left
Rob Pike's avatar
Rob Pike committed
3137 3138 3139
hand side must match the number of values.  For instance, If
<code>f</code> is a function returning two values,
</p>
3140

3141 3142 3143
<pre>
x, y = f()
</pre>
3144

Rob Pike's avatar
Rob Pike committed
3145 3146 3147
<p>
assigns the first value to <code>x</code> and the second to <code>y</code>.
</p>
3148

Rob Pike's avatar
Rob Pike committed
3149 3150
<p>
In the second form, the number of operands on the left must equal the number
3151 3152 3153 3154
of expressions on the right, each of which must be single-valued.
The expressions on the right are evaluated before assigning to
any of the operands on the left, but otherwise the evaluation
order is unspecified.
Rob Pike's avatar
Rob Pike committed
3155
</p>
3156

3157
<pre>
Rob Pike's avatar
Rob Pike committed
3158
a, b = b, a  // exchange a and b
3159
</pre>
Rob Pike's avatar
Rob Pike committed
3160 3161 3162 3163 3164 3165

<p>
In assignments, the type of each value must be assignment compatible
(§Assignment compatibility) with the type of the
operand to which it is assigned.
</p>
3166 3167


3168
<h3>If statements</h3>
3169

Rob Pike's avatar
Rob Pike committed
3170 3171 3172 3173 3174 3175 3176
<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
present, the "else" branch is executed.  A missing condition
is equivalent to <code>true</code>.
</p>
3177

Rob Pike's avatar
Rob Pike committed
3178
<pre class="grammar">
3179
IfStmt    = "if" [ [ SimpleStmt ] ";" ] [ Expression ] Block [ "else" Statement ] .
3180
</pre>
3181

3182 3183 3184 3185 3186
<pre>
if x > 0 {
	return true;
}
</pre>
3187

3188 3189 3190 3191
<p>
An "if" statement may include a simple statement before the expression.
The scope of any variables declared by that statement
extends to the end of the "if" statement
Rob Pike's avatar
Rob Pike committed
3192
and the variables are initialized once before the statement is entered.
3193
</p>
3194

3195 3196 3197 3198 3199 3200 3201 3202 3203
<pre>
if x := f(); x < y {
	return x;
} else if x > z {
	return z;
} else {
	return y;
}
</pre>
3204 3205


3206
<h3>Switch statements</h3>
3207

Rob Pike's avatar
Rob Pike committed
3208 3209
<p>
"Switch" statements provide multi-way execution.
Rob Pike's avatar
Rob Pike committed
3210 3211 3212
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
3213
</p>
3214 3215

<pre class="grammar">
3216
SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
3217 3218
</pre>

Rob Pike's avatar
Rob Pike committed
3219
<p>
Rob Pike's avatar
Rob Pike committed
3220 3221 3222 3223 3224 3225 3226
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.
</p>

3227
<h4>Expression switches</h4>
Rob Pike's avatar
Rob Pike committed
3228 3229 3230 3231 3232

<p>
In an expression switch,
the switch expression is evaluated and
the case expressions, which need not be constants,
3233
are evaluated left-to-right and top-to-bottom; the first one that equals the
Rob Pike's avatar
Rob Pike committed
3234
switch expression
Rob Pike's avatar
Rob Pike committed
3235 3236
triggers execution of the statements of the associated case;
the other cases are skipped.
Rob Pike's avatar
Rob Pike committed
3237 3238
If no case matches and there is a "default" case,
its statements are executed.
Rob Pike's avatar
Rob Pike committed
3239 3240
There can be at most one default case and it may appear anywhere in the
"switch" statement.
3241 3242
A missing expression is equivalent to
the expression <code>true</code>.
Rob Pike's avatar
Rob Pike committed
3243
</p>
3244 3245

<pre class="grammar">
3246
ExprSwitchStmt = "switch" [ [ SimpleStmt ] ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
3247 3248
ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
ExprSwitchCase = "case" ExpressionList | "default" .
3249 3250
</pre>

Rob Pike's avatar
Rob Pike committed
3251 3252 3253
<p>
In a case or default clause,
the last statement only may be a "fallthrough" statement
3254
(§Fallthrough statement) to
Rob Pike's avatar
Rob Pike committed
3255
indicate that control should flow from the end of this clause to
3256
the first statement of the next clause.
Rob Pike's avatar
Rob Pike committed
3257 3258
Otherwise control flows to the end of the "switch" statement.
</p>
3259
<p>
3260
Each case clause acts as a block for scoping purposes
3261
(§Declarations and scope rules).
Rob Pike's avatar
Rob Pike committed
3262
</p>
3263
<p>
3264
A "switch" statement may include a simple statement before the
Rob Pike's avatar
Rob Pike committed
3265
expression.
3266 3267 3268
The scope of any variables declared by that statement
extends to the end of the "switch" statement
and the variables are initialized once before the statement is entered.
Rob Pike's avatar
Rob Pike committed
3269
</p>
3270

3271 3272
<pre>
switch tag {
3273 3274 3275
default: s3()
case 0, 1, 2, 3: s1()
case 4, 5, 6, 7: s2()
3276
}
3277

Rob Pike's avatar
Rob Pike committed
3278
switch x := f(); {
3279 3280
case x &lt; 0: return -x
default: return x
3281
}
3282

Rob Pike's avatar
Rob Pike committed
3283
switch {          // missing expression means "true"
3284 3285 3286
case x < y: f1();
case x < z: f2();
case x == 4: f3();
3287 3288
}
</pre>
3289

3290
<h4>Type switches</h4>
Rob Pike's avatar
Rob Pike committed
3291 3292

<p>
3293 3294 3295
A type switch compares types rather than values. It is otherwise similar
to an expression switch. It is introduced by special
notation in the form of a simple declaration whose right hand side
3296
has the form of a type assertion (§Type assertions)
3297 3298
using the reserved word <code>type</code> rather than an actual type.
Cases then match literal types against the dynamic type of the expression
3299
in the type assertion.
Rob Pike's avatar
Rob Pike committed
3300 3301
</p>

3302
<pre class="grammar">
3303
TypeSwitchStmt  = "switch" [ [ SimpleStmt ] ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
3304 3305
TypeSwitchGuard = identifier ":=" Expression "." "(" "type" ")" .
TypeCaseClause  = TypeSwitchCase ":" [ StatementList ] .
3306
TypeSwitchCase  = "case" ( type | "nil" ) | "default" .
Rob Pike's avatar
Rob Pike committed
3307 3308
</pre>

3309 3310 3311 3312 3313 3314
<p>
If the interface value equals <code>nil</code>,
only an explict <code>nil</code> case or "default"
case will execute.
</p>

Rob Pike's avatar
Rob Pike committed
3315 3316 3317
<p>
Given a function <code>f</code>
that returns a value of interface type,
3318
the following type switch:
Rob Pike's avatar
Rob Pike committed
3319 3320 3321 3322
</p>

<pre>
switch i := f().(type) {
3323 3324
case nil:
	printString("f() returns nil");
Rob Pike's avatar
Rob Pike committed
3325 3326 3327 3328
case int:
	printInt(i);	// i is an int
case float:
	printFloat(i);	// i is a float
3329 3330
case func(int) float:
	printFunction(i);	// i is a function
Rob Pike's avatar
Rob Pike committed
3331 3332 3333
default:
	printString("don't know the type");
}
3334
</pre>
Rob Pike's avatar
Rob Pike committed
3335

3336 3337 3338 3339 3340 3341
<p>
could be rewritten:
</p>

<pre>
v := f();
3342 3343 3344
if v == nil {
	printString("f() returns nil");
} else if i, is_int := v.(int); is_int {
Rob Pike's avatar
Rob Pike committed
3345
	printInt(i);	// i is an int
3346
} else if i, is_float := v.(float); is_float {
Rob Pike's avatar
Rob Pike committed
3347
	printFloat(i);	// i is a float
3348 3349 3350
} else if i, is_func := v.(func(int) float); is_func {
	printFunction(i);	// i is a function
} else {
Rob Pike's avatar
Rob Pike committed
3351 3352 3353
	printString("don't know the type");
}
</pre>
3354

3355 3356 3357 3358 3359 3360
<p>
In a type switch, the guard is mandatory,
there can be only one type per "case", and
the "fallthrough" statement is not allowed.
</p>

3361
<h3>For statements</h3>
3362

Rob Pike's avatar
Rob Pike committed
3363 3364 3365 3366
<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>
3367

Rob Pike's avatar
Rob Pike committed
3368
<pre class="grammar">
3369
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
3370 3371
Condition = Expression .
</pre>
3372

Rob Pike's avatar
Rob Pike committed
3373 3374 3375 3376 3377 3378
<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.
If the condition is absent, it is equivalent to <code>true</code>.
</p>
3379

3380 3381 3382 3383 3384
<pre>
for a &lt; b {
	a *= 2
}
</pre>
3385

Rob Pike's avatar
Rob Pike committed
3386 3387 3388 3389 3390 3391 3392
<p>
A "for" statement with a "for" clause is also controlled by its condition, but
additionally it may specify an <i>init</i>
and a <i>post</i> statement, such as an assignment,
an increment or decrement statement. The init statement (but not the post
statement) may also be a short variable declaration; the scope of the variables
it declares ends at the end of the statement
3393
(§Declarations and scope rules).
Rob Pike's avatar
Rob Pike committed
3394
</p>
3395

Rob Pike's avatar
Rob Pike committed
3396
<pre class="grammar">
3397 3398 3399
ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
InitStmt = SimpleStmt .
PostStmt = SimpleStmt .
3400
</pre>
3401

3402 3403 3404 3405 3406
<pre>
for i := 0; i < 10; i++ {
	f(i)
}
</pre>
3407

3408
<p>
Rob Pike's avatar
Rob Pike committed
3409 3410 3411 3412 3413 3414 3415 3416
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).
Any element of the "for" clause may be empty but the semicolons are
required unless there is only a condition.
If the condition is absent, it is equivalent to <code>true</code>.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3417

3418 3419 3420 3421
<pre>
for ; cond ; { S() }    is the same as    for cond { S() }
for true { S() }        is the same as    for      { S() }
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3422

Rob Pike's avatar
Rob Pike committed
3423 3424
<p>
A "for" statement with a "range" clause
Rob Pike's avatar
Rob Pike committed
3425 3426
iterates through all entries of an array, slice, string or map,
or values received on a channel.
Robert Griesemer's avatar
Robert Griesemer committed
3427 3428
For each entry it first assigns the current index or key to an iteration
variable - or the current (index, element) or (key, value) pair to a pair
Rob Pike's avatar
Rob Pike committed
3429 3430
of iteration variables - and then executes the block.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3431

Rob Pike's avatar
Rob Pike committed
3432
<pre class="grammar">
3433
RangeClause = ExpressionList ( "=" | ":=" ) "range" Expression .
3434
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3435

Rob Pike's avatar
Rob Pike committed
3436
<p>
Rob Pike's avatar
Rob Pike committed
3437 3438
The type of the right-hand expression in the "range" clause must be an
array, slice, string or map, or a pointer to an array, slice, string or map;
3439
or it may be a channel.
Rob Pike's avatar
Rob Pike committed
3440
Except for channels,
3441 3442 3443 3444
the identifier list must contain one or two expressions
(as in assignments, these must be a
variable, pointer indirection, field selector, or index expression)
denoting the
Rob Pike's avatar
Rob Pike committed
3445
iteration variables. On each iteration,
Rob Pike's avatar
Rob Pike committed
3446
the first variable is set to the string, array or slice index or
Robert Griesemer's avatar
Robert Griesemer committed
3447
map key, and the second variable, if present, is set to the corresponding
Rob Pike's avatar
Rob Pike committed
3448
string or array element or map value.
Rob Pike's avatar
Rob Pike committed
3449 3450 3451 3452
The types of the array or slice index (always <code>int</code>)
and element, or of the map key and value respectively,
must be assignment compatible to the iteration variables.
</p>
3453
<p>
Rob Pike's avatar
Rob Pike committed
3454 3455
For strings, the "range" clause iterates over the Unicode code points
in the string.  On successive iterations, the index variable will be the
Rob Pike's avatar
Rob Pike committed
3456
index of successive UTF-8-encoded code points in the string, and
Rob Pike's avatar
Rob Pike committed
3457 3458 3459 3460 3461 3462 3463
the second variable, of type <code>int</code>, will be the value of
the corresponding code point.  If the iteration encounters an invalid
UTF-8 sequence, the second variable will be <code>0xFFFD</code>,
the Unicode replacement character, and the next iteration will advance
a single byte in the string.
</p>
<p>
3464
For channels, the identifier list must contain one identifier.
Robert Griesemer's avatar
Robert Griesemer committed
3465
The iteration receives values sent on the channel until the channel is closed;
3466 3467 3468
it does not process the zero value sent before the channel is closed.
</p>
<p>
Rob Pike's avatar
Rob Pike committed
3469
The iteration variables may be declared by the "range" clause (":="), in which
3470
case their scope ends at the end of the "for" statement (§Declarations and
Rob Pike's avatar
Rob Pike committed
3471
scope rules). In this case their types are set to
3472
<code>int</code> and the array element type, or the map key and value types, respectively.
Rob Pike's avatar
Rob Pike committed
3473 3474 3475
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
3476

3477 3478
<pre>
var a [10]string;
3479
m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6};
3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495

for i, s := range a {
	// type of i is int
	// type of s is string
	// s == a[i]
	g(i, s)
}

var key string;
var val interface {};  // value type of m is assignment-compatible to val
for key, value = range m {
	h(key, value)
}
// key == last map key encountered in iteration
// val == map[key]
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3496

Rob Pike's avatar
Rob Pike committed
3497
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3498 3499
If map entries that have not yet been processed are deleted during iteration,
they will not be processed. If map entries are inserted during iteration, the
3500
behavior is implementation-dependent, but each entry will be processed at most once.
Rob Pike's avatar
Rob Pike committed
3501
</p>
3502

3503
<h3>Go statements</h3>
3504

Rob Pike's avatar
Rob Pike committed
3505
<p>
3506
A "go" statement starts the execution of a function or method call
Rob Pike's avatar
Rob Pike committed
3507 3508 3509
as an independent concurrent thread of control, or <i>goroutine</i>,
within the same address space.
</p>
3510

Rob Pike's avatar
Rob Pike committed
3511
<pre class="grammar">
3512
GoStmt = "go" Expression .
3513
</pre>
3514

Rob Pike's avatar
Rob Pike committed
3515 3516 3517
<p>
The expression must be a call, and
unlike with a regular call, program execution does not wait
3518
for the invoked function to complete.
Rob Pike's avatar
Rob Pike committed
3519
</p>
3520

3521 3522 3523 3524
<pre>
go Server()
go func(ch chan <- bool) { for { sleep(10); ch <- true; }} (c)
</pre>
3525 3526


3527
<h3>Select statements</h3>
3528

Rob Pike's avatar
Rob Pike committed
3529 3530 3531
<p>
A "select" statement chooses which of a set of possible communications
will proceed.  It looks similar to a "switch" statement but with the
3532
cases all referring to communication operations.
Rob Pike's avatar
Rob Pike committed
3533
</p>
3534

Rob Pike's avatar
Rob Pike committed
3535
<pre class="grammar">
3536
SelectStmt = "select" "{" { CommClause } "}" .
3537
CommClause = CommCase ":" StatementList .
3538 3539 3540 3541
CommCase = "case" ( SendExpr | RecvExpr) | "default" .
SendExpr =  Expression "&lt;-" Expression .
RecvExpr =  [ Expression ( "=" | ":=" ) ] "&lt;-" Expression .
</pre>
3542

Rob Pike's avatar
Rob Pike committed
3543
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3544 3545
Each communication clause acts as a block for the purpose of scoping
(§Declarations and scope rules).
Rob Pike's avatar
Rob Pike committed
3546
</p>
3547
<p>
Rob Pike's avatar
Rob Pike committed
3548 3549
For all the send and receive expressions in the "select"
statement, the channel expression is evaluated.  Any expressions
Rob Pike's avatar
Rob Pike committed
3550 3551 3552 3553
that appear on the right hand side of send expressions are also
evaluated. If any of the resulting channels can proceed, one is
chosen and the corresponding communication and statements are
evaluated.  Otherwise, if there is a default case, that executes;
3554
if not, the statement blocks until one of the communications can
Rob Pike's avatar
Rob Pike committed
3555
complete.  The channels and send expressions are not re-evaluated.
Rob Pike's avatar
Rob Pike committed
3556 3557 3558 3559 3560
A channel pointer may be <code>nil</code>,
which is equivalent to that case not
being present in the select statement
except, if a send, its expression is still evaluated.
</p>
3561
<p>
Rob Pike's avatar
Rob Pike committed
3562 3563
Since all the channels and send expressions are evaluated, any side
effects in that evaluation will occur for all the communications
Rob Pike's avatar
Rob Pike committed
3564 3565
in the "select" statement.
</p>
3566
<p>
Rob Pike's avatar
Rob Pike committed
3567
If multiple cases can proceed, a uniform fair choice is made to decide
3568
which single communication will execute.
3569
<p>
Rob Pike's avatar
Rob Pike committed
3570 3571 3572 3573 3574
The receive case may declare a new variable using a short variable declaration
(§Short variable declarations).
The scope of such variables continues to the end of the
respective case's statements.
</p>
3575

3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588
<pre>
var c, c1, c2 chan int;
var i1, i2 int;
select {
case i1 = &lt;-c1:
	print("received ", i1, " from c1\n");
case c2 &lt;- i2:
	print("sent ", i2, " to c2\n");
default:
	print("no communication\n");
}

for {  // send random sequence of bits to c
3589
	select {
3590 3591
	case c &lt;- 0:  // note: no statement, no fallthrough, no folding of cases
	case c &lt;- 1:
3592
	}
3593 3594
}
</pre>
3595

3596
<font color=red>
3597
TODO: Make semantics more precise.
3598
</font>
3599 3600


3601
<h3>Return statements</h3>
3602

Rob Pike's avatar
Rob Pike committed
3603 3604
<p>
A "return" statement terminates execution of the containing function
3605
and optionally provides a result value or values to the caller.
Rob Pike's avatar
Rob Pike committed
3606
</p>
3607

Rob Pike's avatar
Rob Pike committed
3608
<pre class="grammar">
3609
ReturnStmt = "return" [ ExpressionList ] .
3610
</pre>
3611

Rob Pike's avatar
Rob Pike committed
3612 3613 3614 3615 3616
<pre>
func procedure() {
	return
}
</pre>
3617

Rob Pike's avatar
Rob Pike committed
3618 3619 3620
<p>
There are two ways to return values from a function with a result
type.  The first is to explicitly list the return value or values
3621 3622
in the "return" statement.
Normally, the expressions
Rob Pike's avatar
Rob Pike committed
3623 3624 3625
must be single-valued and assignment-compatible to the elements of
the result type of the function.
</p>
3626

3627 3628
<pre>
func simple_f() int {
Rob Pike's avatar
Rob Pike committed
3629 3630 3631 3632 3633
	return 2
}

func complex_f1() (re float, im float) {
	return -7.0, -4.0
3634 3635
}
</pre>
3636

Rob Pike's avatar
Rob Pike committed
3637 3638 3639 3640 3641 3642
<p>
However, if the expression list in the "return" statement is a single call
to a multi-valued function, the values returned from the called function
will be returned from this one.  The result types of the current function
and the called function must match.
</p>
3643

3644
<pre>
Rob Pike's avatar
Rob Pike committed
3645 3646
func complex_f2() (re float, im float) {
	return complex_f1()
3647 3648
}
</pre>
3649

Rob Pike's avatar
Rob Pike committed
3650
<p>
3651
The second way to return values is to use the elements of the
Rob Pike's avatar
Rob Pike committed
3652 3653 3654 3655 3656 3657
result list of the function as variables.  When the function begins
execution, these variables are initialized to the zero values for
their type (§The zero value).  The function can assign them as
necessary; if the "return" provides no values, those of the variables
will be returned to the caller.
</p>
3658

3659
<pre>
Rob Pike's avatar
Rob Pike committed
3660
func complex_f3() (re float, im float) {
3661 3662 3663 3664 3665
	re = 7.0;
	im = 4.0;
	return;
}
</pre>
3666

3667 3668 3669 3670
<p>
TODO: Define when return is required.
</p>

3671
<h3>Break statements</h3>
3672

Rob Pike's avatar
Rob Pike committed
3673 3674 3675 3676
<p>
A "break" statement terminates execution of the innermost
"for", "switch" or "select" statement.
</p>
3677

Rob Pike's avatar
Rob Pike committed
3678
<pre class="grammar">
3679
BreakStmt = "break" [ Label ].
3680
</pre>
3681

Rob Pike's avatar
Rob Pike committed
3682 3683 3684 3685 3686 3687
<p>
If there is a label, it must be that of an enclosing
"for", "switch" or "select" statement, and that is the one whose execution
terminates
(§For statements, §Switch statements, §Select statements).
</p>
3688

3689 3690 3691
<pre>
L: for i < n {
	switch i {
Rob Pike's avatar
Rob Pike committed
3692
		case 5: break L
3693
	}
3694 3695
}
</pre>
3696

3697
<h3>Continue statements</h3>
3698

Rob Pike's avatar
Rob Pike committed
3699 3700 3701 3702
<p>
A "continue" statement begins the next iteration of the
innermost "for" loop at the post statement (§For statements).
</p>
3703

Rob Pike's avatar
Rob Pike committed
3704
<pre class="grammar">
3705
ContinueStmt = "continue" [ Label ].
3706
</pre>
3707

Rob Pike's avatar
Rob Pike committed
3708 3709 3710
<p>
The optional label is analogous to that of a "break" statement.
</p>
3711

3712
<h3>Goto statements</h3>
3713

Rob Pike's avatar
Rob Pike committed
3714 3715 3716
<p>
A "goto" statement transfers control to the statement with the corresponding label.
</p>
3717

Rob Pike's avatar
Rob Pike committed
3718
<pre class="grammar">
3719
GotoStmt = "goto" Label .
3720
</pre>
3721

3722 3723 3724
<pre>
goto Error
</pre>
3725

Rob Pike's avatar
Rob Pike committed
3726 3727
<p>
Executing the "goto" statement must not cause any variables to come into
3728 3729
scope that were not already in scope at the point of the goto.  For
instance, this example:
Rob Pike's avatar
Rob Pike committed
3730
</p>
3731

3732 3733 3734 3735 3736
<pre>
goto L;  // BAD
v := 3;
L:
</pre>
3737

Rob Pike's avatar
Rob Pike committed
3738 3739 3740
<p>
is erroneous because the jump to label <code>L</code> skips
the creation of <code>v</code>.
3741
(TODO: Eliminate in favor of used and not set errors?)
Rob Pike's avatar
Rob Pike committed
3742
</p>
3743

3744
<h3>Fallthrough statements</h3>
3745

Rob Pike's avatar
Rob Pike committed
3746 3747
<p>
A "fallthrough" statement transfers control to the first statement of the
3748 3749 3750
next case clause in a expression "switch" statement (§Expression switches). It may
be used only as the final non-empty statement in a case or default clause in an
expression "switch" statement.
Rob Pike's avatar
Rob Pike committed
3751
</p>
3752

Rob Pike's avatar
Rob Pike committed
3753
<pre class="grammar">
3754
FallthroughStmt = "fallthrough" .
3755
</pre>
3756 3757


3758
<h3>Defer statements</h3>
Robert Griesemer's avatar
Robert Griesemer committed
3759

Rob Pike's avatar
Rob Pike committed
3760 3761 3762 3763
<p>
A "defer" statement invokes a function whose execution is deferred to the moment
the surrounding function returns.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3764

Rob Pike's avatar
Rob Pike committed
3765
<pre class="grammar">
3766
DeferStmt = "defer" Expression .
3767
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3768

Rob Pike's avatar
Rob Pike committed
3769 3770 3771
<p>
The expression must be a function or method call.
Each time the "defer" statement
3772
executes, the parameters to the function call are evaluated and saved anew but the
Robert Griesemer's avatar
Robert Griesemer committed
3773
function is not invoked. Immediately before the innermost function surrounding
Rob Pike's avatar
Rob Pike committed
3774
the "defer" statement returns, but after its return value (if any) is evaluated,
Robert Griesemer's avatar
Robert Griesemer committed
3775 3776
each deferred function is executed with its saved parameters. Deferred functions
are executed in LIFO order.
Rob Pike's avatar
Rob Pike committed
3777
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3778

3779 3780 3781
<pre>
lock(l);
defer unlock(l);  // unlocking happens before surrounding function returns
Robert Griesemer's avatar
Robert Griesemer committed
3782

3783 3784 3785 3786 3787
// prints 3 2 1 0 before surrounding function returns
for i := 0; i &lt;= 3; i++ {
	defer fmt.Print(i);
}
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3788

Rob Pike's avatar
Rob Pike committed
3789
<hr/>
3790

3791
<h2>Predeclared functions</h2>
3792 3793
<ul>
	<li>cap
3794 3795
	<li>close
	<li>closed
3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806
	<li>len
	<li>make
	<li>new
	<li>panic
	<li>panicln
	<li>print
	<li>println
</ul>

<h3>Length and capacity</h3>

Rob Pike's avatar
Rob Pike committed
3807
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
3808
Call       Argument type       Result
3809 3810

len(s)    string, *string      string length (in bytes)
Rob Pike's avatar
Rob Pike committed
3811 3812 3813 3814
          [n]T, *[n]T          array length (== n)
          []T, *[]T            slice length
          map[K]T, *map[K]T    map length
          chan T               number of elements in channel buffer
3815 3816

cap(s)    []T, *[]T            capacity of s
Rob Pike's avatar
Rob Pike committed
3817 3818
          map[K]T, *map[K]T    capacity of s
          chan T               channel buffer capacity
3819
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3820

3821
<p>
Rob Pike's avatar
Rob Pike committed
3822 3823 3824
The type of the result is always <code>int</code> and the
implementation guarantees that
the result always fits into an <code>int</code>.
3825
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3826
The capacity of a slice or map is the number of elements for which there is
Rob Pike's avatar
Rob Pike committed
3827 3828
space allocated in the underlying array (for a slice) or map. For a slice
<code>s</code>, at any time the following relationship holds:
Robert Griesemer's avatar
Robert Griesemer committed
3829

3830 3831 3832
<pre>
0 <= len(s) <= cap(s)
</pre>
3833

3834

3835
<h3>Conversions</h3>
3836

Rob Pike's avatar
Rob Pike committed
3837 3838 3839
<p>
Conversions look like function calls of the form
</p>
3840

Rob Pike's avatar
Rob Pike committed
3841
<pre class="grammar">
3842 3843
T(value)
</pre>
3844

Rob Pike's avatar
Rob Pike committed
3845
<p>
Russ Cox's avatar
Russ Cox committed
3846 3847 3848
where <code>T</code> is a type
and <code>value</code> is an expression
that can be converted to a value
Rob Pike's avatar
Rob Pike committed
3849
of result type <code>T</code>.
3850
<p>
3851
The following conversion rules apply:
Rob Pike's avatar
Rob Pike committed
3852 3853 3854
</p>
<ul>
<li>
3855
1) Between two compatible types (§Type identity and compatibility).
3856
The conversion always succeeds.
Russ Cox's avatar
Russ Cox committed
3857 3858
</li>
<li>
3859 3860 3861 3862 3863 3864
2) Between two types that would be compatible if they
or any of their component types were unnamed (§Type identity and compatibility).
The conversion always succeeds.
</li>
<li>
3) Between integer types.  If the value is a signed quantity, it is
3865 3866
sign extended to implicit infinite precision; otherwise it is zero
extended.  It is then truncated to fit in the result type size.
Rob Pike's avatar
Rob Pike committed
3867 3868 3869 3870
For example, <code>uint32(int8(0xFF))</code> is <code>0xFFFFFFFF</code>.
The conversion always yields a valid value; there is no signal for overflow.
</li>
<li>
3871
4) Between integer and floating point types, or between floating point
3872
types.  To avoid overdefining the properties of the conversion, for
3873
now it is defined as a ``best effort'' conversion.  The conversion
3874
always succeeds but the value may be a NaN or other problematic
3875
result. <font color=red>TODO: clarify?</font>
Rob Pike's avatar
Rob Pike committed
3876 3877
</li>
<li>
3878
5) Strings permit three special conversions:
Rob Pike's avatar
Rob Pike committed
3879 3880
</li>
<li>
3881
5a) Converting an integer value yields a string containing the UTF-8
3882 3883
representation of the integer.

3884 3885 3886
<pre>
string(0x65e5)  // "\u65e5"
</pre>
3887

Rob Pike's avatar
Rob Pike committed
3888 3889
</li>
<li>
3890
5b) Converting a slice of integers yields a string that is the
3891 3892 3893 3894 3895 3896 3897
concatenation of the individual integers converted to strings.
If the slice value is <code>nil</code>, the result is the empty string.
<pre>
string([]int{0x65e5, 0x672c, 0x8a9e})  // "\u65e5\u672c\u8a9e"
</pre>
</li>
<li>
3898
5c) Converting a slice of bytes yields a string whose successive
3899 3900
bytes are those of the slice. If the slice value is <code>nil</code>,
the result is the empty string.
3901

3902
<pre>
3903
string([]byte{'h', 'e', 'l', 'l', 'o'})  // "hello"
3904
</pre>
Rob Pike's avatar
Rob Pike committed
3905 3906
</li>
</ul>
3907

Rob Pike's avatar
Rob Pike committed
3908
<p>
Rob Pike's avatar
Rob Pike committed
3909 3910 3911 3912
There is no linguistic mechanism to convert between pointers and integers.
The <code>unsafe</code> package
implements this functionality under
restricted circumstances (§Package <code>unsafe</code>).
Rob Pike's avatar
Rob Pike committed
3913
</p>
3914 3915


3916
<h3>Allocation</h3>
3917

Rob Pike's avatar
Rob Pike committed
3918 3919 3920
<p>
The built-in function <code>new</code> takes a type <code>T</code> and
returns a value of type <code>*T</code>.
3921
The memory is initialized as described in the section on initial values
Rob Pike's avatar
Rob Pike committed
3922
(§The zero value).
Rob Pike's avatar
Rob Pike committed
3923
</p>
3924

3925 3926 3927
<pre>
new(T)
</pre>
3928

Rob Pike's avatar
Rob Pike committed
3929
<p>
3930
For instance
Rob Pike's avatar
Rob Pike committed
3931
</p>
3932

3933 3934 3935 3936
<pre>
type S struct { a int; b float }
new(S)
</pre>
3937

3938
<p>
Rob Pike's avatar
Rob Pike committed
3939 3940 3941 3942 3943
dynamically allocates memory for a variable of type <code>S</code>,
initializes it (<code>a=0</code>, <code>b=0.0</code>),
and returns a value of type <code>*S</code> containing the address
of the memory.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3944

Rob Pike's avatar
Rob Pike committed
3945
<h3>Making slices, maps and channels</h3>
Robert Griesemer's avatar
Robert Griesemer committed
3946

Rob Pike's avatar
Rob Pike committed
3947 3948 3949 3950 3951 3952 3953
<p>
Slices, maps and channels are reference types that do not require the
extra indirection of an allocation with <code>new</code>.
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>).
Robert Griesemer's avatar
Robert Griesemer committed
3954
The memory is initialized as described in the section on initial values
Rob Pike's avatar
Rob Pike committed
3955
(§The zero value).
Rob Pike's avatar
Rob Pike committed
3956
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3957

3958 3959 3960
<pre>
make(T [, optional list of expressions])
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3961

Rob Pike's avatar
Rob Pike committed
3962
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3963
For instance
Rob Pike's avatar
Rob Pike committed
3964
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3965

3966 3967 3968
<pre>
make(map[string] int)
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3969

Rob Pike's avatar
Rob Pike committed
3970
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3971
creates a new map value and initializes it to an empty map.
Rob Pike's avatar
Rob Pike committed
3972
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3973

Rob Pike's avatar
Rob Pike committed
3974 3975
<p>
The parameters affect sizes for allocating slices, maps, and
Robert Griesemer's avatar
Robert Griesemer committed
3976
buffered channels:
Rob Pike's avatar
Rob Pike committed
3977
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3978

3979 3980 3981 3982 3983
<pre>
s := make([]int, 10, 100);        # slice with len(s) == 10, cap(s) == 100
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
</pre>
3984

Rob Pike's avatar
Rob Pike committed
3985
<hr/>
3986

3987
<h2>Packages</h2>
3988

Rob Pike's avatar
Rob Pike committed
3989 3990 3991
<p>
Go programs are constructed by linking together <i>packages</i>.
A package is in turn constructed from one or more source files that
Rob Pike's avatar
Rob Pike committed
3992
together provide access to a set of types, constants, functions,
Rob Pike's avatar
Rob Pike committed
3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004
and variables.  Those elements may be <i>imported</i> and used in
another package.
</p>

<h3>Source file organization</h3>

<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,
types, variables, and constants.  The source text following the
4005
package clause acts as a block for scoping (§Declarations and scope
Rob Pike's avatar
Rob Pike committed
4006 4007
rules).
</p>
4008

Rob Pike's avatar
Rob Pike committed
4009
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
4010
SourceFile       = PackageClause { ImportDecl [ ";" ] } { Declaration [ ";" ] } .
4011
</pre>
4012

Rob Pike's avatar
Rob Pike committed
4013 4014
<h3>Package clause</h3>

4015
<p>
Rob Pike's avatar
Rob Pike committed
4016 4017 4018
A package clause begins each source file and defines the package
to which the file belongs.
</p>
4019

Rob Pike's avatar
Rob Pike committed
4020
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
4021 4022
PackageClause    = "package" PackageName .
</pre>
4023

Rob Pike's avatar
Rob Pike committed
4024 4025
<pre>
package math
4026
</pre>
4027

Rob Pike's avatar
Rob Pike committed
4028 4029 4030 4031
<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>
4032

Rob Pike's avatar
Rob Pike committed
4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043
<h3>Import</h3>

<p>
A source file gains access to exported identifiers (§Exported
identifiers) from another package through an import declaration.
In the general form, an import declaration provides an identifier
that code in the source file may use to access the imported package's
contents and a file name referring to the (compiled) implementation of
the package.  The file name may be relative to a repository of
installed packages.
</p>
4044

Rob Pike's avatar
Rob Pike committed
4045
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
4046 4047 4048 4049
ImportDecl       = "import" ( ImportSpec | "(" [ ImportSpecList ] ")" ) .
ImportSpecList   = ImportSpec { ";" ImportSpec } [ ";" ] .
ImportSpec       = [ "." | PackageName ] PackageFileName .
PackageFileName  = StringLit .
4050
</pre>
4051

4052
<p>
Rob Pike's avatar
Rob Pike committed
4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066
After an import, in the usual case an exported name <i>N</i> from the imported
package <i>P</i> may be accessed by the qualified identifier
<i>P</i><code>.</code><i>N</i> (§Qualified identifiers).  The actual
name <i>P</i> depends on the form of the import declaration.  If
an explicit package name <code>p1</code> is provided, the qualified
identifer will have the form <code>p1.</code><i>N</i>.  If no name
is provided in the import declaration, <i>P</i> will be the package
name declared within the source files of the imported package.
Finally, if the import declaration uses an explicit period
(<code>.</code>) for the package name, <i>N</i> will appear
in the package-level scope of the current file and the qualified name is
unnecessary and erroneous.  In this form, it is an error if the import introduces
a name conflict.
</p>
4067
<p>
Rob Pike's avatar
Rob Pike committed
4068 4069 4070 4071 4072
In this table, assume we have compiled a package named
<code>math</code>, which exports function <code>Sin</code>, and
installed the compiled package in file
<code>"lib/math"</code>.
</p>
4073

Rob Pike's avatar
Rob Pike committed
4074 4075 4076 4077 4078 4079
<pre class="grammar">
Import syntax               Local name of Sin

import M "lib/math"         M.Sin
import   "lib/math"         math.Sin
import . "lib/math"         Sin
4080
</pre>
4081

Rob Pike's avatar
Rob Pike committed
4082 4083
<h3>Multi-file packages</h3>

4084
<p>
Rob Pike's avatar
Rob Pike committed
4085 4086 4087 4088 4089 4090 4091
If a package is constructed from multiple source files, all names
at package-level scope, not just exported names, are visible to all the
files in the package. An import declaration is still necessary to
declare intention to use the names,
but the imported names do not need a qualified identifer to be
accessed.
</p>
4092

Rob Pike's avatar
Rob Pike committed
4093 4094 4095 4096 4097 4098 4099 4100 4101
<p>
The compilation of a multi-file package may require
that the files be compiled and installed in an order that satisfies
the resolution of names imported within the package.
</p>

<p>
If source file <code>math1.go</code> contains
</p>
4102
<pre>
Rob Pike's avatar
Rob Pike committed
4103 4104 4105 4106 4107
package math

const twoPi = 6.283185307179586

function Sin(x float) float { return ... }
4108
</pre>
4109

4110
<p>
Rob Pike's avatar
Rob Pike committed
4111 4112
and file <code>"math2.go"</code> begins
</p>
4113
<pre>
Rob Pike's avatar
Rob Pike committed
4114 4115 4116
package math

import "lib/math"
4117
</pre>
4118

4119
<p>
Rob Pike's avatar
Rob Pike committed
4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130
then, provided <code>"math1.go"</code> is compiled first and
installed in <code>"lib/math"</code>, <code>math2.go</code>
may refer directly to <code>Sin</code> and <code>twoPi</code>
without a qualified identifier.
</p>

<h3>An example package</h3>

<p>
Here is a complete Go package that implements a concurrent prime sieve.
</p>
4131

4132 4133 4134
<pre>
package main

Rob Pike's avatar
Rob Pike committed
4135 4136
import "fmt"

4137 4138 4139 4140
// Send the sequence 2, 3, 4, ... to channel 'ch'.
func generate(ch chan <- int) {
	for i := 2; ; i++ {
		ch <- i  // Send 'i' to channel 'ch'.
4141
	}
4142 4143 4144 4145
}

// Copy the values from channel 'in' to channel 'out',
// removing those divisible by 'prime'.
4146 4147
func filter(src chan <- int, dst <-chan int, prime int) {
	for i := range src {  // Loop over values received from 'src'.
4148
		if i % prime != 0 {
4149
			dst <- i  // Send 'i' to channel 'dst'.
4150 4151
		}
	}
4152 4153 4154 4155 4156 4157 4158 4159
}

// The prime sieve: Daisy-chain filter processes together.
func sieve() {
	ch := make(chan int);  // Create a new channel.
	go generate(ch);  // Start generate() as a subprocess.
	for {
		prime := <-ch;
Rob Pike's avatar
Rob Pike committed
4160
		fmt.Print(prime, "\n");
4161 4162 4163
		ch1 := make(chan int);
		go filter(ch, ch1, prime);
		ch = ch1
4164
	}
4165
}
4166

4167 4168 4169 4170
func main() {
	sieve()
}
</pre>
4171

Rob Pike's avatar
Rob Pike committed
4172
<hr/>
4173

4174
<h2>Program initialization and execution</h2>
4175

Rob Pike's avatar
Rob Pike committed
4176 4177
<h3>The zero value</h3>
<p>
4178
When memory is allocated to store a value, either through a declaration
Rob Pike's avatar
Rob Pike committed
4179
or <code>new()</code>, and no explicit initialization is provided, the memory is
4180
given a default initialization.  Each element of such a value is
Rob Pike's avatar
Rob Pike committed
4181 4182 4183
set to the zero value for its type: <code>false</code> for booleans,
<code>0</code> for integers, <code>0.0</code> for floats, <code>""</code>
for strings, and <code>nil</code> for pointers and interfaces.
Rob Pike's avatar
Rob Pike committed
4184
This initialization is done recursively, so for instance each element of an
Rob Pike's avatar
Rob Pike committed
4185 4186
array of structs will have its fields zeroed if no value is specified.
</p>
4187
<p>
4188
These two simple declarations are equivalent:
Rob Pike's avatar
Rob Pike committed
4189
</p>
4190

4191 4192 4193 4194
<pre>
var i int;
var i int = 0;
</pre>
4195

Rob Pike's avatar
Rob Pike committed
4196
<p>
4197
After
Rob Pike's avatar
Rob Pike committed
4198
</p>
4199

4200 4201 4202 4203
<pre>
type T struct { i int; f float; next *T };
t := new(T);
</pre>
4204

Rob Pike's avatar
Rob Pike committed
4205
<p>
4206
the following holds:
Rob Pike's avatar
Rob Pike committed
4207
</p>
4208

4209 4210 4211 4212 4213
<pre>
t.i == 0
t.f == 0.0
t.next == nil
</pre>
4214

Rob Pike's avatar
Rob Pike committed
4215 4216 4217 4218 4219 4220 4221 4222
<p>
The same would also be true after
</p>

<pre>
var t T
</pre>

Rob Pike's avatar
Rob Pike committed
4223 4224
<h3>Program execution</h3>
<p>
4225
A package with no imports is initialized by assigning initial values to
Rob Pike's avatar
Rob Pike committed
4226 4227 4228 4229 4230 4231 4232 4233 4234 4235
all its package-level variables in declaration order and then calling any
package-level function with the name and signature of
</p>
<pre>
func init()
</pre>
<p>
defined in its source. Since a package may contain more
than one source file, there may be more than one
<code>init()</code> function in a package, but
4236
only one per source file.
Rob Pike's avatar
Rob Pike committed
4237
</p>
4238
<p>
4239
Initialization code may contain "go" statements, but the functions
4240 4241
they invoke do not begin execution until initialization of the entire
program is complete. Therefore, all initialization code is run in a single
Rob Pike's avatar
Rob Pike committed
4242
goroutine.
Rob Pike's avatar
Rob Pike committed
4243
</p>
4244
<p>
Rob Pike's avatar
Rob Pike committed
4245 4246 4247
An <code>init()</code> function cannot be referred to from anywhere
in a program. In particular, <code>init()</code> cannot be called explicitly,
nor can a pointer to <code>init</code> be assigned to a function variable.
Rob Pike's avatar
Rob Pike committed
4248
</p>
4249
<p>
4250
If a package has imports, the imported packages are initialized
4251
before initializing the package itself. If multiple packages import
Rob Pike's avatar
Rob Pike committed
4252
a package <code>P</code>, <code>P</code> will be initialized only once.
Rob Pike's avatar
Rob Pike committed
4253
</p>
4254
<p>
4255 4256
The importing of packages, by construction, guarantees that there can
be no cyclic dependencies in initialization.
Rob Pike's avatar
Rob Pike committed
4257
</p>
4258
<p>
4259
A complete program, possibly created by linking multiple packages,
Rob Pike's avatar
Rob Pike committed
4260
must have one package called <code>main</code>, with a function
Rob Pike's avatar
Rob Pike committed
4261
</p>
4262

4263
<pre>
Rob Pike's avatar
Rob Pike committed
4264
func main() { ... }
4265
</pre>
4266

Rob Pike's avatar
Rob Pike committed
4267
<p>
Rob Pike's avatar
Rob Pike committed
4268 4269
defined.
The function <code>main.main()</code> takes no arguments and returns no value.
Rob Pike's avatar
Rob Pike committed
4270
</p>
4271
<p>
Rob Pike's avatar
Rob Pike committed
4272
Program execution begins by initializing the <code>main</code> package and then
Rob Pike's avatar
Rob Pike committed
4273 4274
invoking <code>main.main()</code>.
</p>
4275
<p>
Rob Pike's avatar
Rob Pike committed
4276
When <code>main.main()</code> returns, the program exits.
Rob Pike's avatar
Rob Pike committed
4277
</p>
Rob Pike's avatar
Rob Pike committed
4278 4279 4280 4281
<p>
Implementation restriction: The compiler assumes package <code>main</code>
is created by a single source file and that it is not imported by any other package.
</p>
4282

Rob Pike's avatar
Rob Pike committed
4283
<hr/>
4284

4285
<h2>System considerations</h2>
4286

4287
<h3>Package <code>unsafe</code></h3>
4288

4289
<p>
Rob Pike's avatar
Rob Pike committed
4290 4291 4292 4293 4294
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>
must be vetted manually for type safety.  The package provides the
following interface:
4295
</p>
4296

Rob Pike's avatar
Rob Pike committed
4297
<pre class="grammar">
4298
package unsafe
4299

4300 4301
type ArbitraryType int  // shorthand for an arbitrary Go type; it is not a real type
type Pointer *ArbitraryType
4302

4303 4304 4305 4306 4307
func Alignof(variable ArbitraryType) int
func Offsetof(selector ArbitraryType) int
func Reflect(i interface {}) (value uint64, typestring string, indir bool)
func Sizeof(variable ArbitraryType) int
func Unreflect(value uint64, typestring string, indir bool) interface {}
4308
</pre>
4309

4310
<p>
4311 4312 4313
Any pointer or value of type <code>uintptr</code> can be converted into
a <code>Pointer</code> and vice versa.
</p>
4314
<p>
4315
The function <code>Sizeof</code> takes an expression denoting a
Rob Pike's avatar
Rob Pike committed
4316
variable of any (complete) type and returns the size of the variable in bytes.
4317
</p>
4318
<p>
4319
The function <code>Offsetof</code> takes a selector (§Selectors) denoting a struct
4320
field of any type and returns the field offset in bytes relative to the
4321 4322
struct's address. For a struct <code>s</code> with field <code>f</code>:
</p>
4323

4324
<pre>
4325
uintptr(unsafe.Pointer(&amp;s)) + uintptr(unsafe.Offsetof(s.f)) == uintptr(unsafe.Pointer(&amp;s.f))
4326
</pre>
4327

4328
<p>
4329 4330 4331 4332 4333 4334 4335
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>
4336

4337 4338 4339
<pre>
uintptr(unsafe.Pointer(&amp;x)) % uintptr(unsafe.Alignof(x)) == 0
</pre>
4340

4341 4342 4343 4344
<p>
Calls to <code>Alignof</code>, <code>Offsetof</code>, and
<code>Sizeof</code> are constant expressions of type <code>int</code>.
</p>
4345 4346 4347
<p>
<font color=red>TODO describe Reflect, Unreflect</font>
</p>
4348

4349

4350
<h3>Size and alignment guarantees</h3>
4351

4352
For the numeric types (§Numeric types), the following sizes are guaranteed:
4353

Rob Pike's avatar
Rob Pike committed
4354
<pre class="grammar">
4355
type                      size in bytes
4356

4357 4358 4359 4360 4361
byte, uint8, int8         1
uint16, int16             2
uint32, int32, float32    4
uint64, int64, float64    8
</pre>
4362

4363
<p>
4364
The following minimal alignment properties are guaranteed:
Rob Pike's avatar
Rob Pike committed
4365
</p>
4366
<ol>
4367
<li>For a variable <code>x</code> of any type: <code>1 <= unsafe.Alignof(x) <= unsafe.Maxalign</code>.
4368

4369
<li>For a variable <code>x</code> of numeric type: <code>unsafe.Alignof(x)</code> is the smaller
4370
   of <code>unsafe.Sizeof(x)</code> and <code>unsafe.Maxalign</code>, but at least 1.
4371

4372 4373
<li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of
   all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of x, but at least 1.
4374

4375 4376
<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.
4377
</ol>
4378

Rob Pike's avatar
Rob Pike committed
4379 4380 4381 4382 4383
<hr/>

<h2><font color=red>Differences between this doc and implementation - TODO</font></h2>
<p>
<font color=red>
Rob Pike's avatar
Rob Pike committed
4384 4385 4386 4387 4388 4389 4390
Implementation accepts only ASCII digits for digits; doc says Unicode.
<br/>
Implementation does not honor the restriction on goto statements and targets (no intervening declarations).
<br/>
cap() does not work on maps or chans.
<br/>
len() does not work on chans.
4391 4392
<br>
string([]int{...}) conversion is not yet implemented.
Rob Pike's avatar
Rob Pike committed
4393 4394
</font>
</p>
4395

4396 4397 4398
</div>
</body>
</html>