go_spec.html 118 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 11


Todo's:
Robert Griesemer's avatar
Robert Griesemer committed
12
[ ] document illegality of package-external tuple assignments to structs
13
	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
14
	a T struct { a b int }.
15 16 17 18 19 20
[ ] should probably write something about evaluation order of statements even
	though obvious
[ ] string conversion: string([]int{}) vs string(int) conversion. Former is
	"inverse" of string range iteration.
[ ] do we need explicit channel conversion (to change channel direction)?

21

22
Wish list:
23 24
[ ] enum symbols that are not mixable with ints or some other mechanism
	(requirement that basic type aliases need conversion for compatibility)
25
[ ] Helper syntax for composite types: allow names/keys/indices for
26 27
	structs/maps/arrays
[ ] built-in assert() ("conditional panic") (gri)
28 29
-->

30

31
<h2>Introduction</h2>
32

33
<p>
Rob Pike's avatar
Rob Pike committed
34 35 36 37
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>
38

39
<p>
Rob Pike's avatar
Rob Pike committed
40 41 42 43 44 45 46
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>
47

48
<p>
Rob Pike's avatar
Rob Pike committed
49 50 51
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
52
<hr/>
53
<h2>Notation</h2>
Rob Pike's avatar
Rob Pike committed
54
<p>
55
The syntax is specified using Extended Backus-Naur Form (EBNF):
Rob Pike's avatar
Rob Pike committed
56
</p>
57

Rob Pike's avatar
Rob Pike committed
58
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
59 60
Production  = production_name "=" Expression .
Expression  = Alternative { "|" Alternative } .
61
Alternative = Term { Term } .
Rob Pike's avatar
Rob Pike committed
62 63
Term        = production_name | token [ "..." token ] | Group | Option | Repetition .
Group       = "(" Expression ")" .
64
Option      = "[" Expression "]" .
Rob Pike's avatar
Rob Pike committed
65
Repetition  = "{" Expression "}" .
66
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
67

Rob Pike's avatar
Rob Pike committed
68 69 70 71
<p>
Productions are expressions constructed from terms and the following
operators, in increasing precedence:
</p>
Rob Pike's avatar
Rob Pike committed
72
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
73 74 75 76
|   alternation
()  grouping
[]  option (0 or 1 times)
{}  repetition (0 to n times)
77
</pre>
78

79
<p>
Rob Pike's avatar
Rob Pike committed
80 81
Lower-case production names are used to identify lexical tokens.
Non-terminals are in CamelCase. Lexical symbols are enclosed in
82 83
double quotes <code>""</code> (the double quote symbol is written as
<code>'"'</code>).
Rob Pike's avatar
Rob Pike committed
84 85
</p>

86
<p>
87 88
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
89 90
</p>

Rob Pike's avatar
Rob Pike committed
91
<hr/>
Robert Griesemer's avatar
Robert Griesemer committed
92

93
<h2>Source code representation</h2>
94

95
<p>
Rob Pike's avatar
Rob Pike committed
96 97 98 99 100 101
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>
102
<p>
Rob Pike's avatar
Rob Pike committed
103 104 105
Each code point is distinct; for instance, upper and lower case letters
are different characters.
</p>
106

107
<h3>Characters</h3>
108

109
<p>
Rob Pike's avatar
Rob Pike committed
110 111
The following terms are used to denote specific Unicode character classes:
</p>
112
<ul>
Rob Pike's avatar
Rob Pike committed
113 114 115 116
	<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>
117
</ul>
118

119
(The Unicode Standard, Section 4.5 General Category - Normative.)
120

121
<h3>Letters and digits</h3>
Rob Pike's avatar
Rob Pike committed
122 123

<p>
124
The underscore character <code>_</code> (U+005F) is considered a letter.
Rob Pike's avatar
Rob Pike committed
125 126
</>
<pre class="grammar">
127 128 129 130 131
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
132 133 134
<hr/>

<h2>Lexical elements</h2>
135

Rob Pike's avatar
Rob Pike committed
136
<h3>Comments</h3>
137

Rob Pike's avatar
Rob Pike committed
138 139
<p>
There are two forms of comments.  The first starts at the character
140 141 142
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
143 144 145
</p>

<h3>Tokens</h3>
146

Rob Pike's avatar
Rob Pike committed
147 148 149 150 151 152 153 154 155 156
<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>
157

158
<h3>Identifiers</h3>
159

Rob Pike's avatar
Rob Pike committed
160 161 162 163 164 165 166
<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 } .
167 168 169 170 171 172 173
</pre>
<pre>
a
_x9
ThisVariableIsExported
αβ
</pre>
174
Some identifiers are predeclared (§Predeclared identifiers).
175

Rob Pike's avatar
Rob Pike committed
176
<h3>Keywords</h3>
177

Rob Pike's avatar
Rob Pike committed
178 179 180 181 182 183 184 185 186 187
<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>
188

Rob Pike's avatar
Rob Pike committed
189 190 191 192 193 194 195 196 197 198 199
<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
200
     &amp;^          &amp;^=
Rob Pike's avatar
Rob Pike committed
201 202 203 204 205 206 207
</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
208 209 210
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
211 212 213 214 215 216
</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 } .
217 218 219 220 221 222 223 224
</pre>

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

Rob Pike's avatar
Rob Pike committed
226 227 228 229 230
<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
231
decimal digits; the exponent part is an <code>e</code> or <code>E</code>
Rob Pike's avatar
Rob Pike committed
232 233 234 235 236 237 238 239
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 ] .
240 241 242 243 244 245 246 247 248 249 250 251 252
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>
253

Rob Pike's avatar
Rob Pike committed
254 255
<h3>Ideal numbers</h3>

256
<p>
Rob Pike's avatar
Rob Pike committed
257 258 259 260 261 262 263
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
numbers</i> have no size or type and cannot overflow.  However,
when (used in an expression) assigned to a variable or typed constant,
the destination must be able to represent the assigned value.
</p>
264
<p>
265
Implementation restriction: A compiler may implement ideal numbers
Rob Pike's avatar
Rob Pike committed
266 267
by choosing an internal representation with at least twice the precision
of any machine type.
Rob Pike's avatar
Rob Pike committed
268
</p>
269

Rob Pike's avatar
Rob Pike committed
270
<h3>Character literals</h3>
271

Rob Pike's avatar
Rob Pike committed
272
<p>
Rob Pike's avatar
Rob Pike committed
273 274 275 276 277 278
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
279
</p>
280
<p>
Rob Pike's avatar
Rob Pike committed
281 282 283
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
284 285 286 287
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
288
</p>
289
<p>
Rob Pike's avatar
Rob Pike committed
290 291
Several backslash escapes allow arbitrary values to be represented
as ASCII text.  There are four ways to represent the integer value
292 293 294 295
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
296 297 298
In each case the value of the literal is the value represented by
the digits in the corresponding base.
</p>
299
<p>
Rob Pike's avatar
Rob Pike committed
300 301 302
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
303
by construction). The `Unicode' escapes <code>\u</code> and <code>\U</code>
Rob Pike's avatar
Rob Pike committed
304
represent Unicode code points so within them some values are illegal,
305
in particular those above <code>0x10FFFF</code> and surrogate halves.
Rob Pike's avatar
Rob Pike committed
306
</p>
307
<p>
Rob Pike's avatar
Rob Pike committed
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
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>
336 337 338 339 340 341 342 343 344 345 346 347 348
<pre>
'a'
'ä'
'本'
'\t'
'\000'
'\007'
'\377'
'\x07'
'\xff'
'\u12e4'
'\U00101234'
</pre>
349

Rob Pike's avatar
Rob Pike committed
350 351 352 353
<p>
The value of a character literal is an ideal integer, just as with
integer literals.
</p>
354

Rob Pike's avatar
Rob Pike committed
355 356 357
<h3>String literals</h3>

<p>
358
String literals represent constant values of type <code>string</code>.
Rob Pike's avatar
Rob Pike committed
359 360 361 362 363
There are two forms: raw string literals and interpreted string
literals.
</p>
<p>
Raw string literals are character sequences between back quotes
364
<code>``</code>.  Within the quotes, any character is legal except
Rob Pike's avatar
Rob Pike committed
365 366 367 368 369 370
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
371
quotes <code>&quot;&quot;</code>. The text between the quotes forms the
Rob Pike's avatar
Rob Pike committed
372
value of the literal, with backslash escapes interpreted as they
373 374 375
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
376 377
<i>bytes</i> of the resulting string; all other escapes represent
the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
378 379 380 381
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
382 383 384 385 386 387
U+00FF.
</p>

<pre class="grammar">
string_lit             = raw_string_lit | interpreted_string_lit .
raw_string_lit         = "`" { unicode_char } "`" .
388 389
interpreted_string_lit = """ { unicode_value | byte_value } """ .
</pre>
390

391 392 393 394 395 396 397 398 399 400 401
<pre>
`abc`
`\n`
"hello, world\n"
"\n"
""
"Hello, world!\n"
"日本語"
"\u65e5本\U00008a9e"
"\xff\u00FF"
</pre>
402

Rob Pike's avatar
Rob Pike committed
403
<p>
404
These examples all represent the same string:
Rob Pike's avatar
Rob Pike committed
405
</p>
406

407
<pre>
Rob Pike's avatar
Rob Pike committed
408 409 410 411
"日本語"                                 // 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
412 413
"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"  // The explicit UTF-8 bytes
</pre>
414

415
<p>
416 417 418 419 420
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
421 422
</p>
<hr/>
423

424
<h2>Types</h2>
425

426
<p>
Rob Pike's avatar
Rob Pike committed
427
A type determines the set of values and operations specific to values of that type.
Rob Pike's avatar
Rob Pike committed
428 429 430 431
A type may be specified by a (possibly qualified (§Qualified identifiers))
type name (§Type declarations) or a <i>type literal</i>,
which composes a new type in terms of previously declared types.
</p>
432

Rob Pike's avatar
Rob Pike committed
433
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
434 435 436 437
Type      = TypeName | TypeLit | "(" Type ")" .
TypeName  = QualifiedIdent.
TypeLit   = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
	    SliceType | MapType | ChannelType .
438
</pre>
439

440
<p>
Rob Pike's avatar
Rob Pike committed
441 442 443
<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
444
channels.
Rob Pike's avatar
Rob Pike committed
445
</p>
446

447
<p>
Rob Pike's avatar
Rob Pike committed
448
At any point in the source code, a type may be <i>complete</i> or
Rob Pike's avatar
Rob Pike committed
449 450 451 452 453 454
<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
455 456
(TODO: Need to figure out how forward declarations of
interface fit in here.)
Rob Pike's avatar
Rob Pike committed
457 458 459 460 461
</p>
<p>
The <i>interface</i> of a type is the set of methods bound to it
(§Method declarations); for pointer types, it is the interface
of the pointer base type (§Pointer types). All types have an interface;
Robert Griesemer's avatar
Robert Griesemer committed
462
if they have no methods, it is the <i>empty interface</i>.
Rob Pike's avatar
Rob Pike committed
463 464 465 466 467 468 469 470 471 472
</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
with the static type of the interface variable.  For non-interfaces
types, the dynamic type is always the static type.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
473

474
<h3>Basic types</h3>
475

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

480
<h3>Numeric types</h3>
481

Rob Pike's avatar
Rob Pike committed
482 483 484
<p>
The architecture-independent numeric types are:
</p>
485

Rob Pike's avatar
Rob Pike committed
486
<pre class="grammar">
487 488 489 490
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)
491

492 493 494 495
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)
496

497 498
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
499 500

byte     familiar alias for uint8
501
</pre>
502

Rob Pike's avatar
Rob Pike committed
503
<p>
504 505 506
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
507
</p>
508

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

514 515 516 517 518 519 520
<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>
521

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

531

532
<h3>Booleans</h3>
533

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

538

539
<h3>Strings</h3>
540

541
<p>
Rob Pike's avatar
Rob Pike committed
542 543 544 545 546 547 548 549 550 551 552
The <code>string</code> type represents the set of textual string values.
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>.
553
</p>
554

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

562
<pre>
Rob Pike's avatar
Rob Pike committed
563 564
"Alea iacta est."
"Alea " /* The die */ `iacta est` /* is cast */ "."
565
</pre>
566

Russ Cox's avatar
Russ Cox committed
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 624 625 626
<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.
627
The <i>capacity</i> is a measure of that extent: it is the sum of
Russ Cox's avatar
Russ Cox committed
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 656 657 658
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>
659

Russ Cox's avatar
Russ Cox committed
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
<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>


680
<h3>Struct types</h3>
681

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

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

696
<pre>
697 698
// An empty struct.
struct {}
699

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

Rob Pike's avatar
Rob Pike committed
709 710 711
<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
712 713
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
714
a pointer or interface type. The unqualified type name acts as the field identifier.
Rob Pike's avatar
Rob Pike committed
715
</p>
716

717 718 719 720 721
<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
722 723
	P.T3;      // the field name is T3
	*P.T4;     // the field name is T4
724
	x, y int;
725
}
726 727
</pre>

Rob Pike's avatar
Rob Pike committed
728
<p>
729 730 731
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
732
</p>
733

734
<pre>
735 736 737 738 739
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
}
740
</pre>
741

742
<p>
Rob Pike's avatar
Rob Pike committed
743 744 745 746 747 748 749 750 751 752
Fields and methods (§Method declarations) of an anonymous field are
promoted to be ordinary fields and methods of the struct (§Selectors).
</p>
<p>
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
field declaration. The tags are made
visible through a reflection library (TODO: reference?)
but are otherwise ignored.
</p>
753

754
<pre>
755
// A struct corresponding to the EventIdMessage protocol buffer.
Rob Pike's avatar
Rob Pike committed
756
// The tag strings define the protocol buffer field numbers.
757
struct {
Rob Pike's avatar
Rob Pike committed
758 759 760
	time_usec uint64 "field 1";
	server_ip uint32 "field 2";
	process_id uint32 "field 3";
761
}
762
</pre>
763

764
<h3>Pointer types</h3>
765

Rob Pike's avatar
Rob Pike committed
766
<p>
767
A pointer type denotes the set of all pointers to variables of a given
768
type, called the <i>base type</i> of the pointer.
Rob Pike's avatar
Rob Pike committed
769
A pointer value may be <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
770
</p>
771

Rob Pike's avatar
Rob Pike committed
772
<pre class="grammar">
773 774
PointerType = "*" BaseType .
BaseType = Type .
775
</pre>
776

777
<pre>
778
*int
Rob Pike's avatar
Rob Pike committed
779
*map[string] *chan int
780
</pre>
781

782
<h3>Function types</h3>
783

Rob Pike's avatar
Rob Pike committed
784
<p>
785
A function type denotes the set of all functions with the same parameter
Rob Pike's avatar
Rob Pike committed
786 787 788
and result types.
A function value may be <code>nil</code>.
</p>
789 790

<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
791 792 793 794 795 796
FunctionType   = "func" Signature .
Signature      = Parameters [ Result ] .
Result         = Parameters | CompleteType .
Parameters     = "(" [ ParameterList ] ")" .
ParameterList  = ParameterDecl { "," ParameterDecl } .
ParameterDecl  = [ IdentifierList ] ( CompleteType | "..." ) .
797 798 799
</pre>

<p>
Rob Pike's avatar
Rob Pike committed
800 801 802 803 804 805 806 807 808 809 810 811
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
812
zero or more additional arguments of any
Rob Pike's avatar
Rob Pike committed
813 814 815
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>
816 817

<pre>
818 819 820 821 822 823 824 825 826
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))
827 828 829
</pre>


830
<h3>Interface types</h3>
831

Rob Pike's avatar
Rob Pike committed
832 833 834 835 836 837
<p>
An interface type specifies an unordered set of methods. A variable
of interface type can store, dynamically, any value that implements
at least that set of methods.
An interface value may be <code>nil</code>.
</p>
838 839

<pre class="grammar">
Russ Cox's avatar
Russ Cox committed
840
InterfaceType      = "interface" "{" [ MethodSpecList ] "}" .
Rob Pike's avatar
Rob Pike committed
841 842 843
MethodSpecList     = MethodSpec { ";" MethodSpec } [ ";" ] .
MethodSpec         = IdentifierList Signature | InterfaceTypeName .
InterfaceTypeName  = TypeName .
844
</pre>
845 846

<pre>
Rob Pike's avatar
Rob Pike committed
847
// A simple File interface
848 849 850
interface {
	Read, Write	(b Buffer) bool;
	Close		();
851 852
}
</pre>
853

Rob Pike's avatar
Rob Pike committed
854 855 856 857 858 859 860
<p>
Any type (including interface types) whose interface includes,
possibly as a subset, the complete set of methods of an interface <code>I</code>
is said to implement interface <code>I</code>.
For instance, if two types <code>S1</code> and <code>S2</code>
have the methods
</p>
861

862
<pre>
863 864 865
func (p T) Read(b Buffer) bool { return ... }
func (p T) Write(b Buffer) bool { return ... }
func (p T) Close() { ... }
866
</pre>
867

Rob Pike's avatar
Rob Pike committed
868 869 870 871 872 873
<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>
874

Rob Pike's avatar
Rob Pike committed
875 876 877 878 879
<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>
880

881
<pre>
Rob Pike's avatar
Rob Pike committed
882
interface { }
883
</pre>
884

Rob Pike's avatar
Rob Pike committed
885 886 887 888 889
<p>
Similarly, consider this interface specification,
which appears within a type declaration (§Type declarations)
to define an interface called <code>Lock</code>:
</p>
890 891 892 893 894

<pre>
type Lock interface {
	Lock, Unlock	();
}
895
</pre>
896

Rob Pike's avatar
Rob Pike committed
897 898 899
<p>
If <code>S1</code> and <code>S2</code> also implement
</p>
Robert Griesemer's avatar
Robert Griesemer committed
900

901 902 903 904 905
<pre>
func (p T) Lock() { ... }
func (p T) Unlock() { ... }
</pre>

906
<p>
Rob Pike's avatar
Rob Pike committed
907 908 909 910 911 912 913 914 915 916
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>
917

918 919 920 921
<pre>
type ReadWrite interface {
	Read, Write	(b Buffer) bool;
}
922

923 924 925 926 927 928
type File interface {
	ReadWrite;  // same as enumerating the methods in ReadWrite
	Lock;       // same as enumerating the methods in Lock
	Close();
}
</pre>
929

930
<h3>Map types</h3>
931

Rob Pike's avatar
Rob Pike committed
932 933 934 935 936 937 938 939 940
<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>
941

Rob Pike's avatar
Rob Pike committed
942
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
943 944 945
MapType     = "map" "[" KeyType "]" ValueType .
KeyType     = CompleteType .
ValueType   = CompleteType .
946
</pre>
947

948
<p>
Rob Pike's avatar
Rob Pike committed
949 950 951 952 953 954 955 956
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>
957

958
<pre>
959 960 961
map [string] int
map [*T] struct { x, y float }
map [string] interface {}
962
</pre>
963

Rob Pike's avatar
Rob Pike committed
964 965 966 967
<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.
968
The value of an uninitialized map is <code>nil</code>.
Rob Pike's avatar
Rob Pike committed
969 970 971 972 973 974
</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
975
capacity hint as arguments:
Rob Pike's avatar
Rob Pike committed
976
</p>
977

978
<pre>
979 980
make(map[string] int)
make(map[string] int, 100)
981
</pre>
982

983 984 985 986 987 988
<p>
The initial capacity does not bound its size:
maps grow to accommodate the number of items
stored in them.
</p>

989
<h3>Channel types</h3>
990

Rob Pike's avatar
Rob Pike committed
991
<p>
992
A channel provides a mechanism for two concurrently executing functions
Rob Pike's avatar
Rob Pike committed
993 994 995 996 997
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>
998

999
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
1000 1001 1002 1003
ChannelType   = Channel | SendChannel | RecvChannel .
Channel       = "chan" ValueType .
SendChannel   = "chan" "&lt;-" ValueType .
RecvChannel   = "&lt;-" "chan" ValueType .
1004
</pre>
1005

Rob Pike's avatar
Rob Pike committed
1006 1007
<p>
Upon creation, a channel can be used both to send and to receive values.
1008
By conversion or assignment, a channel may be constrained only to send or
Rob Pike's avatar
Rob Pike committed
1009 1010 1011
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>
1012

1013
<pre>
Rob Pike's avatar
Rob Pike committed
1014
chan T         // can be used to send and receive values of type T
1015
chan &lt;- float  // can only be used to send floats
Rob Pike's avatar
Rob Pike committed
1016
&lt;-chan int     // can only be used to receive ints
1017
</pre>
1018

Rob Pike's avatar
Rob Pike committed
1019 1020 1021
<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>,
1022
which takes the channel type and an optional capacity as arguments:
Rob Pike's avatar
Rob Pike committed
1023
</p>
1024

1025

1026
<pre>
1027
make(chan int, 100)
1028
</pre>
1029

Rob Pike's avatar
Rob Pike committed
1030 1031
<p>
The capacity, in number of elements, sets the size of the buffer in the channel. If the
1032
capacity is greater than zero, the channel is asynchronous and, provided the
Rob Pike's avatar
Rob Pike committed
1033 1034 1035
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>
1036

1037 1038 1039 1040 1041 1042 1043 1044 1045
<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
1046
<h2>General properties of types and values</h2>
1047 1048

<p>
Rob Pike's avatar
Rob Pike committed
1049 1050 1051 1052
Types may be <i>different</i>, <i>structurally equal</i> (or just <i>equal</i>),
or <i>identical</i>.
Go is <i>type safe</i>: different types cannot be mixed
in binary operations and values cannot be assigned to variables of different
1053
types. Values can be assigned to variables of equal type.
Rob Pike's avatar
Rob Pike committed
1054 1055 1056 1057
</p>

<h3>Type equality and identity </h3>

1058 1059
<p>
Two type names denote equal types if the types in the corresponding declarations
Rob Pike's avatar
Rob Pike committed
1060 1061 1062 1063
are equal (§Declarations and Scope).
Two type literals specify equal types if they have the same
literal structure and corresponding components have equal types.
In detail:
1064
</p>
Rob Pike's avatar
Rob Pike committed
1065

1066
<ul>
Rob Pike's avatar
Rob Pike committed
1067
	<li>Two pointer types are equal if they have equal base types.</li>
1068

Rob Pike's avatar
Rob Pike committed
1069 1070
	<li>Two array types are equal if they have equal element types and
	  the same array length.</li>
1071

Rob Pike's avatar
Rob Pike committed
1072 1073 1074
	<li>Two struct types are equal if they have the same sequence of fields,
	    with the same names and equal types. Two anonymous fields are
	    considered to have the same name.</li>
1075

1076 1077
	<li>Two function types are equal if they have the same number of parameters
	  and result values and if corresponding parameter and result types are
Rob Pike's avatar
Rob Pike committed
1078 1079
	  the same. All "..." parameters have equal type.
	  Parameter and result names are not required to match.</li>
1080

Rob Pike's avatar
Rob Pike committed
1081
	<li>Two slice types are equal if they have equal element types.</li>
1082

1083
	<li>Two channel types are equal if they have equal value types and
Rob Pike's avatar
Rob Pike committed
1084
	  the same direction.</li>
1085

Rob Pike's avatar
Rob Pike committed
1086
	<li>Two map types are equal if they have equal key and value types.</li>
1087

1088
	<li>Two interface types are equal if they have the same set of methods
Rob Pike's avatar
Rob Pike committed
1089 1090
	  with the same names and equal function types. The order
	  of the methods is irrelevant.</li>
1091 1092 1093
</ul>

<p>
Rob Pike's avatar
Rob Pike committed
1094 1095 1096 1097 1098 1099 1100 1101
Type identity is more stringent than type equality.
It requires for type names
that they originate in the same type declaration, while for equality it requires
only that they originate in equal type declarations.
Also, the names of parameters and results must match for function types.
In all other respects, the definition of type identity is the
same as for type equality listed above but with ``identical''
substitued for ``equal''.
1102 1103
</p>
<p>
Rob Pike's avatar
Rob Pike committed
1104 1105
By definition, identical types are also equal types.
Two types are different if they are not equal.
1106
</p>
1107

1108
<p>
Rob Pike's avatar
Rob Pike committed
1109 1110
Given the declarations
</p>
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

<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
)
1121
</pre>
1122

Rob Pike's avatar
Rob Pike committed
1123
<p>
Russ Cox's avatar
Russ Cox committed
1124
these types are equal:
Rob Pike's avatar
Rob Pike committed
1125
</p>
1126

1127
<pre>
1128
T0 and T0
Rob Pike's avatar
Rob Pike committed
1129
T0 and T1
1130 1131
T0 and []string
T4 and T5
Russ Cox's avatar
Russ Cox committed
1132
T3 and struct { a int; c int }
1133
</pre>
1134

Rob Pike's avatar
Rob Pike committed
1135
<p>
Russ Cox's avatar
Russ Cox committed
1136 1137 1138 1139 1140 1141
<code>T2</code> and <code>T3</code> are not equal because
they have different field names.
</p>

<p>
These types are identical:
Rob Pike's avatar
Rob Pike committed
1142
</p>
1143

1144
<pre>
1145 1146 1147
T0 and T0
[]int and []int
struct { a, b *T5 } and struct { a, b *T5 }
1148
</pre>
1149

Rob Pike's avatar
Rob Pike committed
1150 1151 1152 1153
<p>
<code>T0</code> and <code>T1</code> are equal but not
identical because they have distinct declarations.
</p>
1154

Rob Pike's avatar
Rob Pike committed
1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
<h3>Assignment compatibility</h3>

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

<h3>Comparison compatibility</h3>

<p>
Values of any type may be compared to other values of equal static
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>
1199 1200
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
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219
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>
1220
Function values are equal if they refer to the same function.
Rob Pike's avatar
Rob Pike committed
1221 1222
</li>
<li>
1223
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
1224 1225 1226
(§Making slices, maps, and channels).
</li>
<li>
1227 1228
Interface values may be compared if they have the same static type.
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
1229 1230
</li>
</ul>
1231
<hr/>
1232 1233


1234 1235 1236 1237 1238 1239 1240
<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>
1241

Rob Pike's avatar
Rob Pike committed
1242
<pre class="grammar">
1243
Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
1244
</pre>
1245

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
<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>
1267

1268 1269 1270
<p>
The scope of an identifier depends on the entity declared:
</p>
1271

1272 1273
<ol>
	<li> The scope of predeclared identifiers is the universe scope.</li>
1274

1275
	<li> The scope of an identifier denoting a type, function or package
1276 1277
	     extends from the point of the identifier in the declaration
	     to the end of the innermost surrounding block.</li>
1278

1279
	<li> The scope of a constant or variable extends textually from
1280
	     the end of its declaration to the end of the innermost
1281
	     surrounding block. If the variable is declared in the
1282
	     <i>init</i> statement of an <code>if</code>,  <code>for</code>,
1283 1284 1285
	     or  <code>switch </code> statement, the
	     innermost surrounding block is the block associated
	     with that statement.</li>
1286

1287 1288
	<li> The scope of a parameter or result is the body of the
	     corresponding function.</li>
1289

1290 1291
	<li> The scope of a field or method is selectors for the
	     corresponding type containing the field or method (§Selectors).</li>
1292

1293
	<li> The scope of a label is a special scope emcompassing
1294
	     the body of the innermost surrounding function, excluding
Rob Pike's avatar
Rob Pike committed
1295
	     nested functions.  Labels do not conflict with non-label identifiers.</li>
1296
</ol>
1297

1298
<h3>Predeclared identifiers</h3>
1299

1300 1301 1302 1303 1304
<p>
The following identifiers are implicitly declared in the outermost scope:
</p>
<pre class="grammar">
Basic types:
1305 1306
	bool byte float32 float64 int8 int16 int32 int64
	string uint8 uint16 uint32 uint64
1307

Rob Pike's avatar
Rob Pike committed
1308
Architecture-specific convenience types:
1309
	float int uint uintptr
1310

1311 1312
Constants:
	true false iota nil
1313

1314
Functions:
1315
	cap len make new panic panicln print println
1316

1317
Packages:
1318
	sys (TODO: does sys endure?)
1319
</pre>
1320

1321
<h3>Exported identifiers</h3>
Robert Griesemer's avatar
Robert Griesemer committed
1322

1323
<p>
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
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>
1334
<p>
1335 1336
it will be exported automatically.
</p>
1337

1338
<h3>Const declarations</h3>
1339

1340 1341 1342 1343 1344 1345 1346 1347
<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>
1348

Rob Pike's avatar
Rob Pike committed
1349
<pre class="grammar">
1350 1351
ConstDecl      = "const" ( ConstSpec | "(" [ ConstSpecList ] ")" ) .
ConstSpecList  = ConstSpec { ";" ConstSpec } [ ";" ] .
Russ Cox's avatar
Russ Cox committed
1352
ConstSpec      = IdentifierList [ [ CompleteType ] "=" ExpressionList ] .
1353

1354 1355
IdentifierList = identifier { "," identifier } .
ExpressionList = Expression { "," Expression } .
1356

1357
CompleteType = Type .
1358
</pre>
1359

1360 1361 1362
<p>
If the type (CompleteType) is omitted, the constants take the
individual types of the corresponding expressions, which may be
1363
<i>ideal integer</i> or <i>ideal float</i> (§Ideal number).  If the type
1364 1365 1366 1367
is present, all constants take the type specified, and the types
of all the expressions must be assignment-compatible
with that type.
</p>
1368

1369
<pre>
1370 1371 1372 1373 1374 1375 1376 1377
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
1378
</pre>
1379

1380 1381 1382 1383
<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
1384
first preceding non-empty expression list, and its type if any.
1385 1386 1387 1388
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
1389 1390
(§Iota) this mechanism permits light-weight declaration of sequential values:
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1391

1392
<pre>
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
const (
	Sunday = iota;
	Monday;
	Tuesday;
	Wednesday;
	Thursday;
	Friday;
	Partyday;
	numberOfDays;  // this constant is not exported
)
1403
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
1404 1405


1406
<h3>Iota</h3>
1407

1408
<p>
1409 1410 1411 1412 1413 1414
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>
1415

1416
<pre>
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
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)
1437
</pre>
1438

1439
<p>
1440 1441 1442
Within an ExpressionList, the value of each <code>iota</code> is the same because
it is only incremented at a semicolon:
</p>
1443

1444
<pre>
1445 1446 1447 1448 1449
const (
	bit0, mask0 = 1 << iota, 1 << iota - 1;  // bit0 == 1, mask0 == 0
	bit1, mask1;                             // bit1 == 2, mask1 == 1
	bit2, mask2;                             // bit2 == 4, mask2 == 3
)
1450
</pre>
1451

1452
<p>
1453 1454 1455
This last example exploits the implicit repetition of the
last non-empty expression list.
</p>
1456 1457


1458
<h3>Type declarations</h3>
1459

1460 1461 1462 1463
<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>
1464

Rob Pike's avatar
Rob Pike committed
1465
<pre class="grammar">
1466 1467
TypeDecl     = "type" ( TypeSpec | "(" [ TypeSpecList ] ")" ) .
TypeSpecList = TypeSpec { ";" TypeSpec } [ ";" ] .
Russ Cox's avatar
Russ Cox committed
1468
TypeSpec     = identifier ( Type | "struct" | "interface" ) .
1469
</pre>
1470

1471
<pre>
1472
type IntArray [16] int
1473

1474 1475 1476 1477
type (
	Point struct { x, y float };
	Polar Point
)
1478

Russ Cox's avatar
Russ Cox committed
1479 1480
type Comparable interface

1481 1482
type TreeNode struct {
	left, right *TreeNode;
Russ Cox's avatar
Russ Cox committed
1483
	value *Comparable;
1484 1485 1486 1487 1488
}

type Comparable interface {
	cmp(Comparable) int
}
1489
</pre>
1490

1491 1492 1493 1494 1495
<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
1496
The type must be complete (§Types).
1497 1498 1499 1500 1501 1502
</p>
<pre class="grammar">
VarDecl     = "var" ( VarSpec | "(" [ VarSpecList ] ")" ) .
VarSpecList = VarSpec { ";" VarSpec } [ ";" ] .
VarSpec     = IdentifierList ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
</pre>
1503

1504
<pre>
1505 1506 1507 1508 1509 1510 1511 1512
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"
)
1513
</pre>
1514

1515
<p>
1516 1517 1518 1519
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
1520
of the type (§The zero value).
1521 1522
The expressions can be general expressions; they need not be constants.
</p>
1523
<p>
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
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>
1536

1537 1538 1539 1540
<pre>
var i = 0       // i has type int
var f = 3.1415  // f has type float
</pre>
1541

1542
<h3>Short variable declarations</h3>
1543

1544
A <i>short variable declaration</i> uses the syntax
1545

Rob Pike's avatar
Rob Pike committed
1546
<pre class="grammar">
1547
SimpleVarDecl = IdentifierList ":=" ExpressionList .
1548
</pre>
1549

1550
and is shorthand for the declaration syntax
1551

1552 1553
<pre class="grammar">
"var" IdentifierList = ExpressionList .
1554
</pre>
1555

1556
<pre>
1557 1558
i, j := 0, 10;
f := func() int { return 7; }
1559
ch := make(chan int);
1560
</pre>
1561

1562
<p>
1563 1564 1565
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
1566
as a call to a multi-valued function.  In this form, the ExpressionList
1567 1568 1569 1570
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>
1571

1572
<pre>
1573
r, w := os.Pipe(fd);  // os.Pipe() returns two values
1574
</pre>
1575

Rob Pike's avatar
Rob Pike committed
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
<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
1590
<p>
1591 1592 1593 1594
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
1595
</p>
1596

1597
<h3>Function declarations</h3>
1598

1599 1600 1601
<p>
A function declaration binds an identifier to a function (§Function types).
</p>
1602

1603 1604 1605
<pre class="grammar">
FunctionDecl = "func" identifier Signature [ Block ] .
</pre>
1606

1607 1608 1609 1610 1611 1612 1613 1614
<pre>
func min(x int, y int) int {
	if x &lt; y {
		return x;
	}
	return y;
}
</pre>
1615

1616 1617 1618 1619
<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>
1620

1621
<h3>Method declarations</h3>
1622

1623
<p>
1624 1625
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
1626
</p>
1627 1628 1629 1630 1631
<pre class="grammar">
MethodDecl = "func" Receiver identifier Signature [ Block ] .
Receiver = "(" [ identifier ] [ "*" ] TypeName ")" .
</pre>

1632
<p>
1633 1634 1635 1636 1637 1638 1639
The receiver type must be a type name or a pointer to a type name,
and that name is called the <i>receiver base type</i> or just <i>base type</i>.
The base type must not be a pointer type and must be
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
1640
</p>
1641

1642 1643 1644 1645 1646
<p>
All methods bound to a base type must have the same receiver type,
either all pointers to the base type or all the base type itself.
Given type <code>Point</code>, the declarations
</p>
1647

1648 1649 1650 1651
<pre>
func (p *Point) Length() float {
	return Math.sqrt(p.x * p.x + p.y * p.y);
}
1652

1653 1654 1655 1656 1657
func (p *Point) Scale(factor float) {
	p.x = p.x * factor;
	p.y = p.y * factor;
}
</pre>
1658

1659 1660 1661 1662
<p>
bind the methods <code>Length</code> and <code>Scale</code>
to the base type <code>Point</code>.
</p>
1663

1664
<p>
1665 1666 1667 1668 1669
If the
receiver's value is not referenced inside the the body of the method,
its identifier may be omitted in the declaration. The same applies in
general to parameters of functions and methods.
</p>
1670

1671 1672 1673 1674 1675 1676
<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>
1677

Rob Pike's avatar
Rob Pike committed
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
<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>

1691
<h3>Forward declarations</h3>
1692

1693
<p>
Rob Pike's avatar
Rob Pike committed
1694
Mutually-recursive types require that one be
1695 1696 1697 1698
<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>
1699

1700
<pre>
1701 1702 1703 1704 1705 1706 1707 1708
type List struct  // forward declaration of List
type Item struct {
	value int;
	next *List;
}
type List struct {
	head, tail *Item
}
1709
</pre>
1710 1711 1712
<p>
A forward-declared type is incomplete (§Types)
until it is fully declared. The full declaration must follow
1713 1714
before the end of the block containing the forward declaration;
it cannot be contained in an inner block.
1715 1716 1717 1718
</p>
<p>
Functions and methods may similarly be forward-declared by omitting their body.
</p>
1719
<pre>
1720 1721 1722 1723 1724 1725 1726 1727
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)
}
1728
</pre>
1729

Rob Pike's avatar
Rob Pike committed
1730
<hr/>
1731

1732
<h2>Expressions</h2>
1733

1734
<p>
Rob Pike's avatar
Rob Pike committed
1735 1736 1737 1738
An expression specifies the computation of a value by applying
operators and functions to operands. An expression has a value and
a type.
</p>
1739

1740
<h3>Operands</h3>
1741 1742 1743

Operands denote the elementary values in an expression.

Rob Pike's avatar
Rob Pike committed
1744
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
1745 1746 1747 1748
Operand    = Literal | QualifiedIdent | "(" Expression ")" .
Literal    = BasicLit | CompositeLit | FunctionLit .
BasicLit   = int_lit | float_lit | char_lit | StringLit .
StringLit  = string_lit { string_lit } .
1749
</pre>
1750 1751


1752
<h3>Constants</h3>
Robert Griesemer's avatar
Robert Griesemer committed
1753

Rob Pike's avatar
Rob Pike committed
1754
<p>
1755 1756 1757 1758 1759 1760
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
1761
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1762

1763
<h3>Qualified identifiers</h3>
1764

1765
<p>
Rob Pike's avatar
Rob Pike committed
1766 1767
A qualified identifier is an identifier qualified by a package name prefix.
</p>
1768

Rob Pike's avatar
Rob Pike committed
1769
<pre class="grammar">
1770
QualifiedIdent = [ ( LocalPackageName | PackageName ) "." ] identifier .
Rob Pike's avatar
Rob Pike committed
1771
LocalPackageName = identifier .
1772 1773
PackageName = identifier .
</pre>
1774

Rob Pike's avatar
Rob Pike committed
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
<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>
1791

1792 1793 1794
TODO: 6g does not implement LocalPackageName.  Is this new?
Is it needed?

1795
<h3>Composite literals</h3>
1796

Rob Pike's avatar
Rob Pike committed
1797 1798 1799 1800
<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
1801
followed by a brace-bound list of expressions,
1802
or a list of key-value pairs for map literals.
Rob Pike's avatar
Rob Pike committed
1803
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1804

Rob Pike's avatar
Rob Pike committed
1805
<pre class="grammar">
1806
CompositeLit  = LiteralType "{" [ ( ExpressionList | KeyValueList ) [ "," ] ] "}" .
Rob Pike's avatar
Rob Pike committed
1807 1808
LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
                SliceType | MapType | TypeName .
1809 1810
KeyValueList  = KeyValueExpr { "," KeyValueExpr } .
KeyValueExpr  = Expression ":" Expression .
1811
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
1812

Rob Pike's avatar
Rob Pike committed
1813 1814
<p>
The LiteralType must be a struct, array, slice, or map type.
1815 1816 1817 1818 1819
(The grammar enforces this constraint except when the type is given
as a TypeName.)
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.
Rob Pike's avatar
Rob Pike committed
1820
</p>
1821

1822 1823 1824 1825
<pre>
type Rat struct { num, den int }
type Num struct { r Rat; f float; s string }
</pre>
1826

Rob Pike's avatar
Rob Pike committed
1827 1828 1829
<p>
one may write
</p>
1830

1831
<pre>
1832 1833 1834 1835
pi := Num{Rat{22, 7}, 3.14159, "pi"}
</pre>

<p>
Rob Pike's avatar
Rob Pike committed
1836 1837
Taking the address of a composite literal (§Address operators)
generates a unique pointer to an instance of the literal's value.
1838 1839 1840
</p>
<pre>
var pi_ptr *Rat = &amp;Rat{22, 7}
1841
</pre>
1842

Rob Pike's avatar
Rob Pike committed
1843
<p>
1844 1845
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
1846
elements are set to the zero value for the array element type.
Rob Pike's avatar
Rob Pike committed
1847 1848 1849 1850
It is an error to provide more elements than specified in the type. The
notation <code>...</code> specifies an array length equal
to the number of elements in the literal.
</p>
1851

1852
<pre>
1853 1854 1855
buffer := [10]string{};               // len(buffer) == 10
primes := [6]int{2, 3, 5, 7, 9, 11};  // len(primes) == 6
days := [...]string{"Sat", "Sun"};    // len(days) == 2
1856
</pre>
1857

Rob Pike's avatar
Rob Pike committed
1858 1859
<p>
A slice literal describes the entire underlying array literal.
1860
Thus, the length and capacity of a slice literal is the number of elements
Rob Pike's avatar
Rob Pike committed
1861 1862
(of the array) provided in the literal. A slice literal has the form
</p>
1863

1864
<pre>
1865
[]T{x1, x2, ... xn}
1866
</pre>
1867

Rob Pike's avatar
Rob Pike committed
1868 1869 1870
<p>
and is a shortcut for a slice operation applied to an array literal:
</p>
1871

1872
<pre>
1873
[n]T{x1, x2, ... xn}[0 : n]
1874
</pre>
1875

Rob Pike's avatar
Rob Pike committed
1876 1877
<p>
In map literals only, the list contains
1878
key-value pairs separated by a colon:
Rob Pike's avatar
Rob Pike committed
1879
</p>
1880

1881
<pre>
1882
m := map[string]int{"good": 0, "bad": 1, "indifferent": 7};
1883
</pre>
1884

1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
<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>

1900
<h3>Function literals</h3>
1901

Rob Pike's avatar
Rob Pike committed
1902 1903 1904 1905
<p>
A function literal represents an anonymous function.
It consists of a specification of the function type and a function body.
</p>
1906

Rob Pike's avatar
Rob Pike committed
1907
<pre class="grammar">
1908
FunctionLit   = FunctionType Block .
1909
Block         = "{" StatementList "}" .
1910
</pre>
1911

1912
<pre>
Rob Pike's avatar
Rob Pike committed
1913
func (a, b int, z float) bool { return a*b &lt; int(z) }
1914
</pre>
1915

Rob Pike's avatar
Rob Pike committed
1916 1917 1918
<p>
A function literal can be assigned to a variable or invoked directly.
</p>
1919

1920
<pre>
Rob Pike's avatar
Rob Pike committed
1921 1922
f := func(x, y int) int { return x + y }
func(ch chan int) { ch &lt;- ACK } (reply_chan)
1923
</pre>
1924

Rob Pike's avatar
Rob Pike committed
1925 1926
<p>
Function literals are <i>closures</i>: they may refer to variables
1927 1928
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
1929 1930
as they are accessible.
</p>
1931

1932

1933
<h3>Primary expressions</h3>
1934

Rob Pike's avatar
Rob Pike committed
1935
<pre class="grammar">
1936 1937 1938 1939 1940
PrimaryExpr =
	Operand |
	PrimaryExpr Selector |
	PrimaryExpr Index |
	PrimaryExpr Slice |
1941
	PrimaryExpr TypeAssertion |
1942 1943
	PrimaryExpr Call .

1944 1945 1946 1947 1948
Selector       = "." identifier .
Index          = "[" Expression "]" .
Slice          = "[" Expression ":" Expression "]" .
TypeAssertion  = "." "(" Type ")" .
Call           = "(" [ ExpressionList ] ")" .
1949 1950 1951 1952 1953 1954 1955 1956
</pre>


<pre>
x
2
(s + ".txt")
f(3.1415, true)
1957
Point{1, 2}
1958 1959 1960 1961 1962 1963 1964 1965 1966
m["foo"]
s[i : j + 1]
obj.color
Math.sin
f.p[i].x()
</pre>


<h3>Selectors</h3>
1967

Rob Pike's avatar
Rob Pike committed
1968
<p>
Robert Griesemer's avatar
Robert Griesemer committed
1969
A primary expression of the form
Rob Pike's avatar
Rob Pike committed
1970
</p>
Robert Griesemer's avatar
Robert Griesemer committed
1971

1972 1973 1974
<pre>
x.f
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
1975

1976
<p>
Rob Pike's avatar
Rob Pike committed
1977 1978 1979 1980 1981 1982 1983
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>
1984
<p>
Rob Pike's avatar
Rob Pike committed
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
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>
1997
<p>
1998
The following rules apply to selectors:
Rob Pike's avatar
Rob Pike committed
1999 2000 2001 2002 2003 2004 2005 2006 2007
</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
2008
expression is illegal.
Rob Pike's avatar
Rob Pike committed
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
</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>
2020
<p>
Rob Pike's avatar
Rob Pike committed
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
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>
2033
<p>
Rob Pike's avatar
Rob Pike committed
2034 2035
For example, given the declarations:
</p>
2036

2037 2038 2039 2040
<pre>
type T0 struct {
	x int;
}
2041

2042
func (recv *T0) M0()
2043

2044 2045 2046
type T1 struct {
	y int;
}
2047

2048
func (recv T1) M1()
2049

2050 2051 2052 2053 2054
type T2 struct {
	z int;
	T1;
	*T0;
}
Robert Griesemer's avatar
Robert Griesemer committed
2055

2056
func (recv *T2) M2()
Robert Griesemer's avatar
Robert Griesemer committed
2057

2058 2059
var p *T2;  // with p != nil and p.T1 != nil
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2060

Rob Pike's avatar
Rob Pike committed
2061 2062 2063
<p>
one may write:
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2064

2065 2066 2067 2068
<pre>
p.z         // (*p).z
p.y         // ((*p).T1).y
p.x         // (*(*p).T0).x
Robert Griesemer's avatar
Robert Griesemer committed
2069

2070 2071 2072 2073
p.M2        // (*p).M2
p.M1        // ((*p).T1).M1
p.M0        // ((*p).T0).M0
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2074 2075


2076
<font color=red>
2077
TODO: Specify what happens to receivers.
2078
</font>
Robert Griesemer's avatar
Robert Griesemer committed
2079

2080

2081
<h3>Indexes</h3>
2082

Rob Pike's avatar
Rob Pike committed
2083
<p>
Robert Griesemer's avatar
Robert Griesemer committed
2084
A primary expression of the form
Rob Pike's avatar
Rob Pike committed
2085
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2086

2087 2088 2089
<pre>
a[x]
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2090

Rob Pike's avatar
Rob Pike committed
2091
<p>
Rob Pike's avatar
Rob Pike committed
2092 2093 2094
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
2095
rules apply:
Rob Pike's avatar
Rob Pike committed
2096
</p>
2097
<p>
Rob Pike's avatar
Rob Pike committed
2098 2099
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
2100
</p>
2101
<ul>
Rob Pike's avatar
Rob Pike committed
2102 2103 2104
	<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>
2105 2106
</ul>
<p>
Rob Pike's avatar
Rob Pike committed
2107 2108
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
2109
</p>
2110
<ul>
2111
	<li><code>x</code>'s type must be equal to the key type of <code>M</code>
Rob Pike's avatar
Rob Pike committed
2112 2113 2114
	  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>
2115
</ul>
Robert Griesemer's avatar
Robert Griesemer committed
2116

2117
<p>
Rob Pike's avatar
Rob Pike committed
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146
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
2147

Rob Pike's avatar
Rob Pike committed
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
<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>
2158

2159
<h3>Slices</h3>
2160

Rob Pike's avatar
Rob Pike committed
2161
<p>
Rob Pike's avatar
Rob Pike committed
2162
Strings, arrays, and slices can be <i>sliced</i> to construct substrings or descriptors
Robert Griesemer's avatar
Robert Griesemer committed
2163 2164
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
2165 2166
difference in the index values in the slice.  After slicing the array <code>a</code>
</p>
2167

2168
<pre>
2169
a := [4]int{1, 2, 3, 4};
2170 2171
s := a[1:3];
</pre>
2172

Rob Pike's avatar
Rob Pike committed
2173
<p>
2174
the slice <code>s</code> has type <code>[]int</code>, length 2, capacity 3, and elements
Rob Pike's avatar
Rob Pike committed
2175
</p>
2176

2177 2178 2179 2180
<pre>
s[0] == 2
s[1] == 3
</pre>
2181

Rob Pike's avatar
Rob Pike committed
2182
<p>
Rob Pike's avatar
Rob Pike committed
2183
The slice length must be non-negative.
2184
For arrays or strings, the indexes
Rob Pike's avatar
Rob Pike committed
2185 2186
<code>lo</code> and <code>hi</code> must satisfy
0 &lt;= <code>lo</code> &lt;= <code>hi</code> &lt;= length;
2187
for slices, the upper bound is the capacity rather than the length.
2188
<p>
Rob Pike's avatar
Rob Pike committed
2189
If the sliced operand is a string, the result of the slice operation is another, new
Robert Griesemer's avatar
Robert Griesemer committed
2190 2191
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
2192
</p>
2193 2194


2195
<h3>Type assertions</h3>
2196

Rob Pike's avatar
Rob Pike committed
2197 2198 2199
<p>
For an expression <code>x</code> and a type <code>T</code>, the primary expression
</p>
2200

2201 2202 2203
<pre>
x.(T)
</pre>
2204

2205
<p>
Rob Pike's avatar
Rob Pike committed
2206
asserts that the value stored in <code>x</code> is of type <code>T</code>.
2207 2208
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
2209 2210
</p>
<p>
2211
More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
Rob Pike's avatar
Rob Pike committed
2212 2213
that the dynamic type of <code>x</code> is identical to the type <code>T</code>
(§Type equality and identity).
2214
If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
Rob Pike's avatar
Rob Pike committed
2215 2216 2217
of <code>T</code> implements the interface <code>T</code> (§Interface types).
<font color=red>TODO: gri wants an error if x is already of type T.</font>
</p>
2218
<p>
2219 2220
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
2221
exception occurs. In other words, even though the dynamic type of <code>x</code>
2222
is known only at run-time, the type of <code>x.(T)</code> is
Rob Pike's avatar
Rob Pike committed
2223 2224
known to be <code>T</code> in a correct program.
</p>
2225
<p>
2226
If a type assertion is used in an assignment of one of the special forms,
Rob Pike's avatar
Rob Pike committed
2227
</p>
2228

2229 2230 2231 2232
<pre>
v, ok = x.(T)
v, ok := x.(T)
</pre>
2233

2234
<p>
2235 2236
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
2237 2238 2239
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.
2240
The type assertion in this construct thus acts like a function call
Rob Pike's avatar
Rob Pike committed
2241 2242
returning a value and a boolean indicating success.  (§Assignments)
</p>
2243

2244

2245
<h3>Calls</h3>
2246

2247
<p>
Rob Pike's avatar
Rob Pike committed
2248 2249
Given an expression <code>f</code> of function type
<code>F</code>,
Rob Pike's avatar
Rob Pike committed
2250
</p>
2251

2252
<pre>
Rob Pike's avatar
Rob Pike committed
2253
f(a1, a2, ... an)
2254
</pre>
2255

2256
<p>
Rob Pike's avatar
Rob Pike committed
2257 2258 2259
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
2260 2261 2262 2263 2264 2265 2266
<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>
2267

2268
<pre>
Rob Pike's avatar
Rob Pike committed
2269 2270 2271
Atan2(x, y)    // function call
var pt *Point;
pt.Scale(3.5)  // method call with receiver pt
2272
</pre>
2273

Rob Pike's avatar
Rob Pike committed
2274 2275 2276 2277 2278 2279
<p>
If the receiver type of the method is declared as a pointer of type <code>*T</code>,
the actual receiver may be a value of type <code>T</code>;
in such cases method invocation implicitly takes the
receiver's address:
</p>
2280

2281
<pre>
Rob Pike's avatar
Rob Pike committed
2282 2283
var p Point;
p.Scale(3.5)
2284
</pre>
2285

2286
<p>
2287
There is no distinct method type and there are no method literals.
Rob Pike's avatar
Rob Pike committed
2288
</p>
2289

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

Rob Pike's avatar
Rob Pike committed
2292 2293 2294 2295 2296 2297 2298 2299
<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>
2300

2301
<p>
Rob Pike's avatar
Rob Pike committed
2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
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>
2312

Rob Pike's avatar
Rob Pike committed
2313 2314 2315
<p>
Given the function and call
</p>
2316
<pre>
Rob Pike's avatar
Rob Pike committed
2317 2318
func Fprintf(f io.Write, format string, args ...)
Fprintf(os.Stdout, "%s %d", "hello", 23);
2319
</pre>
2320

Rob Pike's avatar
Rob Pike committed
2321 2322 2323 2324 2325
<p>
Within <code>Fprintf</code>, the dynamic type of <code>args</code> for this
call will be, schematically,
<code> struct { string; int }</code>.
</p>
2326 2327


Rob Pike's avatar
Rob Pike committed
2328 2329 2330 2331 2332
<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.
2333

2334
<h3>Operators</h3>
2335

Rob Pike's avatar
Rob Pike committed
2336
<p>
2337
Operators combine operands into expressions.
Rob Pike's avatar
Rob Pike committed
2338
</p>
2339

Rob Pike's avatar
Rob Pike committed
2340
<pre class="grammar">
2341
Expression = UnaryExpr | Expression binary_op UnaryExpr .
Rob Pike's avatar
Rob Pike committed
2342
UnaryExpr  = PrimaryExpr | unary_op UnaryExpr .
2343

Rob Pike's avatar
Rob Pike committed
2344 2345 2346 2347 2348
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
2349
mul_op     = "*" | "/" | "%" | "&lt;&lt;" | ">>" | "&amp;" | "&amp;^" .
2350

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

2354
<p>
Rob Pike's avatar
Rob Pike committed
2355 2356
The operand types in binary operations must be equal, with the following exceptions:
</p>
2357
<ul>
Rob Pike's avatar
Rob Pike committed
2358
	<li>Except in shift expressions, if one operand has numeric type and the other operand is
2359
	  an ideal number, the ideal number is converted to match the type of
Rob Pike's avatar
Rob Pike committed
2360
	  the other operand (§Expressions).</li>
2361

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

Rob Pike's avatar
Rob Pike committed
2366 2367 2368 2369
	<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>

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

2373
	<li>When comparing two operands of channel type, the channel value types
Rob Pike's avatar
Rob Pike committed
2374
	  must be equal but the channel direction is ignored.</li>
2375
</ul>
2376

2377
<p>
Rob Pike's avatar
Rob Pike committed
2378 2379 2380 2381 2382 2383 2384 2385 2386
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
2387
operators, comparison operators, communication operators,
Rob Pike's avatar
Rob Pike committed
2388 2389
<code>&amp;&amp;</code> (logical and), and finally <code>||</code> (logical or):
</p>
2390

Rob Pike's avatar
Rob Pike committed
2391
<pre class="grammar">
2392
Precedence    Operator
Rob Pike's avatar
Rob Pike committed
2393
    6             *  /  %  &lt;&lt;  >>  &amp;  &amp;^
2394 2395 2396 2397 2398 2399
    5             +  -  |  ^
    4             ==  !=  &lt;  &lt;=  >  >=
    3             &lt;-
    2             &amp;&amp;
    1             ||
</pre>
2400

Rob Pike's avatar
Rob Pike committed
2401
<p>
2402
Binary operators of the same precedence associate from left to right.
Rob Pike's avatar
Rob Pike committed
2403 2404
For instance, <code>x / y / z</code> is the same as <code>(x / y) / z</code>.
</p>
2405
<p>
Rob Pike's avatar
Rob Pike committed
2406 2407
Examples:
</p>
2408

2409 2410 2411 2412 2413 2414 2415 2416
<pre>
+x
23 + 3*x[i]
x &lt;= f()
^a >> b
f() || g()
x == y + 1 &amp;&amp; &lt;-chan_ptr > 0
</pre>
2417 2418


2419 2420
<h3>Arithmetic operators</h3>
<p>
2421
Arithmetic operators apply to numeric types and yield a result of the same
Rob Pike's avatar
Rob Pike committed
2422 2423 2424 2425 2426
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>
2427

Rob Pike's avatar
Rob Pike committed
2428
<pre class="grammar">
2429 2430 2431 2432 2433
+    sum                    integers, floats, strings
-    difference             integers, floats
*    product                integers, floats
/    quotient               integers, floats
%    remainder              integers
2434

2435 2436 2437 2438
&amp;    bitwise and            integers
|    bitwise or             integers
^    bitwise xor            integers
&amp;^   bit clear (and not)    integers
2439

2440 2441
<<   left shift             integer << unsigned integer
>>   right shift            integer >> unsigned integer
2442
</pre>
2443

Rob Pike's avatar
Rob Pike committed
2444 2445 2446 2447
<p>
Strings can be concatenated using the <code>+</code> operator
or the <code>+=</code> assignment operator:
</p>
2448

2449
<pre>
Rob Pike's avatar
Rob Pike committed
2450 2451
s := "hi" + string(c);
s += " and good bye";
2452
</pre>
2453

2454
<p>
Rob Pike's avatar
Rob Pike committed
2455 2456 2457 2458 2459
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>
2460

2461 2462 2463
<pre>
(a / b) * b + a % b == a
</pre>
2464

Rob Pike's avatar
Rob Pike committed
2465 2466
<p>
with <code>(a / b)</code> truncated towards zero.
2467
Examples:
Rob Pike's avatar
Rob Pike committed
2468
</p>
2469

2470 2471 2472 2473 2474 2475 2476
<pre>
 x     y     x / y     x % y
 5     3       1         2
-5     3      -1        -2
 5    -3      -1         2
-5    -3       1        -2
</pre>
2477

Rob Pike's avatar
Rob Pike committed
2478 2479
<p>
If the dividend is positive and the divisor is a constant power of 2,
2480 2481
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
2482
</p>
2483

2484 2485 2486 2487 2488
<pre>
 x     x / 4     x % 4     x >> 2     x &amp; 3
 11      2         3         2          3
-11     -2        -3        -3          1
</pre>
2489

Rob Pike's avatar
Rob Pike committed
2490
<p>
2491 2492
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
2493 2494 2495 2496 2497 2498 2499 2500
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>
2501

Rob Pike's avatar
Rob Pike committed
2502 2503 2504
<p>
For integer operands, the unary operators
<code>+</code>, <code>-</code>, and <code>^</code> are defined as
Robert Griesemer's avatar
Robert Griesemer committed
2505
follows:
Rob Pike's avatar
Rob Pike committed
2506
</p>
2507

Rob Pike's avatar
Rob Pike committed
2508
<pre class="grammar">
2509 2510 2511 2512
+x                          is 0 + x
-x    negation              is 0 - x
^x    bitwise complement    is m ^ x  with m = "all bits set to 1"
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2513

2514 2515 2516 2517 2518
<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
2519

2520
<h3>Integer overflow</h3>
Robert Griesemer's avatar
Robert Griesemer committed
2521

Rob Pike's avatar
Rob Pike committed
2522 2523 2524 2525 2526
<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
2527
(§Numeric types). Loosely speaking, these unsigned integer operations
Robert Griesemer's avatar
Robert Griesemer committed
2528
discard high bits upon overflow, and programs may rely on ``wrap around''.
Rob Pike's avatar
Rob Pike committed
2529
</p>
2530
<p>
Rob Pike's avatar
Rob Pike committed
2531 2532
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
2533 2534
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
2535
No exception is raised as a result of overflow. A
Robert Griesemer's avatar
Robert Griesemer committed
2536
compiler may not optimize code under the assumption that overflow does
Rob Pike's avatar
Rob Pike committed
2537 2538
not occur. For instance, it may not assume that <code>x &lt; x + 1</code> is always true.
</p>
2539 2540


2541
<h3>Comparison operators</h3>
2542

Rob Pike's avatar
Rob Pike committed
2543
<p>
2544
Comparison operators yield a boolean result. All comparison operators apply
Rob Pike's avatar
Rob Pike committed
2545 2546 2547 2548
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>
2549

Rob Pike's avatar
Rob Pike committed
2550
<pre class="grammar">
2551 2552 2553 2554 2555 2556 2557
==    equal
!=    not equal
<     less
<=    less or equal
>     greater
>=    greater or equal
</pre>
2558

Rob Pike's avatar
Rob Pike committed
2559 2560 2561 2562
<p>
Numeric basic types are compared in the usual way.
</p>
<p>
2563
Strings are compared byte-wise (lexically).
Rob Pike's avatar
Rob Pike committed
2564
</p>
2565
<p>
2566
Booleans are equal if they are either both "true" or both "false".
Rob Pike's avatar
Rob Pike committed
2567
</p>
2568
<p>
Rob Pike's avatar
Rob Pike committed
2569 2570 2571
The rules for comparison of composite types are described in the
section on §Comparison compatibility.
</p>
2572

2573

2574
<h3>Logical operators</h3>
2575

Rob Pike's avatar
Rob Pike committed
2576
<p>
2577 2578
Logical operators apply to boolean operands and yield a boolean result.
The right operand is evaluated conditionally.
Rob Pike's avatar
Rob Pike committed
2579
</p>
2580

Rob Pike's avatar
Rob Pike committed
2581
<pre class="grammar">
2582 2583 2584 2585
&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>
2586 2587


2588
<h3>Address operators</h3>
2589

Rob Pike's avatar
Rob Pike committed
2590
<p>
Rob Pike's avatar
Rob Pike committed
2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604
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>

2605 2606
<p>
<font color=red>TODO: This text needs to be cleaned up and go elsewhere, there are no address
2607
operators involved.
2608
</font>
Rob Pike's avatar
Rob Pike committed
2609
</p>
2610
<p>
Rob Pike's avatar
Rob Pike committed
2611
Methods are a form of function and a method ``value'' has a function type.
2612
Consider the type T with method M:
Rob Pike's avatar
Rob Pike committed
2613
</p>
2614

2615 2616 2617 2618 2619 2620 2621
<pre>
type T struct {
	a int;
}
func (tp *T) M(a int) int;
var t *T;
</pre>
2622

Rob Pike's avatar
Rob Pike committed
2623
<p>
2624
To construct the value of method M, one writes
Rob Pike's avatar
Rob Pike committed
2625
</p>
2626

2627 2628 2629
<pre>
t.M
</pre>
2630

Rob Pike's avatar
Rob Pike committed
2631
<p>
2632
using the variable t (not the type T).
2633
<font color=red>TODO: It makes perfect sense to be able to say T.M (in fact, it makes more
2634 2635
sense then t.M, since only the type T is needed to find the method M, i.e.,
its address). TBD.
2636
</font>
Rob Pike's avatar
Rob Pike committed
2637
</p>
2638

Rob Pike's avatar
Rob Pike committed
2639
<p>
2640
The expression t.M is a function value with type
Rob Pike's avatar
Rob Pike committed
2641
</p>
2642

2643 2644 2645
<pre>
func (t *T, a int) int
</pre>
2646

Rob Pike's avatar
Rob Pike committed
2647
<p>
2648
and may be invoked only as a function, not as a method:
Rob Pike's avatar
Rob Pike committed
2649
</p>
2650

2651 2652 2653 2654 2655
<pre>
var f func (t *T, a int) int;
f = t.M;
x := f(t, 7);
</pre>
2656

Rob Pike's avatar
Rob Pike committed
2657
<p>
2658
Note that one does not write t.f(7); taking the value of a method demotes
2659
it to a function.
Rob Pike's avatar
Rob Pike committed
2660
</p>
2661

Rob Pike's avatar
Rob Pike committed
2662
<p>
2663
In general, given type T with method M and variable t of type T,
2664
the method invocation
Rob Pike's avatar
Rob Pike committed
2665
</p>
2666

2667 2668 2669
<pre>
t.M(args)
</pre>
2670

Rob Pike's avatar
Rob Pike committed
2671
<p>
2672
is equivalent to the function call
Rob Pike's avatar
Rob Pike committed
2673
</p>
2674

2675 2676 2677
<pre>
(t.M)(t, args)
</pre>
2678

Rob Pike's avatar
Rob Pike committed
2679
<p>
2680
<font color=red>
2681 2682
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.
2683
</font>
Rob Pike's avatar
Rob Pike committed
2684
</p>
2685
<p>
2686
If T is an interface type, the expression t.M does not determine which
2687
underlying type's M is called until the point of the call itself. Thus given
2688
T1 and T2, both implementing interface I with method M, the sequence
Rob Pike's avatar
Rob Pike committed
2689
</p>
2690

2691 2692 2693 2694 2695 2696 2697
<pre>
var t1 *T1;
var t2 *T2;
var i I = t1;
m := i.M;
m(t2, 7);
</pre>
2698

Rob Pike's avatar
Rob Pike committed
2699
<p>
2700
will invoke t2.M() even though m was constructed with an expression involving
2701
t1. Effectively, the value of m is a function literal
Rob Pike's avatar
Rob Pike committed
2702
</p>
2703

2704 2705 2706 2707 2708
<pre>
func (recv I, a int) {
	recv.M(a);
}
</pre>
2709

Rob Pike's avatar
Rob Pike committed
2710
<p>
2711
that is automatically created.
Rob Pike's avatar
Rob Pike committed
2712
</p>
2713 2714
<p>
<font color=red>
2715
TODO: Document implementation restriction: It is illegal to take the address
2716
of a result parameter (e.g.: func f() (x int, p *int) { return 2, &amp;x }).
2717
(TBD: is it an implementation restriction or fact?)
2718
</font>
Rob Pike's avatar
Rob Pike committed
2719
</p>
2720

2721
<h3>Communication operators</h3>
2722

2723
<p>
Rob Pike's avatar
Rob Pike committed
2724 2725
The term <i>channel</i> means "variable of channel type" (§Channel types).
</p>
2726 2727
<p>
The send operation uses the binary operator "&lt;-", which operates on
2728
a channel and a value (expression):
Rob Pike's avatar
Rob Pike committed
2729
</p>
2730

2731 2732 2733
<pre>
ch <- 3
</pre>
2734

Rob Pike's avatar
Rob Pike committed
2735 2736 2737 2738 2739 2740 2741 2742
<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>
2743
<p>
2744 2745 2746
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
2747 2748 2749 2750
false if it did not. (The channel and
the expression to be sent are evaluated regardless.)
These two examples are equivalent:
</p>
2751

2752 2753 2754
<pre>
ok := ch <- 3;
if ok { print("sent") } else { print("not sent") }
2755

2756 2757
if ch <- 3 { print("sent") } else { print("not sent") }
</pre>
2758

Rob Pike's avatar
Rob Pike committed
2759
<p>
2760 2761 2762 2763
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
2764
</p>
2765 2766
<p>
The receive operation uses the prefix unary operator "&lt;-".
Rob Pike's avatar
Rob Pike committed
2767 2768 2769
The value of the expression is the value received, whose type
is the element type of the channel.
</p>
2770

2771 2772 2773
<pre>
<-ch
</pre>
2774

Rob Pike's avatar
Rob Pike committed
2775
<p>
2776
The expression blocks until a value is available, which then can
Rob Pike's avatar
Rob Pike committed
2777 2778 2779 2780
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>
2781

2782 2783 2784 2785 2786 2787
<pre>
v1 := <-ch
v2 = <-ch
f(<-ch)
<-strobe  // wait until clock pulse
</pre>
2788

Rob Pike's avatar
Rob Pike committed
2789
<p>
2790
If a receive expression is used in a tuple assignment of the form
Rob Pike's avatar
Rob Pike committed
2791
</p>
2792

2793 2794 2795
<pre>
x, ok = <-ch;  // or: x, ok := <-ch
</pre>
2796

Rob Pike's avatar
Rob Pike committed
2797 2798 2799 2800 2801 2802 2803 2804 2805
<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>
2806

Rob Pike's avatar
Rob Pike committed
2807 2808 2809 2810
<p>
<font color=red>TODO: Probably in a separate section, communication semantices
need to be presented regarding send, receive, select, and goroutines.</font>
</p>
2811

2812
<h3>Constant expressions</h3>
Robert Griesemer's avatar
Robert Griesemer committed
2813

2814 2815 2816 2817 2818 2819 2820 2821
<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
2822
elements.  If it contains only numeric literals, its type is <i>ideal
2823 2824
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).
2825
The nature of the arithmetic
2826 2827 2828 2829
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
2830

2831
<pre>
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
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;
2850
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
2851

2852
<p>
2853 2854
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
2855
expression can be represented accurately in that context.
2856
It is erroneous to assign a value with a non-zero fractional part
Rob Pike's avatar
Rob Pike committed
2857 2858 2859 2860 2861 2862 2863 2864
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>.
2865
</p>
Robert Griesemer's avatar
Robert Griesemer committed
2866

2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897
<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>
The size of the mask used by the unary bitwise complement
operator in a typed constant expression is equal to the size of the
expression's type.  In an ideal constant expression, the bitwise
complement operator inverts all the bits, producing a negative value.
</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)
^int8(1)    // error, same as 0xFF ^ int8(1) = int8(0xFE), out of range
</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>

2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
<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>
For example, while evaluating the arguments for this call
to function <code>f</code>,
</p>
<pre>
f(g(), h() + x[i()], <-c)
</pre>
<p>
the call to <code>g()</code> happens before the call to <code>h()</code>,
which happens before the call to <code>i()</code>, all of
of which happen before receiving the value from the channel
<code>c</code>.
However, the order of those events compared to the evaluation of
<code>f</code>, the evaluation of <code>x</code>, and the indexing
Russ Cox's avatar
Russ Cox committed
2921
of <code>x</code> by the return value of
2922 2923 2924
<code>i()</code> is not specified.
</p>

Rob Pike's avatar
Rob Pike committed
2925
<hr/>
Robert Griesemer's avatar
Robert Griesemer committed
2926

2927
<h2>Statements</h2>
2928

Rob Pike's avatar
Rob Pike committed
2929
<p>
2930
Statements control execution.
Rob Pike's avatar
Rob Pike committed
2931
</p>
2932

Rob Pike's avatar
Rob Pike committed
2933
<pre class="grammar">
2934
Statement =
2935 2936 2937 2938
	Declaration | EmptyStmt | LabeledStmt |
	SimpleStmt | GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
	FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
	DeferStmt .
Robert Griesemer's avatar
Robert Griesemer committed
2939

2940
SimpleStmt = ExpressionStmt | IncDecStmt | Assignment | SimpleVarDecl .
2941

Rob Pike's avatar
Rob Pike committed
2942 2943
StatementList = Statement { Separator Statement } .
Separator     = [ ";" ]
2944
</pre>
2945

2946
<p>
Rob Pike's avatar
Rob Pike committed
2947 2948
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
2949
</p>
2950
<ul>
Rob Pike's avatar
Rob Pike committed
2951 2952
	<li>ends with the closing parenthesis ")" of a list of declarations
	    (§Declarations and Scope); or</li>
2953
	<li>ends with a closing brace "}" that is not part of an expression.
2954
</ul>
2955

2956

2957
<h3>Empty statements</h3>
2958

Rob Pike's avatar
Rob Pike committed
2959
<p>
2960
The empty statement does nothing.
Rob Pike's avatar
Rob Pike committed
2961
</p>
2962

Rob Pike's avatar
Rob Pike committed
2963
<pre class="grammar">
2964
EmptyStmt = .
2965
</pre>
2966

Rob Pike's avatar
Rob Pike committed
2967 2968 2969 2970 2971
<p>
A statement list can always in effect be terminated with a semicolon by
adding an empty statement.
</p>

2972

2973 2974 2975 2976 2977 2978 2979 2980
<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">
2981
LabeledStmt = Label ":" Statement .
2982 2983 2984 2985 2986 2987 2988 2989
Label       = identifier .
</pre>

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


2990
<h3>Expression statements</h3>
2991

Rob Pike's avatar
Rob Pike committed
2992 2993 2994 2995 2996 2997
<p>
Function calls, method calls, and channel operations
can appear in statement context.
</p>


Rob Pike's avatar
Rob Pike committed
2998
<pre class="grammar">
2999
ExpressionStmt = Expression .
3000
</pre>
3001

3002 3003
<pre>
f(x+y)
Rob Pike's avatar
Rob Pike committed
3004
<-ch
3005
</pre>
3006 3007


3008
<h3>IncDec statements</h3>
3009

Rob Pike's avatar
Rob Pike committed
3010
<p>
3011
The "++" and "--" statements increment or decrement their operands
Rob Pike's avatar
Rob Pike committed
3012 3013 3014
by the ideal numeric value 1.  As with an assignment, the operand
must be a variable, pointer indirection, field selector or index expression.
</p>
3015

Rob Pike's avatar
Rob Pike committed
3016
<pre class="grammar">
3017
IncDecStmt = Expression ( "++" | "--" ) .
3018
</pre>
3019

Rob Pike's avatar
Rob Pike committed
3020
<p>
3021 3022
The following assignment statements (§Assignments) are semantically
equivalent:
Rob Pike's avatar
Rob Pike committed
3023
</p>
3024

Rob Pike's avatar
Rob Pike committed
3025
<pre class="grammar">
3026 3027 3028 3029
IncDec statement    Assignment
x++                 x += 1
x--                 x -= 1
</pre>
3030

3031
<h3>Assignments</h3>
3032

Rob Pike's avatar
Rob Pike committed
3033
<pre class="grammar">
3034
Assignment = ExpressionList assign_op ExpressionList .
Rob Pike's avatar
Rob Pike committed
3035

3036 3037
assign_op = [ add_op | mul_op ] "=" .
</pre>
3038

Rob Pike's avatar
Rob Pike committed
3039 3040 3041 3042
<p>
Each left-hand side operand must be a variable, pointer indirection,
field selector, or index expression.
</p>
3043

3044 3045 3046 3047 3048
<pre>
x = 1
*p = f()
a[i] = 23
k = <-ch
3049
i &amp;^= 1&lt;&lt;n
3050
</pre>
3051

Rob Pike's avatar
Rob Pike committed
3052 3053 3054 3055 3056 3057 3058
<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>
3059

3060
<pre>
Rob Pike's avatar
Rob Pike committed
3061
a[i] <<= 2
3062
</pre>
3063

Rob Pike's avatar
Rob Pike committed
3064 3065 3066 3067 3068
<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
3069 3070
operations, §Map operations) or a type assertion (§Type assertions).
The number of operands on the left
Rob Pike's avatar
Rob Pike committed
3071 3072 3073
hand side must match the number of values.  For instance, If
<code>f</code> is a function returning two values,
</p>
3074

3075 3076 3077
<pre>
x, y = f()
</pre>
3078

Rob Pike's avatar
Rob Pike committed
3079 3080 3081
<p>
assigns the first value to <code>x</code> and the second to <code>y</code>.
</p>
3082

Rob Pike's avatar
Rob Pike committed
3083 3084
<p>
In the second form, the number of operands on the left must equal the number
3085 3086 3087 3088
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
3089
</p>
3090

3091
<pre>
Rob Pike's avatar
Rob Pike committed
3092
a, b = b, a  // exchange a and b
3093
</pre>
Rob Pike's avatar
Rob Pike committed
3094 3095 3096 3097 3098 3099

<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>
3100 3101


3102
<h3>If statements</h3>
3103

Rob Pike's avatar
Rob Pike committed
3104 3105 3106 3107 3108 3109 3110
<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>
3111

Rob Pike's avatar
Rob Pike committed
3112
<pre class="grammar">
3113
IfStmt    = "if" [ [ SimpleStmt ] ";" ] [ Expression ] Block [ "else" Statement ] .
3114
</pre>
3115

3116 3117 3118 3119 3120
<pre>
if x > 0 {
	return true;
}
</pre>
3121

3122 3123 3124 3125
<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
3126
and the variables are initialized once before the statement is entered.
3127
</p>
3128

3129 3130 3131 3132 3133 3134 3135 3136 3137
<pre>
if x := f(); x < y {
	return x;
} else if x > z {
	return z;
} else {
	return y;
}
</pre>
3138 3139


3140
<h3>Switch statements</h3>
3141

Rob Pike's avatar
Rob Pike committed
3142 3143
<p>
"Switch" statements provide multi-way execution.
Rob Pike's avatar
Rob Pike committed
3144 3145 3146
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
3147
</p>
3148 3149

<pre class="grammar">
3150
SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
3151 3152
</pre>

Rob Pike's avatar
Rob Pike committed
3153
<p>
Rob Pike's avatar
Rob Pike committed
3154 3155 3156 3157 3158 3159 3160
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>

3161
<h4>Expression switches</h4>
Rob Pike's avatar
Rob Pike committed
3162 3163 3164 3165 3166 3167 3168

<p>
In an expression switch,
the switch expression is evaluated and
the case expressions, which need not be constants,
are evaluated top-to-bottom; the first one that equals the
switch expression
Rob Pike's avatar
Rob Pike committed
3169 3170
triggers execution of the statements of the associated case;
the other cases are skipped.
Rob Pike's avatar
Rob Pike committed
3171 3172
If no case matches and there is a "default" case,
its statements are executed.
Rob Pike's avatar
Rob Pike committed
3173 3174
There can be at most one default case and it may appear anywhere in the
"switch" statement.
3175 3176
A missing expression is equivalent to
the expression <code>true</code>.
Rob Pike's avatar
Rob Pike committed
3177
</p>
3178 3179

<pre class="grammar">
3180
ExprSwitchStmt = "switch" [ [ SimpleStmt ] ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
3181 3182
ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
ExprSwitchCase = "case" ExpressionList | "default" .
3183 3184
</pre>

Rob Pike's avatar
Rob Pike committed
3185 3186 3187
<p>
In a case or default clause,
the last statement only may be a "fallthrough" statement
3188
(§Fallthrough statement) to
Rob Pike's avatar
Rob Pike committed
3189
indicate that control should flow from the end of this clause to
3190
the first statement of the next clause.
Rob Pike's avatar
Rob Pike committed
3191 3192
Otherwise control flows to the end of the "switch" statement.
</p>
3193
<p>
3194
Each case clause acts as a block for scoping purposes
3195
(§Declarations and scope rules).
Rob Pike's avatar
Rob Pike committed
3196
</p>
3197
<p>
3198
A "switch" statement may include a simple statement before the
Rob Pike's avatar
Rob Pike committed
3199
expression.
3200 3201 3202
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
3203
</p>
3204

3205 3206
<pre>
switch tag {
3207 3208 3209
default: s3()
case 0, 1, 2, 3: s1()
case 4, 5, 6, 7: s2()
3210
}
3211

Rob Pike's avatar
Rob Pike committed
3212
switch x := f(); {
3213 3214
case x &lt; 0: return -x
default: return x
3215
}
3216

Rob Pike's avatar
Rob Pike committed
3217
switch {          // missing expression means "true"
3218 3219 3220
case x < y: f1();
case x < z: f2();
case x == 4: f3();
3221 3222
}
</pre>
3223

3224
<h4>Type switches</h4>
Rob Pike's avatar
Rob Pike committed
3225 3226

<p>
3227 3228 3229
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
3230
has the form of a type assertion (§Type assertions)
3231 3232
using the reserved word <code>type</code> rather than an actual type.
Cases then match literal types against the dynamic type of the expression
3233
in the type assertion.
Rob Pike's avatar
Rob Pike committed
3234 3235
</p>

3236
<pre class="grammar">
3237
TypeSwitchStmt  = "switch" [ [ SimpleStmt ] ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
3238 3239
TypeSwitchGuard = identifier ":=" Expression "." "(" "type" ")" .
TypeCaseClause  = TypeSwitchCase ":" [ StatementList ] .
3240
TypeSwitchCase  = "case" ( type | "nil" ) | "default" .
Rob Pike's avatar
Rob Pike committed
3241 3242
</pre>

3243 3244 3245 3246 3247 3248
<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
3249 3250 3251
<p>
Given a function <code>f</code>
that returns a value of interface type,
3252
the following type switch:
Rob Pike's avatar
Rob Pike committed
3253 3254 3255 3256
</p>

<pre>
switch i := f().(type) {
3257 3258
case nil:
	printString("f() returns nil");
Rob Pike's avatar
Rob Pike committed
3259 3260 3261 3262
case int:
	printInt(i);	// i is an int
case float:
	printFloat(i);	// i is a float
3263 3264
case func(int) float:
	printFunction(i);	// i is a function
Rob Pike's avatar
Rob Pike committed
3265 3266 3267
default:
	printString("don't know the type");
}
3268
</pre>
Rob Pike's avatar
Rob Pike committed
3269

3270 3271 3272 3273 3274 3275
<p>
could be rewritten:
</p>

<pre>
v := f();
3276 3277 3278
if v == nil {
	printString("f() returns nil");
} else if i, is_int := v.(int); is_int {
Rob Pike's avatar
Rob Pike committed
3279
	printInt(i);	// i is an int
3280
} else if i, is_float := v.(float); is_float {
Rob Pike's avatar
Rob Pike committed
3281
	printFloat(i);	// i is a float
3282 3283 3284
} 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
3285 3286 3287
	printString("don't know the type");
}
</pre>
3288

3289 3290 3291 3292 3293 3294
<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>

3295
<h3>For statements</h3>
3296

Rob Pike's avatar
Rob Pike committed
3297 3298 3299 3300
<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>
3301

Rob Pike's avatar
Rob Pike committed
3302
<pre class="grammar">
3303
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
3304 3305
Condition = Expression .
</pre>
3306

Rob Pike's avatar
Rob Pike committed
3307 3308 3309 3310 3311 3312
<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>
3313

3314 3315 3316 3317 3318
<pre>
for a &lt; b {
	a *= 2
}
</pre>
3319

Rob Pike's avatar
Rob Pike committed
3320 3321 3322 3323 3324 3325 3326
<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
3327
(§Declarations and scope rules).
Rob Pike's avatar
Rob Pike committed
3328
</p>
3329

Rob Pike's avatar
Rob Pike committed
3330
<pre class="grammar">
3331 3332 3333
ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
InitStmt = SimpleStmt .
PostStmt = SimpleStmt .
3334
</pre>
3335

3336 3337 3338 3339 3340
<pre>
for i := 0; i < 10; i++ {
	f(i)
}
</pre>
3341

3342
<p>
Rob Pike's avatar
Rob Pike committed
3343 3344 3345 3346 3347 3348 3349 3350
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
3351

3352 3353 3354 3355
<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
3356

Rob Pike's avatar
Rob Pike committed
3357 3358
<p>
A "for" statement with a "range" clause
Rob Pike's avatar
Rob Pike committed
3359 3360
iterates through all entries of an array, slice, string or map,
or values received on a channel.
Robert Griesemer's avatar
Robert Griesemer committed
3361 3362
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
3363 3364
of iteration variables - and then executes the block.
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3365

Rob Pike's avatar
Rob Pike committed
3366
<pre class="grammar">
3367
RangeClause = ExpressionList ( "=" | ":=" ) "range" Expression .
3368
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3369

Rob Pike's avatar
Rob Pike committed
3370
<p>
Rob Pike's avatar
Rob Pike committed
3371 3372
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;
3373
or it may be a channel.
Rob Pike's avatar
Rob Pike committed
3374
Except for channels,
3375 3376 3377 3378
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
3379
iteration variables. On each iteration,
Rob Pike's avatar
Rob Pike committed
3380
the first variable is set to the string, array or slice index or
Robert Griesemer's avatar
Robert Griesemer committed
3381
map key, and the second variable, if present, is set to the corresponding
Rob Pike's avatar
Rob Pike committed
3382
string or array element or map value.
Rob Pike's avatar
Rob Pike committed
3383 3384 3385 3386
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>
3387
<p>
Rob Pike's avatar
Rob Pike committed
3388 3389
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
3390
index of successive UTF-8-encoded code points in the string, and
Rob Pike's avatar
Rob Pike committed
3391 3392 3393 3394 3395 3396 3397
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>
3398 3399 3400 3401 3402
For channels, the identifier list must contain one identifier.
The iteration recieves values sent on the channel until the channel is closed;
it does not process the zero value sent before the channel is closed.
</p>
<p>
Rob Pike's avatar
Rob Pike committed
3403
The iteration variables may be declared by the "range" clause (":="), in which
3404
case their scope ends at the end of the "for" statement (§Declarations and
Rob Pike's avatar
Rob Pike committed
3405
scope rules). In this case their types are set to
3406
<code>int</code> and the array element type, or the map key and value types, respectively.
Rob Pike's avatar
Rob Pike committed
3407 3408 3409
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
3410

3411 3412
<pre>
var a [10]string;
3413
m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6};
3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429

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
3430

Rob Pike's avatar
Rob Pike committed
3431
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3432 3433
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
3434
behavior is implementation-dependent, but each entry will be processed at most once.
Rob Pike's avatar
Rob Pike committed
3435
</p>
3436

3437
<h3>Go statements</h3>
3438

Rob Pike's avatar
Rob Pike committed
3439
<p>
3440
A "go" statement starts the execution of a function or method call
Rob Pike's avatar
Rob Pike committed
3441 3442 3443
as an independent concurrent thread of control, or <i>goroutine</i>,
within the same address space.
</p>
3444

Rob Pike's avatar
Rob Pike committed
3445
<pre class="grammar">
3446
GoStmt = "go" Expression .
3447
</pre>
3448

Rob Pike's avatar
Rob Pike committed
3449 3450 3451
<p>
The expression must be a call, and
unlike with a regular call, program execution does not wait
3452
for the invoked function to complete.
Rob Pike's avatar
Rob Pike committed
3453
</p>
3454

3455 3456 3457 3458
<pre>
go Server()
go func(ch chan <- bool) { for { sleep(10); ch <- true; }} (c)
</pre>
3459 3460


3461
<h3>Select statements</h3>
3462

Rob Pike's avatar
Rob Pike committed
3463 3464 3465
<p>
A "select" statement chooses which of a set of possible communications
will proceed.  It looks similar to a "switch" statement but with the
3466
cases all referring to communication operations.
Rob Pike's avatar
Rob Pike committed
3467
</p>
3468

Rob Pike's avatar
Rob Pike committed
3469
<pre class="grammar">
3470
SelectStmt = "select" "{" { CommClause } "}" .
3471
CommClause = CommCase ":" StatementList .
3472 3473 3474 3475
CommCase = "case" ( SendExpr | RecvExpr) | "default" .
SendExpr =  Expression "&lt;-" Expression .
RecvExpr =  [ Expression ( "=" | ":=" ) ] "&lt;-" Expression .
</pre>
3476

Rob Pike's avatar
Rob Pike committed
3477
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3478 3479
Each communication clause acts as a block for the purpose of scoping
(§Declarations and scope rules).
Rob Pike's avatar
Rob Pike committed
3480
</p>
3481
<p>
Rob Pike's avatar
Rob Pike committed
3482 3483
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
3484 3485 3486 3487
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;
3488
if not, the statement blocks until one of the communications can
Rob Pike's avatar
Rob Pike committed
3489
complete.  The channels and send expressions are not re-evaluated.
Rob Pike's avatar
Rob Pike committed
3490 3491 3492 3493 3494
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>
3495
<p>
Rob Pike's avatar
Rob Pike committed
3496 3497
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
3498 3499
in the "select" statement.
</p>
3500
<p>
Rob Pike's avatar
Rob Pike committed
3501
If multiple cases can proceed, a uniform fair choice is made to decide
3502
which single communication will execute.
3503
<p>
Rob Pike's avatar
Rob Pike committed
3504 3505 3506 3507 3508
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>
3509

3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522
<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
3523
	select {
3524 3525
	case c &lt;- 0:  // note: no statement, no fallthrough, no folding of cases
	case c &lt;- 1:
3526
	}
3527 3528
}
</pre>
3529

3530
<font color=red>
3531
TODO: Make semantics more precise.
3532
</font>
3533 3534


3535
<h3>Return statements</h3>
3536

Rob Pike's avatar
Rob Pike committed
3537 3538
<p>
A "return" statement terminates execution of the containing function
3539
and optionally provides a result value or values to the caller.
Rob Pike's avatar
Rob Pike committed
3540
</p>
3541

Rob Pike's avatar
Rob Pike committed
3542
<pre class="grammar">
3543
ReturnStmt = "return" [ ExpressionList ] .
3544
</pre>
3545

Rob Pike's avatar
Rob Pike committed
3546 3547 3548 3549 3550
<pre>
func procedure() {
	return
}
</pre>
3551

Rob Pike's avatar
Rob Pike committed
3552 3553 3554
<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
3555 3556
in the "return" statement.
Normally, the expressions
Rob Pike's avatar
Rob Pike committed
3557 3558 3559
must be single-valued and assignment-compatible to the elements of
the result type of the function.
</p>
3560

3561 3562
<pre>
func simple_f() int {
Rob Pike's avatar
Rob Pike committed
3563 3564 3565 3566 3567
	return 2
}

func complex_f1() (re float, im float) {
	return -7.0, -4.0
3568 3569
}
</pre>
3570

Rob Pike's avatar
Rob Pike committed
3571 3572 3573 3574 3575 3576
<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>
3577

3578
<pre>
Rob Pike's avatar
Rob Pike committed
3579 3580
func complex_f2() (re float, im float) {
	return complex_f1()
3581 3582
}
</pre>
3583

Rob Pike's avatar
Rob Pike committed
3584
<p>
3585
The second way to return values is to use the elements of the
Rob Pike's avatar
Rob Pike committed
3586 3587 3588 3589 3590 3591
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>
3592

3593
<pre>
Rob Pike's avatar
Rob Pike committed
3594
func complex_f3() (re float, im float) {
3595 3596 3597 3598 3599
	re = 7.0;
	im = 4.0;
	return;
}
</pre>
3600

3601 3602 3603 3604
<p>
TODO: Define when return is required.
</p>

3605
<h3>Break statements</h3>
3606

Rob Pike's avatar
Rob Pike committed
3607 3608 3609 3610
<p>
A "break" statement terminates execution of the innermost
"for", "switch" or "select" statement.
</p>
3611

Rob Pike's avatar
Rob Pike committed
3612
<pre class="grammar">
3613
BreakStmt = "break" [ Label ].
3614
</pre>
3615

Rob Pike's avatar
Rob Pike committed
3616 3617 3618 3619 3620 3621
<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>
3622

3623 3624 3625
<pre>
L: for i < n {
	switch i {
Rob Pike's avatar
Rob Pike committed
3626
		case 5: break L
3627
	}
3628 3629
}
</pre>
3630

3631
<h3>Continue statements</h3>
3632

Rob Pike's avatar
Rob Pike committed
3633 3634 3635 3636
<p>
A "continue" statement begins the next iteration of the
innermost "for" loop at the post statement (§For statements).
</p>
3637

Rob Pike's avatar
Rob Pike committed
3638
<pre class="grammar">
3639
ContinueStmt = "continue" [ Label ].
3640
</pre>
3641

Rob Pike's avatar
Rob Pike committed
3642 3643 3644
<p>
The optional label is analogous to that of a "break" statement.
</p>
3645

3646
<h3>Goto statements</h3>
3647

Rob Pike's avatar
Rob Pike committed
3648 3649 3650
<p>
A "goto" statement transfers control to the statement with the corresponding label.
</p>
3651

Rob Pike's avatar
Rob Pike committed
3652
<pre class="grammar">
3653
GotoStmt = "goto" Label .
3654
</pre>
3655

3656 3657 3658
<pre>
goto Error
</pre>
3659

Rob Pike's avatar
Rob Pike committed
3660 3661
<p>
Executing the "goto" statement must not cause any variables to come into
3662 3663
scope that were not already in scope at the point of the goto.  For
instance, this example:
Rob Pike's avatar
Rob Pike committed
3664
</p>
3665

3666 3667 3668 3669 3670
<pre>
goto L;  // BAD
v := 3;
L:
</pre>
3671

Rob Pike's avatar
Rob Pike committed
3672 3673 3674
<p>
is erroneous because the jump to label <code>L</code> skips
the creation of <code>v</code>.
3675
(TODO: Eliminate in favor of used and not set errors?)
Rob Pike's avatar
Rob Pike committed
3676
</p>
3677

3678
<h3>Fallthrough statements</h3>
3679

Rob Pike's avatar
Rob Pike committed
3680 3681
<p>
A "fallthrough" statement transfers control to the first statement of the
3682 3683 3684
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
3685
</p>
3686

Rob Pike's avatar
Rob Pike committed
3687
<pre class="grammar">
3688
FallthroughStmt = "fallthrough" .
3689
</pre>
3690 3691


3692
<h3>Defer statements</h3>
Robert Griesemer's avatar
Robert Griesemer committed
3693

Rob Pike's avatar
Rob Pike committed
3694 3695 3696 3697
<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
3698

Rob Pike's avatar
Rob Pike committed
3699
<pre class="grammar">
3700
DeferStmt = "defer" Expression .
3701
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3702

Rob Pike's avatar
Rob Pike committed
3703 3704 3705
<p>
The expression must be a function or method call.
Each time the "defer" statement
3706
executes, the parameters to the function call are evaluated and saved anew but the
Robert Griesemer's avatar
Robert Griesemer committed
3707
function is not invoked. Immediately before the innermost function surrounding
Rob Pike's avatar
Rob Pike committed
3708
the "defer" statement returns, but after its return value (if any) is evaluated,
Robert Griesemer's avatar
Robert Griesemer committed
3709 3710
each deferred function is executed with its saved parameters. Deferred functions
are executed in LIFO order.
Rob Pike's avatar
Rob Pike committed
3711
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3712

3713 3714 3715
<pre>
lock(l);
defer unlock(l);  // unlocking happens before surrounding function returns
Robert Griesemer's avatar
Robert Griesemer committed
3716

3717 3718 3719 3720 3721
// 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
3722

Rob Pike's avatar
Rob Pike committed
3723
<hr/>
3724

3725
<h2>Predeclared functions</h2>
3726 3727
<ul>
	<li>cap
3728 3729
	<li>close
	<li>closed
3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740
	<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
3741
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
3742
Call       Argument type       Result
3743 3744

len(s)    string, *string      string length (in bytes)
Rob Pike's avatar
Rob Pike committed
3745 3746 3747 3748
          [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
3749 3750

cap(s)    []T, *[]T            capacity of s
Rob Pike's avatar
Rob Pike committed
3751 3752
          map[K]T, *map[K]T    capacity of s
          chan T               channel buffer capacity
3753
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3754

3755
<p>
Rob Pike's avatar
Rob Pike committed
3756 3757 3758
The type of the result is always <code>int</code> and the
implementation guarantees that
the result always fits into an <code>int</code>.
3759
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3760
The capacity of a slice or map is the number of elements for which there is
Rob Pike's avatar
Rob Pike committed
3761 3762
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
3763

3764 3765 3766
<pre>
0 <= len(s) <= cap(s)
</pre>
3767

3768

3769
<h3>Conversions</h3>
3770

Rob Pike's avatar
Rob Pike committed
3771 3772 3773
<p>
Conversions look like function calls of the form
</p>
3774

Rob Pike's avatar
Rob Pike committed
3775
<pre class="grammar">
3776 3777
T(value)
</pre>
3778

Rob Pike's avatar
Rob Pike committed
3779
<p>
Russ Cox's avatar
Russ Cox committed
3780 3781 3782
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
3783
of result type <code>T</code>.
3784
<p>
3785
The following conversion rules apply:
Rob Pike's avatar
Rob Pike committed
3786 3787 3788
</p>
<ul>
<li>
Russ Cox's avatar
Russ Cox committed
3789 3790 3791 3792
1) Between equal types.  The conversion always succeeds.
</li>
<li>
2) Between integer types.  If the value is a signed quantity, it is
3793 3794
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
3795 3796 3797 3798
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>
Russ Cox's avatar
Russ Cox committed
3799
3) Between integer and floating point types, or between floating point
3800
types.  To avoid overdefining the properties of the conversion, for
3801
now it is defined as a ``best effort'' conversion.  The conversion
3802
always succeeds but the value may be a NaN or other problematic
3803
result. <font color=red>TODO: clarify?</font>
Rob Pike's avatar
Rob Pike committed
3804 3805
</li>
<li>
Russ Cox's avatar
Russ Cox committed
3806
4) Strings permit two special conversions.
Rob Pike's avatar
Rob Pike committed
3807 3808
</li>
<li>
Russ Cox's avatar
Russ Cox committed
3809
4a) Converting an integer value yields a string containing the UTF-8
3810 3811
representation of the integer.

3812 3813 3814
<pre>
string(0x65e5)  // "\u65e5"
</pre>
3815

Rob Pike's avatar
Rob Pike committed
3816 3817
</li>
<li>
Russ Cox's avatar
Russ Cox committed
3818 3819
4b) Converting a slice of bytes yields a string whose successive
bytes are those of the slice.
3820

3821
<pre>
3822
string([]byte{'h', 'e', 'l', 'l', 'o'}) // "hello"
3823
</pre>
Rob Pike's avatar
Rob Pike committed
3824 3825
</li>
</ul>
3826

Rob Pike's avatar
Rob Pike committed
3827
<p>
Rob Pike's avatar
Rob Pike committed
3828 3829 3830 3831
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
3832
</p>
3833 3834


3835
<h3>Allocation</h3>
3836

Rob Pike's avatar
Rob Pike committed
3837 3838 3839
<p>
The built-in function <code>new</code> takes a type <code>T</code> and
returns a value of type <code>*T</code>.
3840
The memory is initialized as described in the section on initial values
Rob Pike's avatar
Rob Pike committed
3841
(§The zero value).
Rob Pike's avatar
Rob Pike committed
3842
</p>
3843

3844 3845 3846
<pre>
new(T)
</pre>
3847

Rob Pike's avatar
Rob Pike committed
3848
<p>
3849
For instance
Rob Pike's avatar
Rob Pike committed
3850
</p>
3851

3852 3853 3854 3855
<pre>
type S struct { a int; b float }
new(S)
</pre>
3856

3857
<p>
Rob Pike's avatar
Rob Pike committed
3858 3859 3860 3861 3862
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
3863

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

Rob Pike's avatar
Rob Pike committed
3866 3867 3868 3869 3870 3871 3872
<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
3873
The memory is initialized as described in the section on initial values
Rob Pike's avatar
Rob Pike committed
3874
(§The zero value).
Rob Pike's avatar
Rob Pike committed
3875
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3876

3877 3878 3879
<pre>
make(T [, optional list of expressions])
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3880

Rob Pike's avatar
Rob Pike committed
3881
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3882
For instance
Rob Pike's avatar
Rob Pike committed
3883
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3884

3885 3886 3887
<pre>
make(map[string] int)
</pre>
Robert Griesemer's avatar
Robert Griesemer committed
3888

Rob Pike's avatar
Rob Pike committed
3889
<p>
Robert Griesemer's avatar
Robert Griesemer committed
3890
creates a new map value and initializes it to an empty map.
Rob Pike's avatar
Rob Pike committed
3891
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3892

Rob Pike's avatar
Rob Pike committed
3893 3894
<p>
The parameters affect sizes for allocating slices, maps, and
Robert Griesemer's avatar
Robert Griesemer committed
3895
buffered channels:
Rob Pike's avatar
Rob Pike committed
3896
</p>
Robert Griesemer's avatar
Robert Griesemer committed
3897

3898 3899 3900 3901 3902
<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>
3903

Rob Pike's avatar
Rob Pike committed
3904
<hr/>
3905

3906
<h2>Packages</h2>
3907

Rob Pike's avatar
Rob Pike committed
3908 3909 3910
<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
3911
together provide access to a set of types, constants, functions,
Rob Pike's avatar
Rob Pike committed
3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923
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
3924
package clause acts as a block for scoping (§Declarations and scope
Rob Pike's avatar
Rob Pike committed
3925 3926
rules).
</p>
3927

Rob Pike's avatar
Rob Pike committed
3928
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
3929
SourceFile       = PackageClause { ImportDecl [ ";" ] } { Declaration [ ";" ] } .
3930
</pre>
3931

Rob Pike's avatar
Rob Pike committed
3932 3933
<h3>Package clause</h3>

3934
<p>
Rob Pike's avatar
Rob Pike committed
3935 3936 3937
A package clause begins each source file and defines the package
to which the file belongs.
</p>
3938

Rob Pike's avatar
Rob Pike committed
3939
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
3940 3941
PackageClause    = "package" PackageName .
</pre>
3942

Rob Pike's avatar
Rob Pike committed
3943 3944
<pre>
package math
3945
</pre>
3946

Rob Pike's avatar
Rob Pike committed
3947 3948 3949 3950
<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>
3951

Rob Pike's avatar
Rob Pike committed
3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
<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>
3963

Rob Pike's avatar
Rob Pike committed
3964
<pre class="grammar">
Rob Pike's avatar
Rob Pike committed
3965 3966 3967 3968
ImportDecl       = "import" ( ImportSpec | "(" [ ImportSpecList ] ")" ) .
ImportSpecList   = ImportSpec { ";" ImportSpec } [ ";" ] .
ImportSpec       = [ "." | PackageName ] PackageFileName .
PackageFileName  = StringLit .
3969
</pre>
3970

3971
<p>
Rob Pike's avatar
Rob Pike committed
3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985
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>
3986
<p>
Rob Pike's avatar
Rob Pike committed
3987 3988 3989 3990 3991
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>
3992

Rob Pike's avatar
Rob Pike committed
3993 3994 3995 3996 3997 3998
<pre class="grammar">
Import syntax               Local name of Sin

import M "lib/math"         M.Sin
import   "lib/math"         math.Sin
import . "lib/math"         Sin
3999
</pre>
4000

Rob Pike's avatar
Rob Pike committed
4001 4002
<h3>Multi-file packages</h3>

4003
<p>
Rob Pike's avatar
Rob Pike committed
4004 4005 4006 4007 4008 4009 4010
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>
4011

Rob Pike's avatar
Rob Pike committed
4012 4013 4014 4015 4016 4017 4018 4019 4020
<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>
4021
<pre>
Rob Pike's avatar
Rob Pike committed
4022 4023 4024 4025 4026
package math

const twoPi = 6.283185307179586

function Sin(x float) float { return ... }
4027
</pre>
4028

4029
<p>
Rob Pike's avatar
Rob Pike committed
4030 4031
and file <code>"math2.go"</code> begins
</p>
4032
<pre>
Rob Pike's avatar
Rob Pike committed
4033 4034 4035
package math

import "lib/math"
4036
</pre>
4037

4038
<p>
Rob Pike's avatar
Rob Pike committed
4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049
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>
4050

4051 4052 4053
<pre>
package main

Rob Pike's avatar
Rob Pike committed
4054 4055
import "fmt"

4056 4057 4058 4059
// 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'.
4060
	}
4061 4062 4063 4064
}

// Copy the values from channel 'in' to channel 'out',
// removing those divisible by 'prime'.
4065 4066
func filter(src chan <- int, dst <-chan int, prime int) {
	for i := range src {  // Loop over values received from 'src'.
4067
		if i % prime != 0 {
4068
			dst <- i  // Send 'i' to channel 'dst'.
4069 4070
		}
	}
4071 4072 4073 4074 4075 4076 4077 4078
}

// 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
4079
		fmt.Print(prime, "\n");
4080 4081 4082
		ch1 := make(chan int);
		go filter(ch, ch1, prime);
		ch = ch1
4083
	}
4084
}
4085

4086 4087 4088 4089
func main() {
	sieve()
}
</pre>
4090

Rob Pike's avatar
Rob Pike committed
4091
<hr/>
4092

4093
<h2>Program initialization and execution</h2>
4094

Rob Pike's avatar
Rob Pike committed
4095 4096
<h3>The zero value</h3>
<p>
4097
When memory is allocated to store a value, either through a declaration
Rob Pike's avatar
Rob Pike committed
4098
or <code>new()</code>, and no explicit initialization is provided, the memory is
4099
given a default initialization.  Each element of such a value is
Rob Pike's avatar
Rob Pike committed
4100 4101 4102
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
4103
This initialization is done recursively, so for instance each element of an
Rob Pike's avatar
Rob Pike committed
4104 4105
array of structs will have its fields zeroed if no value is specified.
</p>
4106
<p>
4107
These two simple declarations are equivalent:
Rob Pike's avatar
Rob Pike committed
4108
</p>
4109

4110 4111 4112 4113
<pre>
var i int;
var i int = 0;
</pre>
4114

Rob Pike's avatar
Rob Pike committed
4115
<p>
4116
After
Rob Pike's avatar
Rob Pike committed
4117
</p>
4118

4119 4120 4121 4122
<pre>
type T struct { i int; f float; next *T };
t := new(T);
</pre>
4123

Rob Pike's avatar
Rob Pike committed
4124
<p>
4125
the following holds:
Rob Pike's avatar
Rob Pike committed
4126
</p>
4127

4128 4129 4130 4131 4132
<pre>
t.i == 0
t.f == 0.0
t.next == nil
</pre>
4133

Rob Pike's avatar
Rob Pike committed
4134 4135 4136 4137 4138 4139 4140 4141
<p>
The same would also be true after
</p>

<pre>
var t T
</pre>

Rob Pike's avatar
Rob Pike committed
4142 4143
<h3>Program execution</h3>
<p>
4144
A package with no imports is initialized by assigning initial values to
Rob Pike's avatar
Rob Pike committed
4145 4146 4147 4148 4149 4150 4151 4152 4153 4154
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
4155
only one per source file.
Rob Pike's avatar
Rob Pike committed
4156
</p>
4157
<p>
4158
Initialization code may contain "go" statements, but the functions
4159 4160
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
4161
goroutine.
Rob Pike's avatar
Rob Pike committed
4162
</p>
4163
<p>
Rob Pike's avatar
Rob Pike committed
4164 4165 4166
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
4167
</p>
4168
<p>
4169
If a package has imports, the imported packages are initialized
4170
before initializing the package itself. If multiple packages import
Rob Pike's avatar
Rob Pike committed
4171
a package <code>P</code>, <code>P</code> will be initialized only once.
Rob Pike's avatar
Rob Pike committed
4172
</p>
4173
<p>
4174 4175
The importing of packages, by construction, guarantees that there can
be no cyclic dependencies in initialization.
Rob Pike's avatar
Rob Pike committed
4176
</p>
4177
<p>
4178
A complete program, possibly created by linking multiple packages,
Rob Pike's avatar
Rob Pike committed
4179
must have one package called <code>main</code>, with a function
Rob Pike's avatar
Rob Pike committed
4180
</p>
4181

4182
<pre>
Rob Pike's avatar
Rob Pike committed
4183
func main() { ... }
4184
</pre>
4185

Rob Pike's avatar
Rob Pike committed
4186
<p>
Rob Pike's avatar
Rob Pike committed
4187 4188
defined.
The function <code>main.main()</code> takes no arguments and returns no value.
Rob Pike's avatar
Rob Pike committed
4189
</p>
4190
<p>
Rob Pike's avatar
Rob Pike committed
4191
Program execution begins by initializing the <code>main</code> package and then
Rob Pike's avatar
Rob Pike committed
4192 4193
invoking <code>main.main()</code>.
</p>
4194
<p>
Rob Pike's avatar
Rob Pike committed
4195
When <code>main.main()</code> returns, the program exits.
Rob Pike's avatar
Rob Pike committed
4196
</p>
Rob Pike's avatar
Rob Pike committed
4197 4198 4199 4200
<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>
4201

Rob Pike's avatar
Rob Pike committed
4202
<hr/>
4203

4204
<h2>System considerations</h2>
4205

4206
<h3>Package <code>unsafe</code></h3>
4207

4208
<p>
Rob Pike's avatar
Rob Pike committed
4209 4210 4211 4212 4213
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:
4214
</p>
4215

Rob Pike's avatar
Rob Pike committed
4216
<pre class="grammar">
4217
package unsafe
4218

4219
const Maxalign int
4220

4221
type Pointer *any  // "any" is shorthand for any Go type; it is not a real type.
4222

4223 4224 4225 4226
func Alignof(variable any) int
func Offsetof(selector any) int
func Sizeof(variable any) int
</pre>
4227

4228
<p>
4229 4230 4231
Any pointer or value of type <code>uintptr</code> can be converted into
a <code>Pointer</code> and vice versa.
</p>
4232
<p>
4233
The function <code>Sizeof</code> takes an expression denoting a
Rob Pike's avatar
Rob Pike committed
4234
variable of any (complete) type and returns the size of the variable in bytes.
4235
</p>
4236
<p>
4237
The function <code>Offsetof</code> takes a selector (§Selectors) denoting a struct
4238
field of any type and returns the field offset in bytes relative to the
4239 4240
struct's address. For a struct <code>s</code> with field <code>f</code>:
</p>
4241

4242
<pre>
4243
uintptr(unsafe.Pointer(&amp;s)) + uintptr(unsafe.Offsetof(s.f)) == uintptr(unsafe.Pointer(&amp;s.f))
4244
</pre>
4245

4246
<p>
4247 4248 4249 4250 4251 4252 4253
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>
4254

4255 4256 4257
<pre>
uintptr(unsafe.Pointer(&amp;x)) % uintptr(unsafe.Alignof(x)) == 0
</pre>
4258

4259
<p>
4260 4261
The maximum alignment is given by the constant <code>Maxalign</code>.
It usually corresponds to the value of <code>Sizeof(x)</code> for
4262
a variable <code>x</code> of the largest numeric type (8 for a
4263 4264 4265 4266 4267 4268 4269
<code>float64</code>), but may
be smaller on systems with weaker alignment restrictions.
</p>
<p>
Calls to <code>Alignof</code>, <code>Offsetof</code>, and
<code>Sizeof</code> are constant expressions of type <code>int</code>.
</p>
4270

4271

4272
<h3>Size and alignment guarantees</h3>
4273

4274
For the numeric types (§Numeric types), the following sizes are guaranteed:
4275

Rob Pike's avatar
Rob Pike committed
4276
<pre class="grammar">
4277
type                      size in bytes
4278

4279 4280 4281 4282 4283
byte, uint8, int8         1
uint16, int16             2
uint32, int32, float32    4
uint64, int64, float64    8
</pre>
4284

4285
<p>
4286
The following minimal alignment properties are guaranteed:
Rob Pike's avatar
Rob Pike committed
4287
</p>
4288
<ol>
4289
<li>For a variable <code>x</code> of any type: <code>1 <= unsafe.Alignof(x) <= unsafe.Maxalign</code>.
4290

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

4294 4295
<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.
4296

4297 4298
<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.
4299
</ol>
4300

Rob Pike's avatar
Rob Pike committed
4301 4302 4303 4304 4305
<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
4306 4307 4308 4309 4310 4311 4312
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.
Rob Pike's avatar
Rob Pike committed
4313 4314
</font>
</p>
4315

4316 4317 4318
</div>
</body>
</html>