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