blob: 154bdbfeaf9643eccc03a50d8536d88ec683511e [file] [log] [blame]
Andrew Gerrand7cb21a72012-01-19 11:24:54 +11001<!--{
2 "Title": "The Go Programming Language Specification",
yah01ee55dd62020-01-15 01:34:43 +00003 "Subtitle": "Version of Jan 14, 2020",
Andrew Gerrand48ba6fe2013-10-04 09:45:06 +10004 "Path": "/ref/spec"
Andrew Gerrand7cb21a72012-01-19 11:24:54 +11005}-->
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006
Russ Cox7c4f7cc2009-08-20 11:11:03 -07007<h2 id="Introduction">Introduction</h2>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07008
Robert Griesemerc2d55862009-02-19 16:49:10 -08009<p>
Rob Pike4501d342009-02-19 17:31:36 -080010This is a reference manual for the Go programming language. For
Andrew Gerrand43ad89d2014-07-25 10:28:39 +100011more information and other documents, see <a href="/">golang.org</a>.
Rob Pike4501d342009-02-19 17:31:36 -080012</p>
Robert Griesemer67153582008-12-16 14:45:09 -080013
Robert Griesemerc2d55862009-02-19 16:49:10 -080014<p>
Rob Pike4501d342009-02-19 17:31:36 -080015Go is a general-purpose language designed with systems programming
Rob Pike678625d2009-09-15 09:54:22 -070016in mind. It is strongly typed and garbage-collected and has explicit
Rob Pike4501d342009-02-19 17:31:36 -080017support for concurrent programming. Programs are constructed from
18<i>packages</i>, whose properties allow efficient management of
griesemer0c5b00d2017-10-23 14:08:41 -070019dependencies.
Rob Pike4501d342009-02-19 17:31:36 -080020</p>
21
Robert Griesemerc2d55862009-02-19 16:49:10 -080022<p>
Alberto Donizetti7d30af82019-12-13 12:07:06 +010023The grammar is compact and simple to parse, allowing for easy analysis
24by automatic tools such as integrated development environments.
Rob Pike4501d342009-02-19 17:31:36 -080025</p>
Larry Hosken698c6c02009-09-17 08:05:12 -070026
Russ Cox7c4f7cc2009-08-20 11:11:03 -070027<h2 id="Notation">Notation</h2>
Rob Pike4501d342009-02-19 17:31:36 -080028<p>
Robert Griesemer4d230302008-12-17 15:39:15 -080029The syntax is specified using Extended Backus-Naur Form (EBNF):
Rob Pike4501d342009-02-19 17:31:36 -080030</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -070031
Rob Pikeff70f092009-02-20 13:36:14 -080032<pre class="grammar">
Robert Griesemer32b822f2011-05-13 12:54:51 -070033Production = production_name "=" [ Expression ] "." .
Rob Pike4501d342009-02-19 17:31:36 -080034Expression = Alternative { "|" Alternative } .
Robert Griesemerc2d55862009-02-19 16:49:10 -080035Alternative = Term { Term } .
Robert Griesemer3c7271f2011-05-24 14:18:44 -070036Term = production_name | token [ "…" token ] | Group | Option | Repetition .
Rob Pike4501d342009-02-19 17:31:36 -080037Group = "(" Expression ")" .
Rob Pikec956e902009-04-14 20:10:49 -070038Option = "[" Expression "]" .
Rob Pike4501d342009-02-19 17:31:36 -080039Repetition = "{" Expression "}" .
Robert Griesemerc2d55862009-02-19 16:49:10 -080040</pre>
Robert Griesemerbbfe3122008-10-09 17:12:09 -070041
Rob Pike4501d342009-02-19 17:31:36 -080042<p>
43Productions are expressions constructed from terms and the following
44operators, in increasing precedence:
45</p>
Rob Pikeff70f092009-02-20 13:36:14 -080046<pre class="grammar">
Rob Pike4501d342009-02-19 17:31:36 -080047| alternation
48() grouping
49[] option (0 or 1 times)
50{} repetition (0 to n times)
Robert Griesemerc2d55862009-02-19 16:49:10 -080051</pre>
Robert Griesemer4d230302008-12-17 15:39:15 -080052
Robert Griesemerc2d55862009-02-19 16:49:10 -080053<p>
Rob Pike4501d342009-02-19 17:31:36 -080054Lower-case production names are used to identify lexical tokens.
Robert Griesemer7c1cb372012-02-29 10:39:20 -080055Non-terminals are in CamelCase. Lexical tokens are enclosed in
Rob Pike678625d2009-09-15 09:54:22 -070056double quotes <code>""</code> or back quotes <code>``</code>.
Rob Pike4501d342009-02-19 17:31:36 -080057</p>
58
Robert Griesemerc2d55862009-02-19 16:49:10 -080059<p>
Robert Griesemer3c7271f2011-05-24 14:18:44 -070060The form <code>a … b</code> represents the set of characters from
61<code>a</code> through <code>b</code> as alternatives. The horizontal
Jeremy Jackins7e054262012-03-19 08:26:36 +110062ellipsis <code></code> is also used elsewhere in the spec to informally denote various
Rob Pike8040f9b2012-02-13 14:38:31 +110063enumerations or code snippets that are not further specified. The character <code></code>
Robert Griesemer3c7271f2011-05-24 14:18:44 -070064(as opposed to the three characters <code>...</code>) is not a token of the Go
65language.
Rob Pike4501d342009-02-19 17:31:36 -080066</p>
67
Russ Cox7c4f7cc2009-08-20 11:11:03 -070068<h2 id="Source_code_representation">Source code representation</h2>
Robert Griesemerdf49fb32008-08-28 17:47:53 -070069
Robert Griesemerc2d55862009-02-19 16:49:10 -080070<p>
Robert Griesemere9192752009-12-01 16:15:53 -080071Source code is Unicode text encoded in
Suriyaa Sundararuban1041ac82018-06-13 07:06:04 +000072<a href="https://en.wikipedia.org/wiki/UTF-8">UTF-8</a>. The text is not
Rob Pikeff70f092009-02-20 13:36:14 -080073canonicalized, so a single accented code point is distinct from the
74same character constructed from combining an accent and a letter;
75those are treated as two code points. For simplicity, this document
Rob Pike9dfc6f62012-08-29 14:46:57 -070076will use the unqualified term <i>character</i> to refer to a Unicode code point
77in the source text.
Rob Pikeff70f092009-02-20 13:36:14 -080078</p>
Robert Griesemerc2d55862009-02-19 16:49:10 -080079<p>
Rob Pikeff70f092009-02-20 13:36:14 -080080Each code point is distinct; for instance, upper and lower case letters
81are different characters.
82</p>
Russ Coxb7d9ffe2010-02-16 16:47:18 -080083<p>
Robert Griesemerf42e8832010-02-17 15:50:34 -080084Implementation restriction: For compatibility with other tools, a
85compiler may disallow the NUL character (U+0000) in the source text.
Russ Coxb7d9ffe2010-02-16 16:47:18 -080086</p>
Rob Pikeafac01d2012-09-06 10:37:13 -070087<p>
88Implementation restriction: For compatibility with other tools, a
Rob Pike488350a2012-09-07 10:28:24 -070089compiler may ignore a UTF-8-encoded byte order mark
90(U+FEFF) if it is the first Unicode code point in the source text.
Rob Pike548c65a2013-04-11 11:33:25 -070091A byte order mark may be disallowed anywhere else in the source.
Rob Pikeafac01d2012-09-06 10:37:13 -070092</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -070093
Russ Cox7c4f7cc2009-08-20 11:11:03 -070094<h3 id="Characters">Characters</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -070095
Robert Griesemerc2d55862009-02-19 16:49:10 -080096<p>
Rob Pike4501d342009-02-19 17:31:36 -080097The following terms are used to denote specific Unicode character classes:
98</p>
Robert Griesemerf7ac31362009-07-10 16:06:40 -070099<pre class="ebnf">
Robert Griesemer0e8032c2011-05-05 09:03:00 -0700100newline = /* the Unicode code point U+000A */ .
101unicode_char = /* an arbitrary Unicode code point except newline */ .
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700102unicode_letter = /* a Unicode code point classified as "Letter" */ .
Robert Griesemer212bdd92016-01-05 14:15:49 -0800103unicode_digit = /* a Unicode code point classified as "Number, decimal digit" */ .
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700104</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700105
Rob Pike678625d2009-09-15 09:54:22 -0700106<p>
Suriyaa Sundararuban1041ac82018-06-13 07:06:04 +0000107In <a href="https://www.unicode.org/versions/Unicode8.0.0/">The Unicode Standard 8.0</a>,
Robert Griesemer212bdd92016-01-05 14:15:49 -0800108Section 4.5 "General Category" defines a set of character categories.
109Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Lo
110as Unicode letters, and those in the Number category Nd as Unicode digits.
Rob Pike678625d2009-09-15 09:54:22 -0700111</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700112
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700113<h3 id="Letters_and_digits">Letters and digits</h3>
Rob Pikeff70f092009-02-20 13:36:14 -0800114
115<p>
Rob Pikef27e9f02009-02-23 19:22:05 -0800116The underscore character <code>_</code> (U+005F) is considered a letter.
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700117</p>
118<pre class="ebnf">
Robert Griesemerc2d55862009-02-19 16:49:10 -0800119letter = unicode_letter | "_" .
Robert Griesemer3c7271f2011-05-24 14:18:44 -0700120decimal_digit = "0" … "9" .
Robert Griesemera0836482019-02-04 15:33:19 -0800121binary_digit = "0" | "1" .
Robert Griesemer3c7271f2011-05-24 14:18:44 -0700122octal_digit = "0" … "7" .
123hex_digit = "0" … "9" | "A" … "F" | "a" … "f" .
Robert Griesemerc2d55862009-02-19 16:49:10 -0800124</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700125
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700126<h2 id="Lexical_elements">Lexical elements</h2>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700127
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700128<h3 id="Comments">Comments</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700129
Rob Pikeff70f092009-02-20 13:36:14 -0800130<p>
Robert Griesemer37a09752015-05-29 17:36:26 -0700131Comments serve as program documentation. There are two forms:
Rob Pikeff70f092009-02-20 13:36:14 -0800132</p>
133
Robert Griesemer130ac742009-12-10 16:43:01 -0800134<ol>
135<li>
136<i>Line comments</i> start with the character sequence <code>//</code>
Robert Griesemer37a09752015-05-29 17:36:26 -0700137and stop at the end of the line.
Robert Griesemer130ac742009-12-10 16:43:01 -0800138</li>
139<li>
140<i>General comments</i> start with the character sequence <code>/*</code>
Robert Griesemer37a09752015-05-29 17:36:26 -0700141and stop with the first subsequent character sequence <code>*/</code>.
Robert Griesemer130ac742009-12-10 16:43:01 -0800142</li>
143</ol>
144
145<p>
Robert Griesemer37a09752015-05-29 17:36:26 -0700146A comment cannot start inside a <a href="#Rune_literals">rune</a> or
147<a href="#String_literals">string literal</a>, or inside a comment.
148A general comment containing no newlines acts like a space.
149Any other comment acts like a newline.
Robert Griesemer130ac742009-12-10 16:43:01 -0800150</p>
151
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700152<h3 id="Tokens">Tokens</h3>
Rob Pikeff70f092009-02-20 13:36:14 -0800153
154<p>
155Tokens form the vocabulary of the Go language.
Robert Griesemereb109a72009-12-28 14:40:42 -0800156There are four classes: <i>identifiers</i>, <i>keywords</i>, <i>operators
Robert Griesemer26e726c2017-03-10 17:17:23 -0800157and punctuation</i>, and <i>literals</i>. <i>White space</i>, formed from
Rob Pike4fe41922009-11-07 22:00:59 -0800158spaces (U+0020), horizontal tabs (U+0009),
159carriage returns (U+000D), and newlines (U+000A),
160is ignored except as it separates tokens
Robert Griesemer0e66a132010-09-27 18:59:11 -0700161that would otherwise combine into a single token. Also, a newline or end of file
Robert Griesemereb109a72009-12-28 14:40:42 -0800162may trigger the insertion of a <a href="#Semicolons">semicolon</a>.
Robert Griesemer130ac742009-12-10 16:43:01 -0800163While breaking the input into tokens,
Rob Pikeff70f092009-02-20 13:36:14 -0800164the next token is the longest sequence of characters that form a
165valid token.
166</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700167
Robert Griesemer130ac742009-12-10 16:43:01 -0800168<h3 id="Semicolons">Semicolons</h3>
169
170<p>
171The formal grammar uses semicolons <code>";"</code> as terminators in
172a number of productions. Go programs may omit most of these semicolons
173using the following two rules:
174</p>
175
176<ol>
177<li>
Robert Griesemer130ac742009-12-10 16:43:01 -0800178When the input is broken into tokens, a semicolon is automatically inserted
Robert Griesemer37a09752015-05-29 17:36:26 -0700179into the token stream immediately after a line's final token if that token is
Robert Griesemer130ac742009-12-10 16:43:01 -0800180<ul>
Robert Griesemer3af480372010-05-14 13:11:48 -0700181 <li>an
182 <a href="#Identifiers">identifier</a>
Robert Griesemer130ac742009-12-10 16:43:01 -0800183 </li>
Charles L. Dorian44262d12011-11-01 15:13:33 +0900184
Robert Griesemer3af480372010-05-14 13:11:48 -0700185 <li>an
186 <a href="#Integer_literals">integer</a>,
187 <a href="#Floating-point_literals">floating-point</a>,
188 <a href="#Imaginary_literals">imaginary</a>,
Rob Pike9dfc6f62012-08-29 14:46:57 -0700189 <a href="#Rune_literals">rune</a>, or
Robert Griesemer3af480372010-05-14 13:11:48 -0700190 <a href="#String_literals">string</a> literal
191 </li>
Charles L. Dorian44262d12011-11-01 15:13:33 +0900192
Robert Griesemer3af480372010-05-14 13:11:48 -0700193 <li>one of the <a href="#Keywords">keywords</a>
194 <code>break</code>,
195 <code>continue</code>,
196 <code>fallthrough</code>, or
197 <code>return</code>
198 </li>
Charles L. Dorian44262d12011-11-01 15:13:33 +0900199
Robert Griesemer26e726c2017-03-10 17:17:23 -0800200 <li>one of the <a href="#Operators_and_punctuation">operators and punctuation</a>
Robert Griesemer3af480372010-05-14 13:11:48 -0700201 <code>++</code>,
202 <code>--</code>,
203 <code>)</code>,
204 <code>]</code>, or
205 <code>}</code>
Robert Griesemer130ac742009-12-10 16:43:01 -0800206 </li>
207</ul>
208</li>
209
210<li>
211To allow complex statements to occupy a single line, a semicolon
212may be omitted before a closing <code>")"</code> or <code>"}"</code>.
213</li>
214</ol>
215
216<p>
217To reflect idiomatic use, code examples in this document elide semicolons
218using these rules.
219</p>
220
221
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700222<h3 id="Identifiers">Identifiers</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700223
Rob Pikeff70f092009-02-20 13:36:14 -0800224<p>
225Identifiers name program entities such as variables and types.
226An identifier is a sequence of one or more letters and digits.
227The first character in an identifier must be a letter.
228</p>
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700229<pre class="ebnf">
Robert Griesemerd36d1912009-09-18 11:58:35 -0700230identifier = letter { letter | unicode_digit } .
Robert Griesemerc2d55862009-02-19 16:49:10 -0800231</pre>
Robert Griesemerc2d55862009-02-19 16:49:10 -0800232<pre>
233a
234_x9
235ThisVariableIsExported
236αβ
237</pre>
Robert Griesemer130ac742009-12-10 16:43:01 -0800238
239<p>
Robert Griesemer4e56b332009-09-10 10:14:00 -0700240Some identifiers are <a href="#Predeclared_identifiers">predeclared</a>.
Robert Griesemer130ac742009-12-10 16:43:01 -0800241</p>
242
Robert Griesemer7a4ed4f2008-09-03 15:15:51 -0700243
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700244<h3 id="Keywords">Keywords</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700245
Rob Pikeff70f092009-02-20 13:36:14 -0800246<p>
247The following keywords are reserved and may not be used as identifiers.
248</p>
249<pre class="grammar">
250break default func interface select
251case defer go map struct
252chan else goto package switch
253const fallthrough if range type
254continue for import return var
255</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700256
Robert Griesemer26e726c2017-03-10 17:17:23 -0800257<h3 id="Operators_and_punctuation">Operators and punctuation</h3>
Rob Pikeff70f092009-02-20 13:36:14 -0800258
259<p>
Robert Griesemer26e726c2017-03-10 17:17:23 -0800260The following character sequences represent <a href="#Operators">operators</a>
261(including <a href="#assign_op">assignment operators</a>) and punctuation:
Rob Pikeff70f092009-02-20 13:36:14 -0800262</p>
263<pre class="grammar">
264+ &amp; += &amp;= &amp;&amp; == != ( )
265- | -= |= || &lt; &lt;= [ ]
266* ^ *= ^= &lt;- &gt; &gt;= { }
Robert Griesemer4ed666e2009-08-27 16:45:42 -0700267/ &lt;&lt; /= &lt;&lt;= ++ = := , ;
268% &gt;&gt; %= &gt;&gt;= -- ! ... . :
Robert Griesemer0eb26fa2016-11-18 09:27:18 -0800269 &amp;^ &amp;^=
Rob Pikeff70f092009-02-20 13:36:14 -0800270</pre>
271
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700272<h3 id="Integer_literals">Integer literals</h3>
Rob Pikeff70f092009-02-20 13:36:14 -0800273
274<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -0700275An integer literal is a sequence of digits representing an
276<a href="#Constants">integer constant</a>.
Robert Griesemera0836482019-02-04 15:33:19 -0800277An optional prefix sets a non-decimal base: <code>0b</code> or <code>0B</code>
278for binary, <code>0</code>, <code>0o</code>, or <code>0O</code> for octal,
279and <code>0x</code> or <code>0X</code> for hexadecimal.
280A single <code>0</code> is considered a decimal zero.
281In hexadecimal literals, letters <code>a</code> through <code>f</code>
282and <code>A</code> through <code>F</code> represent values 10 through 15.
283</p>
284
285<p>
286For readability, an underscore character <code>_</code> may appear after
287a base prefix or between successive digits; such underscores do not change
288the literal's value.
Rob Pikeff70f092009-02-20 13:36:14 -0800289</p>
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700290<pre class="ebnf">
Robert Griesemera0836482019-02-04 15:33:19 -0800291int_lit = decimal_lit | binary_lit | octal_lit | hex_lit .
292decimal_lit = "0" | ( "1" … "9" ) [ [ "_" ] decimal_digits ] .
293binary_lit = "0" ( "b" | "B" ) [ "_" ] binary_digits .
294octal_lit = "0" [ "o" | "O" ] [ "_" ] octal_digits .
295hex_lit = "0" ( "x" | "X" ) [ "_" ] hex_digits .
296
297decimal_digits = decimal_digit { [ "_" ] decimal_digit } .
298binary_digits = binary_digit { [ "_" ] binary_digit } .
299octal_digits = octal_digit { [ "_" ] octal_digit } .
300hex_digits = hex_digit { [ "_" ] hex_digit } .
Robert Griesemerc2d55862009-02-19 16:49:10 -0800301</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700302
Robert Griesemerc2d55862009-02-19 16:49:10 -0800303<pre>
30442
Robert Griesemera0836482019-02-04 15:33:19 -08003054_2
Robert Griesemerc2d55862009-02-19 16:49:10 -08003060600
Robert Griesemera0836482019-02-04 15:33:19 -08003070_600
3080o600
3090O600 // second character is capital letter 'O'
Robert Griesemerc2d55862009-02-19 16:49:10 -08003100xBadFace
Robert Griesemera0836482019-02-04 15:33:19 -08003110xBad_Face
3120x_67_7a_2f_cc_40_c6
Robert Griesemerc2d55862009-02-19 16:49:10 -0800313170141183460469231731687303715884105727
Robert Griesemera0836482019-02-04 15:33:19 -0800314170_141183_460469_231731_687303_715884_105727
315
316_42 // an identifier, not an integer literal
31742_ // invalid: _ must separate successive digits
3184__2 // invalid: only one _ at a time
3190_xBadFace // invalid: _ must separate successive digits
Robert Griesemerc2d55862009-02-19 16:49:10 -0800320</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700321
Robert Griesemera0836482019-02-04 15:33:19 -0800322
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700323<h3 id="Floating-point_literals">Floating-point literals</h3>
Robert Griesemera0836482019-02-04 15:33:19 -0800324
Rob Pikeff70f092009-02-20 13:36:14 -0800325<p>
Robert Griesemera0836482019-02-04 15:33:19 -0800326A floating-point literal is a decimal or hexadecimal representation of a
Robert Griesemer19b1d352009-09-24 19:36:48 -0700327<a href="#Constants">floating-point constant</a>.
Rob Pikeff70f092009-02-20 13:36:14 -0800328</p>
Robert Griesemera0836482019-02-04 15:33:19 -0800329
330<p>
331A decimal floating-point literal consists of an integer part (decimal digits),
332a decimal point, a fractional part (decimal digits), and an exponent part
333(<code>e</code> or <code>E</code> followed by an optional sign and decimal digits).
334One of the integer part or the fractional part may be elided; one of the decimal point
335or the exponent part may be elided.
336An exponent value exp scales the mantissa (integer and fractional part) by 10<sup>exp</sup>.
337</p>
338
339<p>
340A hexadecimal floating-point literal consists of a <code>0x</code> or <code>0X</code>
341prefix, an integer part (hexadecimal digits), a radix point, a fractional part (hexadecimal digits),
342and an exponent part (<code>p</code> or <code>P</code> followed by an optional sign and decimal digits).
343One of the integer part or the fractional part may be elided; the radix point may be elided as well,
344but the exponent part is required. (This syntax matches the one given in IEEE 754-2008 §5.12.3.)
345An exponent value exp scales the mantissa (integer and fractional part) by 2<sup>exp</sup>.
346</p>
347
348<p>
349For readability, an underscore character <code>_</code> may appear after
350a base prefix or between successive digits; such underscores do not change
351the literal value.
352</p>
353
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700354<pre class="ebnf">
Robert Griesemera0836482019-02-04 15:33:19 -0800355float_lit = decimal_float_lit | hex_float_lit .
356
357decimal_float_lit = decimal_digits "." [ decimal_digits ] [ decimal_exponent ] |
358 decimal_digits decimal_exponent |
359 "." decimal_digits [ decimal_exponent ] .
360decimal_exponent = ( "e" | "E" ) [ "+" | "-" ] decimal_digits .
361
362hex_float_lit = "0" ( "x" | "X" ) hex_mantissa hex_exponent .
363hex_mantissa = [ "_" ] hex_digits "." [ hex_digits ] |
364 [ "_" ] hex_digits |
365 "." hex_digits .
366hex_exponent = ( "p" | "P" ) [ "+" | "-" ] decimal_digits .
Robert Griesemerc2d55862009-02-19 16:49:10 -0800367</pre>
Robert Griesemerad711102008-09-11 17:48:20 -0700368
Robert Griesemerc2d55862009-02-19 16:49:10 -0800369<pre>
3700.
Rob Pike72970872010-03-04 12:35:16 -080037172.40
Robert Griesemera0836482019-02-04 15:33:19 -0800372072.40 // == 72.40
Robert Griesemerc2d55862009-02-19 16:49:10 -08003732.71828
3741.e+0
3756.67428e-11
3761E6
377.25
378.12345E+5
Robert Griesemera0836482019-02-04 15:33:19 -08003791_5. // == 15.0
3800.15e+0_2 // == 15.0
381
3820x1p-2 // == 0.25
3830x2.p10 // == 2048.0
3840x1.Fp+0 // == 1.9375
3850X.8p-0 // == 0.5
3860X_1FFFP-16 // == 0.1249847412109375
3870x15e-2 // == 0x15e - 2 (integer subtraction)
388
3890x.p1 // invalid: mantissa has no digits
3901p-2 // invalid: p exponent requires hexadecimal mantissa
3910x1.5e-2 // invalid: hexadecimal mantissa requires p exponent
3921_.5 // invalid: _ must separate successive digits
3931._5 // invalid: _ must separate successive digits
3941.5_e1 // invalid: _ must separate successive digits
3951.5e_1 // invalid: _ must separate successive digits
3961.5e1_ // invalid: _ must separate successive digits
Robert Griesemerc2d55862009-02-19 16:49:10 -0800397</pre>
Robert Griesemerad711102008-09-11 17:48:20 -0700398
Robert Griesemera0836482019-02-04 15:33:19 -0800399
Rob Pike72970872010-03-04 12:35:16 -0800400<h3 id="Imaginary_literals">Imaginary literals</h3>
Robert Griesemera0836482019-02-04 15:33:19 -0800401
Rob Pike72970872010-03-04 12:35:16 -0800402<p>
Robert Griesemera0836482019-02-04 15:33:19 -0800403An imaginary literal represents the imaginary part of a
Rob Pike72970872010-03-04 12:35:16 -0800404<a href="#Constants">complex constant</a>.
Robert Griesemera0836482019-02-04 15:33:19 -0800405It consists of an <a href="#Integer_literals">integer</a> or
406<a href="#Floating-point_literals">floating-point</a> literal
407followed by the lower-case letter <code>i</code>.
408The value of an imaginary literal is the value of the respective
409integer or floating-point literal multiplied by the imaginary unit <i>i</i>.
Rob Pike72970872010-03-04 12:35:16 -0800410</p>
Robert Griesemera0836482019-02-04 15:33:19 -0800411
Rob Pike72970872010-03-04 12:35:16 -0800412<pre class="ebnf">
Robert Griesemera0836482019-02-04 15:33:19 -0800413imaginary_lit = (decimal_digits | int_lit | float_lit) "i" .
Rob Pike72970872010-03-04 12:35:16 -0800414</pre>
415
Robert Griesemera0836482019-02-04 15:33:19 -0800416<p>
417For backward compatibility, an imaginary literal's integer part consisting
418entirely of decimal digits (and possibly underscores) is considered a decimal
419integer, even if it starts with a leading <code>0</code>.
420</p>
421
Rob Pike72970872010-03-04 12:35:16 -0800422<pre>
4230i
Robert Griesemera0836482019-02-04 15:33:19 -08004240123i // == 123i for backward-compatibility
4250o123i // == 0o123 * 1i == 83i
4260xabci // == 0xabc * 1i == 2748i
Rob Pike72970872010-03-04 12:35:16 -08004270.i
4282.71828i
4291.e+0i
4306.67428e-11i
4311E6i
432.25i
433.12345E+5i
Robert Griesemera0836482019-02-04 15:33:19 -08004340x1p-2i // == 0x1p-2 * 1i == 0.25i
Rob Pike72970872010-03-04 12:35:16 -0800435</pre>
436
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700437
Rob Pike9dfc6f62012-08-29 14:46:57 -0700438<h3 id="Rune_literals">Rune literals</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700439
Rob Pike4501d342009-02-19 17:31:36 -0800440<p>
Rob Pike9dfc6f62012-08-29 14:46:57 -0700441A rune literal represents a <a href="#Constants">rune constant</a>,
442an integer value identifying a Unicode code point.
Robert Griesemer37a09752015-05-29 17:36:26 -0700443A rune literal is expressed as one or more characters enclosed in single quotes,
444as in <code>'x'</code> or <code>'\n'</code>.
445Within the quotes, any character may appear except newline and unescaped single
446quote. A single quoted character represents the Unicode value
Rob Pike9dfc6f62012-08-29 14:46:57 -0700447of the character itself,
Rob Pikeff70f092009-02-20 13:36:14 -0800448while multi-character sequences beginning with a backslash encode
449values in various formats.
Rob Pike4501d342009-02-19 17:31:36 -0800450</p>
Robert Griesemera0836482019-02-04 15:33:19 -0800451
Rob Pikeff70f092009-02-20 13:36:14 -0800452<p>
453The simplest form represents the single character within the quotes;
454since Go source text is Unicode characters encoded in UTF-8, multiple
455UTF-8-encoded bytes may represent a single integer value. For
Rob Pikef27e9f02009-02-23 19:22:05 -0800456instance, the literal <code>'a'</code> holds a single byte representing
457a literal <code>a</code>, Unicode U+0061, value <code>0x61</code>, while
458<code>'ä'</code> holds two bytes (<code>0xc3</code> <code>0xa4</code>) representing
459a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>.
Rob Pikeff70f092009-02-20 13:36:14 -0800460</p>
Robert Griesemera0836482019-02-04 15:33:19 -0800461
Rob Pikeff70f092009-02-20 13:36:14 -0800462<p>
Rob Pike9dfc6f62012-08-29 14:46:57 -0700463Several backslash escapes allow arbitrary values to be encoded as
Oling Cat845f4d62012-09-05 14:53:13 +1000464ASCII text. There are four ways to represent the integer value
Rob Pikef27e9f02009-02-23 19:22:05 -0800465as a numeric constant: <code>\x</code> followed by exactly two hexadecimal
466digits; <code>\u</code> followed by exactly four hexadecimal digits;
467<code>\U</code> followed by exactly eight hexadecimal digits, and a
468plain backslash <code>\</code> followed by exactly three octal digits.
Rob Pikeff70f092009-02-20 13:36:14 -0800469In each case the value of the literal is the value represented by
470the digits in the corresponding base.
471</p>
Robert Griesemera0836482019-02-04 15:33:19 -0800472
Rob Pikeff70f092009-02-20 13:36:14 -0800473<p>
474Although these representations all result in an integer, they have
475different valid ranges. Octal escapes must represent a value between
Rob Pike678625d2009-09-15 09:54:22 -07004760 and 255 inclusive. Hexadecimal escapes satisfy this condition
477by construction. The escapes <code>\u</code> and <code>\U</code>
Rob Pikeff70f092009-02-20 13:36:14 -0800478represent Unicode code points so within them some values are illegal,
Rob Pikef27e9f02009-02-23 19:22:05 -0800479in particular those above <code>0x10FFFF</code> and surrogate halves.
Rob Pikeff70f092009-02-20 13:36:14 -0800480</p>
Robert Griesemera0836482019-02-04 15:33:19 -0800481
Rob Pikeff70f092009-02-20 13:36:14 -0800482<p>
483After a backslash, certain single-character escapes represent special values:
484</p>
Robert Griesemera0836482019-02-04 15:33:19 -0800485
Rob Pikeff70f092009-02-20 13:36:14 -0800486<pre class="grammar">
487\a U+0007 alert or bell
488\b U+0008 backspace
489\f U+000C form feed
490\n U+000A line feed or newline
491\r U+000D carriage return
492\t U+0009 horizontal tab
493\v U+000b vertical tab
494\\ U+005c backslash
Rob Pike9dfc6f62012-08-29 14:46:57 -0700495\' U+0027 single quote (valid escape only within rune literals)
Rob Pikeff70f092009-02-20 13:36:14 -0800496\" U+0022 double quote (valid escape only within string literals)
Robert Griesemerc2d55862009-02-19 16:49:10 -0800497</pre>
Robert Griesemera0836482019-02-04 15:33:19 -0800498
Robert Griesemerc2d55862009-02-19 16:49:10 -0800499<p>
Rob Pike9dfc6f62012-08-29 14:46:57 -0700500All other sequences starting with a backslash are illegal inside rune literals.
Rob Pike4501d342009-02-19 17:31:36 -0800501</p>
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700502<pre class="ebnf">
Robert Griesemerc863db42013-01-07 18:02:58 -0800503rune_lit = "'" ( unicode_value | byte_value ) "'" .
Rob Pikeff70f092009-02-20 13:36:14 -0800504unicode_value = unicode_char | little_u_value | big_u_value | escaped_char .
505byte_value = octal_byte_value | hex_byte_value .
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700506octal_byte_value = `\` octal_digit octal_digit octal_digit .
507hex_byte_value = `\` "x" hex_digit hex_digit .
508little_u_value = `\` "u" hex_digit hex_digit hex_digit hex_digit .
509big_u_value = `\` "U" hex_digit hex_digit hex_digit hex_digit
Rob Pikeff70f092009-02-20 13:36:14 -0800510 hex_digit hex_digit hex_digit hex_digit .
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700511escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
Rob Pikeff70f092009-02-20 13:36:14 -0800512</pre>
Robert Griesemer19b1d352009-09-24 19:36:48 -0700513
Robert Griesemerc2d55862009-02-19 16:49:10 -0800514<pre>
515'a'
516'ä'
517'本'
518'\t'
519'\000'
520'\007'
521'\377'
522'\x07'
523'\xff'
524'\u12e4'
525'\U00101234'
Robert Griesemer37a09752015-05-29 17:36:26 -0700526'\'' // rune literal containing single quote character
Rob Pike9dfc6f62012-08-29 14:46:57 -0700527'aa' // illegal: too many characters
528'\xa' // illegal: too few hexadecimal digits
529'\0' // illegal: too few octal digits
530'\uDFFF' // illegal: surrogate half
531'\U00110000' // illegal: invalid Unicode code point
Robert Griesemerc2d55862009-02-19 16:49:10 -0800532</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700533
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700534
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700535<h3 id="String_literals">String literals</h3>
Rob Pikeff70f092009-02-20 13:36:14 -0800536
537<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -0700538A string literal represents a <a href="#Constants">string constant</a>
539obtained from concatenating a sequence of characters. There are two forms:
540raw string literals and interpreted string literals.
Rob Pikeff70f092009-02-20 13:36:14 -0800541</p>
Robert Griesemera0836482019-02-04 15:33:19 -0800542
Rob Pikeff70f092009-02-20 13:36:14 -0800543<p>
Robert Griesemer37a09752015-05-29 17:36:26 -0700544Raw string literals are character sequences between back quotes, as in
545<code>`foo`</code>. Within the quotes, any character may appear except
Robert Griesemerdb7a6222009-06-18 13:51:14 -0700546back quote. The value of a raw string literal is the
Rob Pike9dfc6f62012-08-29 14:46:57 -0700547string composed of the uninterpreted (implicitly UTF-8-encoded) characters
548between the quotes;
Robert Griesemerdb7a6222009-06-18 13:51:14 -0700549in particular, backslashes have no special meaning and the string may
Robert Griesemer11b7c892011-12-15 10:51:51 -0800550contain newlines.
Ian Lance Taylor2a627da2014-05-16 12:20:03 -0700551Carriage return characters ('\r') inside raw string literals
Rob Pikec26ca912011-12-14 21:52:41 -0800552are discarded from the raw string value.
Rob Pikeff70f092009-02-20 13:36:14 -0800553</p>
Robert Griesemera0836482019-02-04 15:33:19 -0800554
Rob Pikeff70f092009-02-20 13:36:14 -0800555<p>
556Interpreted string literals are character sequences between double
Robert Griesemer37a09752015-05-29 17:36:26 -0700557quotes, as in <code>&quot;bar&quot;</code>.
558Within the quotes, any character may appear except newline and unescaped double quote.
559The text between the quotes forms the
Rob Pikeff70f092009-02-20 13:36:14 -0800560value of the literal, with backslash escapes interpreted as they
Robin Eklindf82097f2014-09-03 10:44:33 -0700561are in <a href="#Rune_literals">rune literals</a> (except that <code>\'</code> is illegal and
Rob Pike9dfc6f62012-08-29 14:46:57 -0700562<code>\"</code> is legal), with the same restrictions.
563The three-digit octal (<code>\</code><i>nnn</i>)
Robert Griesemere9192752009-12-01 16:15:53 -0800564and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual
Rob Pikeff70f092009-02-20 13:36:14 -0800565<i>bytes</i> of the resulting string; all other escapes represent
566the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
Rob Pikef27e9f02009-02-23 19:22:05 -0800567Thus inside a string literal <code>\377</code> and <code>\xFF</code> represent
568a single byte of value <code>0xFF</code>=255, while <code>ÿ</code>,
569<code>\u00FF</code>, <code>\U000000FF</code> and <code>\xc3\xbf</code> represent
Robert Griesemere1e76192009-09-25 14:11:03 -0700570the two bytes <code>0xc3</code> <code>0xbf</code> of the UTF-8 encoding of character
Rob Pikeff70f092009-02-20 13:36:14 -0800571U+00FF.
572</p>
573
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700574<pre class="ebnf">
Rob Pikeff70f092009-02-20 13:36:14 -0800575string_lit = raw_string_lit | interpreted_string_lit .
Robert Griesemer0e8032c2011-05-05 09:03:00 -0700576raw_string_lit = "`" { unicode_char | newline } "`" .
Robert Griesemerd4d4ff02009-10-19 13:13:59 -0700577interpreted_string_lit = `"` { unicode_value | byte_value } `"` .
Robert Griesemerc2d55862009-02-19 16:49:10 -0800578</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700579
Robert Griesemerc2d55862009-02-19 16:49:10 -0800580<pre>
Robert Griesemer37a09752015-05-29 17:36:26 -0700581`abc` // same as "abc"
Robert Griesemerdb7a6222009-06-18 13:51:14 -0700582`\n
Robert Griesemer37a09752015-05-29 17:36:26 -0700583\n` // same as "\\n\n\\n"
Robert Griesemerc2d55862009-02-19 16:49:10 -0800584"\n"
Robert Griesemer37a09752015-05-29 17:36:26 -0700585"\"" // same as `"`
Robert Griesemerc2d55862009-02-19 16:49:10 -0800586"Hello, world!\n"
587"日本語"
588"\u65e5本\U00008a9e"
589"\xff\u00FF"
Robert Griesemer37a09752015-05-29 17:36:26 -0700590"\uD800" // illegal: surrogate half
591"\U00110000" // illegal: invalid Unicode code point
Robert Griesemerc2d55862009-02-19 16:49:10 -0800592</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700593
Rob Pikeff70f092009-02-20 13:36:14 -0800594<p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700595These examples all represent the same string:
Rob Pikeff70f092009-02-20 13:36:14 -0800596</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700597
Robert Griesemerc2d55862009-02-19 16:49:10 -0800598<pre>
Rob Pikeff70f092009-02-20 13:36:14 -0800599"日本語" // UTF-8 input text
600`日本語` // UTF-8 input text as a raw literal
Rob Pike9dfc6f62012-08-29 14:46:57 -0700601"\u65e5\u672c\u8a9e" // the explicit Unicode code points
602"\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points
603"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes
Robert Griesemerc2d55862009-02-19 16:49:10 -0800604</pre>
Robert Griesemercd499272008-09-29 12:09:00 -0700605
Robert Griesemerc2d55862009-02-19 16:49:10 -0800606<p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700607If the source code represents a character as two code points, such as
608a combining form involving an accent and a letter, the result will be
Rob Pike9dfc6f62012-08-29 14:46:57 -0700609an error if placed in a rune literal (it is not a single code
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700610point), and will appear as two code points if placed in a string
611literal.
Rob Pikeff70f092009-02-20 13:36:14 -0800612</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700613
Robert Griesemer19b1d352009-09-24 19:36:48 -0700614
615<h2 id="Constants">Constants</h2>
616
Russ Coxa9336352011-12-08 21:48:19 -0500617<p>There are <i>boolean constants</i>,
Rob Pike9dfc6f62012-08-29 14:46:57 -0700618<i>rune constants</i>,
Russ Coxa9336352011-12-08 21:48:19 -0500619<i>integer constants</i>,
Rob Pike72970872010-03-04 12:35:16 -0800620<i>floating-point constants</i>, <i>complex constants</i>,
Robert Griesemerf3310122013-07-25 09:35:55 -0700621and <i>string constants</i>. Rune, integer, floating-point,
Rob Pike72970872010-03-04 12:35:16 -0800622and complex constants are
Robert Griesemer19b1d352009-09-24 19:36:48 -0700623collectively called <i>numeric constants</i>.
624</p>
Rob Pike678625d2009-09-15 09:54:22 -0700625
626<p>
Russ Coxa9336352011-12-08 21:48:19 -0500627A constant value is represented by a
Rob Pike9dfc6f62012-08-29 14:46:57 -0700628<a href="#Rune_literals">rune</a>,
Robert Griesemer19b1d352009-09-24 19:36:48 -0700629<a href="#Integer_literals">integer</a>,
630<a href="#Floating-point_literals">floating-point</a>,
Rob Pike72970872010-03-04 12:35:16 -0800631<a href="#Imaginary_literals">imaginary</a>,
Russ Coxa9336352011-12-08 21:48:19 -0500632or
Robert Griesemer19b1d352009-09-24 19:36:48 -0700633<a href="#String_literals">string</a> literal,
634an identifier denoting a constant,
Robert Griesemer27693562011-06-13 16:47:33 -0700635a <a href="#Constant_expressions">constant expression</a>,
636a <a href="#Conversions">conversion</a> with a result that is a constant, or
Russ Coxf4429182010-07-01 17:49:47 -0700637the result value of some built-in functions such as
638<code>unsafe.Sizeof</code> applied to any value,
639<code>cap</code> or <code>len</code> applied to
640<a href="#Length_and_capacity">some expressions</a>,
Rob Pike72970872010-03-04 12:35:16 -0800641<code>real</code> and <code>imag</code> applied to a complex constant
Robert Griesemerb94c0d22011-01-19 23:07:21 -0500642and <code>complex</code> applied to numeric constants.
Robert Griesemer19b1d352009-09-24 19:36:48 -0700643The boolean truth values are represented by the predeclared constants
644<code>true</code> and <code>false</code>. The predeclared identifier
645<a href="#Iota">iota</a> denotes an integer constant.
Rob Pike678625d2009-09-15 09:54:22 -0700646</p>
647
Robert Griesemer19b1d352009-09-24 19:36:48 -0700648<p>
Rob Pike72970872010-03-04 12:35:16 -0800649In general, complex constants are a form of
650<a href="#Constant_expressions">constant expression</a>
651and are discussed in that section.
652</p>
653
654<p>
Robert Griesemer55ecda42015-09-17 18:10:20 -0700655Numeric constants represent exact values of arbitrary precision and do not overflow.
656Consequently, there are no constants denoting the IEEE-754 negative zero, infinity,
657and not-a-number values.
Robert Griesemer19b1d352009-09-24 19:36:48 -0700658</p>
659
660<p>
Robert Griesemer47094dc2014-09-30 11:44:29 -0700661Constants may be <a href="#Types">typed</a> or <i>untyped</i>.
Robert Griesemer19b1d352009-09-24 19:36:48 -0700662Literal constants, <code>true</code>, <code>false</code>, <code>iota</code>,
663and certain <a href="#Constant_expressions">constant expressions</a>
664containing only untyped constant operands are untyped.
665</p>
666
667<p>
668A constant may be given a type explicitly by a <a href="#Constant_declarations">constant declaration</a>
669or <a href="#Conversions">conversion</a>, or implicitly when used in a
670<a href="#Variable_declarations">variable declaration</a> or an
671<a href="#Assignments">assignment</a> or as an
672operand in an <a href="#Expressions">expression</a>.
673It is an error if the constant value
griesemerb40831b2017-08-21 15:47:51 +0200674cannot be <a href="#Representability">represented</a> as a value of the respective type.
Robert Griesemer19b1d352009-09-24 19:36:48 -0700675</p>
676
677<p>
Robert Griesemer47094dc2014-09-30 11:44:29 -0700678An untyped constant has a <i>default type</i> which is the type to which the
679constant is implicitly converted in contexts where a typed value is required,
680for instance, in a <a href="#Short_variable_declarations">short variable declaration</a>
681such as <code>i := 0</code> where there is no explicit type.
682The default type of an untyped constant is <code>bool</code>, <code>rune</code>,
683<code>int</code>, <code>float64</code>, <code>complex128</code> or <code>string</code>
684respectively, depending on whether it is a boolean, rune, integer, floating-point,
685complex, or string constant.
686</p>
687
688<p>
Ian Lance Taylor9126c652012-02-13 11:25:56 -0800689Implementation restriction: Although numeric constants have arbitrary
690precision in the language, a compiler may implement them using an
691internal representation with limited precision. That said, every
692implementation must:
Robert Griesemer19b1d352009-09-24 19:36:48 -0700693</p>
Robert Griesemera0836482019-02-04 15:33:19 -0800694
Ian Lance Taylor9126c652012-02-13 11:25:56 -0800695<ul>
696 <li>Represent integer constants with at least 256 bits.</li>
Robert Griesemer19b1d352009-09-24 19:36:48 -0700697
Ian Lance Taylor9126c652012-02-13 11:25:56 -0800698 <li>Represent floating-point constants, including the parts of
699 a complex constant, with a mantissa of at least 256 bits
Robert Griesemer8fbfdad2015-12-10 11:18:41 -0800700 and a signed binary exponent of at least 16 bits.</li>
Ian Lance Taylor9126c652012-02-13 11:25:56 -0800701
702 <li>Give an error if unable to represent an integer constant
703 precisely.</li>
704
705 <li>Give an error if unable to represent a floating-point or
706 complex constant due to overflow.</li>
707
708 <li>Round to the nearest representable constant if unable to
709 represent a floating-point or complex constant due to limits
710 on precision.</li>
711</ul>
Robert Griesemera0836482019-02-04 15:33:19 -0800712
Ian Lance Taylor9126c652012-02-13 11:25:56 -0800713<p>
714These requirements apply both to literal constants and to the result
715of evaluating <a href="#Constant_expressions">constant
716expressions</a>.
717</p>
Robert Griesemer19b1d352009-09-24 19:36:48 -0700718
Robert Griesemera0836482019-02-04 15:33:19 -0800719
Robert Griesemer6962c152014-10-16 15:08:49 -0700720<h2 id="Variables">Variables</h2>
721
722<p>
723A variable is a storage location for holding a <i>value</i>.
724The set of permissible values is determined by the
725variable's <i><a href="#Types">type</a></i>.
726</p>
727
728<p>
729A <a href="#Variable_declarations">variable declaration</a>
730or, for function parameters and results, the signature
731of a <a href="#Function_declarations">function declaration</a>
732or <a href="#Function_literals">function literal</a> reserves
733storage for a named variable.
734
735Calling the built-in function <a href="#Allocation"><code>new</code></a>
736or taking the address of a <a href="#Composite_literals">composite literal</a>
737allocates storage for a variable at run time.
738Such an anonymous variable is referred to via a (possibly implicit)
739<a href="#Address_operators">pointer indirection</a>.
740</p>
741
742<p>
743<i>Structured</i> variables of <a href="#Array_types">array</a>, <a href="#Slice_types">slice</a>,
744and <a href="#Struct_types">struct</a> types have elements and fields that may
745be <a href="#Address_operators">addressed</a> individually. Each such element
746acts like a variable.
747</p>
748
749<p>
Robert Griesemer2d9378c2015-07-27 13:30:16 -0700750The <i>static type</i> (or just <i>type</i>) of a variable is the
Robert Griesemer6962c152014-10-16 15:08:49 -0700751type given in its declaration, the type provided in the
752<code>new</code> call or composite literal, or the type of
753an element of a structured variable.
754Variables of interface type also have a distinct <i>dynamic type</i>,
755which is the concrete type of the value assigned to the variable at run time
756(unless the value is the predeclared identifier <code>nil</code>,
757which has no type).
758The dynamic type may vary during execution but values stored in interface
759variables are always <a href="#Assignability">assignable</a>
Robert Griesemer2d9378c2015-07-27 13:30:16 -0700760to the static type of the variable.
761</p>
Robert Griesemer6962c152014-10-16 15:08:49 -0700762
763<pre>
764var x interface{} // x is nil and has static type interface{}
765var v *T // v has value nil, static type *T
766x = 42 // x has value 42 and dynamic type int
767x = v // x has value (*T)(nil) and dynamic type *T
768</pre>
769
770<p>
771A variable's value is retrieved by referring to the variable in an
772<a href="#Expressions">expression</a>; it is the most recent value
773<a href="#Assignments">assigned</a> to the variable.
774If a variable has not yet been assigned a value, its value is the
775<a href="#The_zero_value">zero value</a> for its type.
776</p>
777
778
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700779<h2 id="Types">Types</h2>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700780
Robert Griesemerc2d55862009-02-19 16:49:10 -0800781<p>
Robert Griesemer56c9b512017-02-02 15:43:56 -0800782A type determines a set of values together with operations and methods specific
783to those values. A type may be denoted by a <i>type name</i>, if it has one,
784or specified using a <i>type literal</i>, which composes a type from existing types.
Rob Pike5af7de32009-02-24 15:17:59 -0800785</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700786
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700787<pre class="ebnf">
Rob Pike8f2330d2009-02-25 16:20:44 -0800788Type = TypeName | TypeLit | "(" Type ")" .
Robert Griesemer809e06b2012-06-26 11:49:19 -0700789TypeName = identifier | QualifiedIdent .
Rob Pike8f2330d2009-02-25 16:20:44 -0800790TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
791 SliceType | MapType | ChannelType .
Robert Griesemerc2d55862009-02-19 16:49:10 -0800792</pre>
Robert Griesemer434c6052008-11-07 13:34:37 -0800793
Robert Griesemerc2d55862009-02-19 16:49:10 -0800794<p>
Robert Griesemer9b49ac02018-01-22 16:20:01 -0800795The language <a href="#Predeclared_identifiers">predeclares</a> certain type names.
796Others are introduced with <a href="#Type_declarations">type declarations</a>.
Robert Griesemerfc61b772009-09-28 14:10:20 -0700797<i>Composite types</i>&mdash;array, struct, pointer, function,
798interface, slice, map, and channel types&mdash;may be constructed using
799type literals.
Rob Pike5af7de32009-02-24 15:17:59 -0800800</p>
Robert Griesemer7abfcd92008-10-07 17:14:30 -0700801
Rob Pike5af7de32009-02-24 15:17:59 -0800802<p>
Robert Griesemer7bc03712010-06-07 15:49:39 -0700803Each type <code>T</code> has an <i>underlying type</i>: If <code>T</code>
Robert Griesemer8d77d2c2014-03-05 19:37:44 -0800804is one of the predeclared boolean, numeric, or string types, or a type literal,
805the corresponding underlying
Robert Griesemer7bc03712010-06-07 15:49:39 -0700806type is <code>T</code> itself. Otherwise, <code>T</code>'s underlying type
807is the underlying type of the type to which <code>T</code> refers in its
808<a href="#Type_declarations">type declaration</a>.
809</p>
810
811<pre>
Robert Griesemer56c9b512017-02-02 15:43:56 -0800812type (
813 A1 = string
814 A2 = A1
815)
816
817type (
818 B1 string
819 B2 B1
820 B3 []B1
821 B4 B3
822)
Robert Griesemer7bc03712010-06-07 15:49:39 -0700823</pre>
824
825<p>
Robert Griesemer56c9b512017-02-02 15:43:56 -0800826The underlying type of <code>string</code>, <code>A1</code>, <code>A2</code>, <code>B1</code>,
827and <code>B2</code> is <code>string</code>.
828The underlying type of <code>[]B1</code>, <code>B3</code>, and <code>B4</code> is <code>[]B1</code>.
Robert Griesemer7bc03712010-06-07 15:49:39 -0700829</p>
830
Robert Griesemer2a838d62011-02-08 13:31:01 -0800831<h3 id="Method_sets">Method sets</h3>
Robert Griesemer7bc03712010-06-07 15:49:39 -0700832<p>
Robert Griesemer2c83f1e2014-05-22 12:23:25 -0700833A type may have a <i>method set</i> associated with it.
Robert Griesemer19b1d352009-09-24 19:36:48 -0700834The method set of an <a href="#Interface_types">interface type</a> is its interface.
Robert Griesemer2c83f1e2014-05-22 12:23:25 -0700835The method set of any other type <code>T</code> consists of all
836<a href="#Method_declarations">methods</a> declared with receiver type <code>T</code>.
837The method set of the corresponding <a href="#Pointer_types">pointer type</a> <code>*T</code>
838is the set of all methods declared with receiver <code>*T</code> or <code>T</code>
Robert Griesemer56809d02009-05-20 11:02:48 -0700839(that is, it also contains the method set of <code>T</code>).
Robert Griesemerf8b41232017-01-10 16:19:14 -0800840Further rules apply to structs containing embedded fields, as described
Robert Griesemer787adb62012-06-04 14:24:10 -0700841in the section on <a href="#Struct_types">struct types</a>.
Robert Griesemer56809d02009-05-20 11:02:48 -0700842Any other type has an empty method set.
Robert Griesemer103c9db2012-03-01 13:57:49 -0800843In a method set, each method must have a
Robert Griesemer2c83f1e2014-05-22 12:23:25 -0700844<a href="#Uniqueness_of_identifiers">unique</a>
845non-<a href="#Blank_identifier">blank</a> <a href="#MethodName">method name</a>.
Rob Pike5af7de32009-02-24 15:17:59 -0800846</p>
Robert Griesemer1f3e8422008-09-29 18:41:30 -0700847
Russ Coxfd2a5112012-02-08 14:28:51 -0500848<p>
849The method set of a type determines the interfaces that the
850type <a href="#Interface_types">implements</a>
851and the methods that can be <a href="#Calls">called</a>
852using a receiver of that type.
853</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700854
Robert Griesemer19b1d352009-09-24 19:36:48 -0700855<h3 id="Boolean_types">Boolean types</h3>
856
Stefan Nilssonc50074e2012-02-29 15:07:52 -0800857<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -0700858A <i>boolean type</i> represents the set of Boolean truth values
859denoted by the predeclared constants <code>true</code>
griesemer4a2391e2017-09-19 14:35:15 +0200860and <code>false</code>. The predeclared boolean type is <code>bool</code>;
861it is a <a href="#Type_definitions">defined type</a>.
Stefan Nilssonc50074e2012-02-29 15:07:52 -0800862</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700863
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700864<h3 id="Numeric_types">Numeric types</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700865
Rob Pike5af7de32009-02-24 15:17:59 -0800866<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -0700867A <i>numeric type</i> represents sets of integer or floating-point values.
868The predeclared architecture-independent numeric types are:
Rob Pike5af7de32009-02-24 15:17:59 -0800869</p>
Robert Griesemerebf14c62008-10-30 14:50:23 -0700870
Rob Pikeff70f092009-02-20 13:36:14 -0800871<pre class="grammar">
Rob Pike72970872010-03-04 12:35:16 -0800872uint8 the set of all unsigned 8-bit integers (0 to 255)
873uint16 the set of all unsigned 16-bit integers (0 to 65535)
874uint32 the set of all unsigned 32-bit integers (0 to 4294967295)
875uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700876
Rob Pike72970872010-03-04 12:35:16 -0800877int8 the set of all signed 8-bit integers (-128 to 127)
878int16 the set of all signed 16-bit integers (-32768 to 32767)
879int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)
880int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700881
Rob Pike72970872010-03-04 12:35:16 -0800882float32 the set of all IEEE-754 32-bit floating-point numbers
883float64 the set of all IEEE-754 64-bit floating-point numbers
884
885complex64 the set of all complex numbers with float32 real and imaginary parts
886complex128 the set of all complex numbers with float64 real and imaginary parts
Rob Pike5af7de32009-02-24 15:17:59 -0800887
Robert Griesemerb910a272011-11-01 01:09:22 -0400888byte alias for uint8
Russ Coxd7f050a2011-12-09 00:11:43 -0500889rune alias for int32
Robert Griesemerc2d55862009-02-19 16:49:10 -0800890</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700891
Rob Pike5af7de32009-02-24 15:17:59 -0800892<p>
Robert Griesemere9192752009-12-01 16:15:53 -0800893The value of an <i>n</i>-bit integer is <i>n</i> bits wide and represented using
Suriyaa Sundararuban1041ac82018-06-13 07:06:04 +0000894<a href="https://en.wikipedia.org/wiki/Two's_complement">two's complement arithmetic</a>.
Rob Pike5af7de32009-02-24 15:17:59 -0800895</p>
Robert Griesemer9dfb2ea2008-12-12 10:30:10 -0800896
Rob Pike5af7de32009-02-24 15:17:59 -0800897<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -0700898There is also a set of predeclared numeric types with implementation-specific sizes:
Rob Pike5af7de32009-02-24 15:17:59 -0800899</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700900
Rob Pikeff70f092009-02-20 13:36:14 -0800901<pre class="grammar">
Robert Griesemercfe92112009-06-18 13:29:40 -0700902uint either 32 or 64 bits
Robert Griesemer97025eb2011-01-13 10:24:04 -0800903int same size as uint
Robert Griesemercfe92112009-06-18 13:29:40 -0700904uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value
Robert Griesemerc2d55862009-02-19 16:49:10 -0800905</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700906
Robert Griesemerc2d55862009-02-19 16:49:10 -0800907<p>
griesemer4a2391e2017-09-19 14:35:15 +0200908To avoid portability issues all numeric types are <a href="#Type_definitions">defined
909types</a> and thus distinct except
910<code>byte</code>, which is an <a href="#Alias_declarations">alias</a> for <code>uint8</code>, and
Russ Coxd7f050a2011-12-09 00:11:43 -0500911<code>rune</code>, which is an alias for <code>int32</code>.
Robert Griesemer26d22602018-10-02 15:55:38 -0700912Explicit conversions
Robert Griesemer7bc03712010-06-07 15:49:39 -0700913are required when different numeric types are mixed in an expression
Rob Pike5af7de32009-02-24 15:17:59 -0800914or assignment. For instance, <code>int32</code> and <code>int</code>
Russ Cox5958dd62009-03-04 17:19:21 -0800915are not the same type even though they may have the same size on a
Rob Pike5af7de32009-02-24 15:17:59 -0800916particular architecture.
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700917
918
Robert Griesemer19b1d352009-09-24 19:36:48 -0700919<h3 id="String_types">String types</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700920
Rob Pike4501d342009-02-19 17:31:36 -0800921<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -0700922A <i>string type</i> represents the set of string values.
Robert Griesemercc065932012-09-14 11:31:56 -0700923A string value is a (possibly empty) sequence of bytes.
Robert Griesemerde578dc2018-11-12 11:25:58 -0800924The number of bytes is called the length of the string and is never negative.
Robert Griesemercc065932012-09-14 11:31:56 -0700925Strings are immutable: once created,
Rob Pike5af7de32009-02-24 15:17:59 -0800926it is impossible to change the contents of a string.
griesemer4a2391e2017-09-19 14:35:15 +0200927The predeclared string type is <code>string</code>;
928it is a <a href="#Type_definitions">defined type</a>.
Robert Griesemercc065932012-09-14 11:31:56 -0700929</p>
Rob Pike5af7de32009-02-24 15:17:59 -0800930
931<p>
Robert Griesemerde578dc2018-11-12 11:25:58 -0800932The length of a string <code>s</code> can be discovered using
Robert Griesemercc065932012-09-14 11:31:56 -0700933the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
934The length is a compile-time constant if the string is a constant.
Robert Griesemer9c9e8112012-12-10 11:55:57 -0800935A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>
9360 through <code>len(s)-1</code>.
Robert Griesemercc065932012-09-14 11:31:56 -0700937It is illegal to take the address of such an element; if
938<code>s[i]</code> is the <code>i</code>'th byte of a
939string, <code>&amp;s[i]</code> is invalid.
Rob Pike4501d342009-02-19 17:31:36 -0800940</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700941
Robert Griesemerdf49fb32008-08-28 17:47:53 -0700942
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700943<h3 id="Array_types">Array types</h3>
Russ Cox461dd912009-03-04 14:44:51 -0800944
945<p>
946An array is a numbered sequence of elements of a single
Robert Griesemer4023dce2009-08-14 17:41:52 -0700947type, called the element type.
Robert Griesemerde578dc2018-11-12 11:25:58 -0800948The number of elements is called the length of the array and is never negative.
Russ Cox461dd912009-03-04 14:44:51 -0800949</p>
950
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700951<pre class="ebnf">
Russ Cox461dd912009-03-04 14:44:51 -0800952ArrayType = "[" ArrayLength "]" ElementType .
953ArrayLength = Expression .
Robert Griesemer4023dce2009-08-14 17:41:52 -0700954ElementType = Type .
Russ Cox461dd912009-03-04 14:44:51 -0800955</pre>
956
957<p>
Robert Griesemer2c83f1e2014-05-22 12:23:25 -0700958The length is part of the array's type; it must evaluate to a
griesemerb40831b2017-08-21 15:47:51 +0200959non-negative <a href="#Constants">constant</a>
960<a href="#Representability">representable</a> by a value
Robert Griesemer39067062012-12-12 11:06:26 -0800961of type <code>int</code>.
962The length of array <code>a</code> can be discovered
Robert Griesemercc065932012-09-14 11:31:56 -0700963using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
Robert Griesemer9c9e8112012-12-10 11:55:57 -0800964The elements can be addressed by integer <a href="#Index_expressions">indices</a>
Robert Griesemer39067062012-12-12 11:06:26 -08009650 through <code>len(a)-1</code>.
Rob Pikeff6a8fd2009-11-20 15:47:15 -0800966Array types are always one-dimensional but may be composed to form
967multi-dimensional types.
Russ Cox461dd912009-03-04 14:44:51 -0800968</p>
969
970<pre>
971[32]byte
972[2*N] struct { x, y int32 }
973[1000]*float64
Rob Pikeff6a8fd2009-11-20 15:47:15 -0800974[3][5]int
975[2][2][2]float64 // same as [2]([2]([2]float64))
Russ Cox461dd912009-03-04 14:44:51 -0800976</pre>
977
Russ Cox7c4f7cc2009-08-20 11:11:03 -0700978<h3 id="Slice_types">Slice types</h3>
Russ Cox461dd912009-03-04 14:44:51 -0800979
980<p>
Robert Griesemer15da9972013-10-16 16:16:54 -0700981A slice is a descriptor for a contiguous segment of an <i>underlying array</i> and
Robert Griesemerb34f0552013-04-02 23:17:37 -0700982provides access to a numbered sequence of elements from that array.
983A slice type denotes the set of all slices of arrays of its element type.
Robert Griesemerde578dc2018-11-12 11:25:58 -0800984The number of elements is called the length of the slice and is never negative.
Robert Griesemer7bc03712010-06-07 15:49:39 -0700985The value of an uninitialized slice is <code>nil</code>.
Russ Cox461dd912009-03-04 14:44:51 -0800986</p>
987
Robert Griesemerf7ac31362009-07-10 16:06:40 -0700988<pre class="ebnf">
Russ Cox461dd912009-03-04 14:44:51 -0800989SliceType = "[" "]" ElementType .
990</pre>
991
992<p>
Robert Griesemerde578dc2018-11-12 11:25:58 -0800993The length of a slice <code>s</code> can be discovered by the built-in function
Robert Griesemercc065932012-09-14 11:31:56 -0700994<a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during
Robert Griesemer9c9e8112012-12-10 11:55:57 -0800995execution. The elements can be addressed by integer <a href="#Index_expressions">indices</a>
9960 through <code>len(s)-1</code>. The slice index of a
Russ Cox461dd912009-03-04 14:44:51 -0800997given element may be less than the index of the same element in the
998underlying array.
999</p>
1000<p>
1001A slice, once initialized, is always associated with an underlying
Rob Pike7ec08562010-01-09 07:32:26 +11001002array that holds its elements. A slice therefore shares storage
Russ Cox461dd912009-03-04 14:44:51 -08001003with its array and with other slices of the same array; by contrast,
1004distinct arrays always represent distinct storage.
1005</p>
1006<p>
1007The array underlying a slice may extend past the end of the slice.
Russ Cox5958dd62009-03-04 17:19:21 -08001008The <i>capacity</i> is a measure of that extent: it is the sum of
Russ Cox461dd912009-03-04 14:44:51 -08001009the length of the slice and the length of the array beyond the slice;
Robert Griesemer462a17e2013-03-22 15:36:04 -07001010a slice of length up to that capacity can be created by
Robert Griesemere333b962013-09-11 17:18:52 -07001011<a href="#Slice_expressions"><i>slicing</i></a> a new one from the original slice.
Russ Cox461dd912009-03-04 14:44:51 -08001012The capacity of a slice <code>a</code> can be discovered using the
Robert Griesemer0c2e6b32010-07-13 11:54:57 -07001013built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.
Russ Cox461dd912009-03-04 14:44:51 -08001014</p>
1015
Russ Cox461dd912009-03-04 14:44:51 -08001016<p>
Robert Griesemer0c2e6b32010-07-13 11:54:57 -07001017A new, initialized slice value for a given element type <code>T</code> is
1018made using the built-in function
1019<a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1020which takes a slice type
Robert Griesemer15da9972013-10-16 16:16:54 -07001021and parameters specifying the length and optionally the capacity.
1022A slice created with <code>make</code> always allocates a new, hidden array
1023to which the returned slice value refers. That is, executing
Russ Cox461dd912009-03-04 14:44:51 -08001024</p>
1025
1026<pre>
1027make([]T, length, capacity)
1028</pre>
1029
1030<p>
Robert Griesemer15da9972013-10-16 16:16:54 -07001031produces the same slice as allocating an array and <a href="#Slice_expressions">slicing</a>
1032it, so these two expressions are equivalent:
Russ Cox461dd912009-03-04 14:44:51 -08001033</p>
1034
1035<pre>
1036make([]int, 50, 100)
1037new([100]int)[0:50]
1038</pre>
1039
Rob Pikeff6a8fd2009-11-20 15:47:15 -08001040<p>
1041Like arrays, slices are always one-dimensional but may be composed to construct
1042higher-dimensional objects.
1043With arrays of arrays, the inner arrays are, by construction, always the same length;
Robert Griesemer15da9972013-10-16 16:16:54 -07001044however with slices of slices (or arrays of slices), the inner lengths may vary dynamically.
1045Moreover, the inner slices must be initialized individually.
Rob Pikeff6a8fd2009-11-20 15:47:15 -08001046</p>
Russ Cox461dd912009-03-04 14:44:51 -08001047
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001048<h3 id="Struct_types">Struct types</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001049
Rob Pike5af7de32009-02-24 15:17:59 -08001050<p>
Robert Griesemerd3b15652009-11-16 08:58:55 -08001051A struct is a sequence of named elements, called fields, each of which has a
1052name and a type. Field names may be specified explicitly (IdentifierList) or
Robert Griesemerf8b41232017-01-10 16:19:14 -08001053implicitly (EmbeddedField).
Robert Griesemerd3b15652009-11-16 08:58:55 -08001054Within a struct, non-<a href="#Blank_identifier">blank</a> field names must
Robert Griesemer103c9db2012-03-01 13:57:49 -08001055be <a href="#Uniqueness_of_identifiers">unique</a>.
Rob Pike5af7de32009-02-24 15:17:59 -08001056</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001057
Robert Griesemerf7ac31362009-07-10 16:06:40 -07001058<pre class="ebnf">
Robert Griesemerf8b41232017-01-10 16:19:14 -08001059StructType = "struct" "{" { FieldDecl ";" } "}" .
1060FieldDecl = (IdentifierList Type | EmbeddedField) [ Tag ] .
1061EmbeddedField = [ "*" ] TypeName .
1062Tag = string_lit .
Robert Griesemerc2d55862009-02-19 16:49:10 -08001063</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001064
Robert Griesemerc2d55862009-02-19 16:49:10 -08001065<pre>
1066// An empty struct.
1067struct {}
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001068
Robert Griesemer4e56b332009-09-10 10:14:00 -07001069// A struct with 6 fields.
Robert Griesemerc2d55862009-02-19 16:49:10 -08001070struct {
Robert Griesemer130ac742009-12-10 16:43:01 -08001071 x, y int
Robert Griesemerb94c0d22011-01-19 23:07:21 -05001072 u float32
1073 _ float32 // padding
Robert Griesemer130ac742009-12-10 16:43:01 -08001074 A *[]int
1075 F func()
Robert Griesemerc2d55862009-02-19 16:49:10 -08001076}
1077</pre>
Robert Griesemer1f3e8422008-09-29 18:41:30 -07001078
Rob Pike5af7de32009-02-24 15:17:59 -08001079<p>
Robert Griesemerf8b41232017-01-10 16:19:14 -08001080A field declared with a type but no explicit field name is called an <i>embedded field</i>.
1081An embedded field must be specified as
Russ Coxbee2d5b2010-09-30 14:59:41 -04001082a type name <code>T</code> or as a pointer to a non-interface type name <code>*T</code>,
Ian Lance Taylor3e804ba2009-08-17 11:40:57 -07001083and <code>T</code> itself may not be
Robert Griesemerd3b15652009-11-16 08:58:55 -08001084a pointer type. The unqualified type name acts as the field name.
Rob Pike5af7de32009-02-24 15:17:59 -08001085</p>
Robert Griesemer1f3e8422008-09-29 18:41:30 -07001086
Robert Griesemerc2d55862009-02-19 16:49:10 -08001087<pre>
Robert Griesemerf8b41232017-01-10 16:19:14 -08001088// A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4
Robert Griesemerc2d55862009-02-19 16:49:10 -08001089struct {
Robert Griesemer130ac742009-12-10 16:43:01 -08001090 T1 // field name is T1
1091 *T2 // field name is T2
1092 P.T3 // field name is T3
1093 *P.T4 // field name is T4
1094 x, y int // field names are x and y
Robert Griesemerc2d55862009-02-19 16:49:10 -08001095}
1096</pre>
Robert Griesemer1f3e8422008-09-29 18:41:30 -07001097
Rob Pike5af7de32009-02-24 15:17:59 -08001098<p>
Robert Griesemerd3b15652009-11-16 08:58:55 -08001099The following declaration is illegal because field names must be unique
1100in a struct type:
Rob Pike5af7de32009-02-24 15:17:59 -08001101</p>
Robert Griesemer071c91b2008-10-23 12:04:45 -07001102
Robert Griesemerc2d55862009-02-19 16:49:10 -08001103<pre>
1104struct {
Robert Griesemerf8b41232017-01-10 16:19:14 -08001105 T // conflicts with embedded field *T and *P.T
1106 *T // conflicts with embedded field T and *P.T
1107 *P.T // conflicts with embedded field T and *T
Robert Griesemerc2d55862009-02-19 16:49:10 -08001108}
1109</pre>
Robert Griesemer1f3e8422008-09-29 18:41:30 -07001110
Robert Griesemerc2d55862009-02-19 16:49:10 -08001111<p>
Robert Griesemer787adb62012-06-04 14:24:10 -07001112A field or <a href="#Method_declarations">method</a> <code>f</code> of an
Robert Griesemerf8b41232017-01-10 16:19:14 -08001113embedded field in a struct <code>x</code> is called <i>promoted</i> if
Robert Griesemer787adb62012-06-04 14:24:10 -07001114<code>x.f</code> is a legal <a href="#Selectors">selector</a> that denotes
1115that field or method <code>f</code>.
1116</p>
1117
1118<p>
1119Promoted fields act like ordinary fields
1120of a struct except that they cannot be used as field names in
1121<a href="#Composite_literals">composite literals</a> of the struct.
1122</p>
1123
1124<p>
Robert Griesemer9b49ac02018-01-22 16:20:01 -08001125Given a struct type <code>S</code> and a <a href="#Type_definitions">defined type</a>
1126<code>T</code>, promoted methods are included in the method set of the struct as follows:
Rob Pike5af7de32009-02-24 15:17:59 -08001127</p>
Robert Griesemer56809d02009-05-20 11:02:48 -07001128<ul>
Robert Griesemer787adb62012-06-04 14:24:10 -07001129 <li>
Robert Griesemerf8b41232017-01-10 16:19:14 -08001130 If <code>S</code> contains an embedded field <code>T</code>,
Robert Griesemer787adb62012-06-04 14:24:10 -07001131 the <a href="#Method_sets">method sets</a> of <code>S</code>
1132 and <code>*S</code> both include promoted methods with receiver
1133 <code>T</code>. The method set of <code>*S</code> also
1134 includes promoted methods with receiver <code>*T</code>.
Robert Griesemer56809d02009-05-20 11:02:48 -07001135 </li>
Robin Eklind1d46fc42012-12-11 12:17:53 -05001136
Robert Griesemer787adb62012-06-04 14:24:10 -07001137 <li>
Robert Griesemerf8b41232017-01-10 16:19:14 -08001138 If <code>S</code> contains an embedded field <code>*T</code>,
Robert Griesemer787adb62012-06-04 14:24:10 -07001139 the method sets of <code>S</code> and <code>*S</code> both
1140 include promoted methods with receiver <code>T</code> or
1141 <code>*T</code>.
Robert Griesemer56809d02009-05-20 11:02:48 -07001142 </li>
1143</ul>
Robert Griesemer787adb62012-06-04 14:24:10 -07001144
Rob Pike5af7de32009-02-24 15:17:59 -08001145<p>
Robert Griesemer56809d02009-05-20 11:02:48 -07001146A field declaration may be followed by an optional string literal <i>tag</i>,
Robert Griesemerd3b15652009-11-16 08:58:55 -08001147which becomes an attribute for all the fields in the corresponding
Robert Griesemer0436a892016-04-22 16:35:29 -07001148field declaration. An empty tag string is equivalent to an absent tag.
1149The tags are made visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a>
Emil Hessman13141312014-01-03 22:48:03 -08001150and take part in <a href="#Type_identity">type identity</a> for structs
Rob Pike5af7de32009-02-24 15:17:59 -08001151but are otherwise ignored.
1152</p>
Robert Griesemer2e90e542008-10-30 15:52:37 -07001153
Robert Griesemerc2d55862009-02-19 16:49:10 -08001154<pre>
Robert Griesemerc2d55862009-02-19 16:49:10 -08001155struct {
Robert Griesemer7305b552015-11-30 14:18:09 -08001156 x, y float64 "" // an empty tag string is like an absent tag
1157 name string "any string is permitted as a tag"
1158 _ [4]byte "ceci n'est pas un champ de structure"
1159}
1160
1161// A struct corresponding to a TimeStamp protocol buffer.
1162// The tag strings define the protocol buffer field numbers;
1163// they follow the convention outlined by the reflect package.
1164struct {
1165 microsec uint64 `protobuf:"1"`
1166 serverIP6 uint64 `protobuf:"2"`
Robert Griesemerc2d55862009-02-19 16:49:10 -08001167}
1168</pre>
Robert Griesemer2e90e542008-10-30 15:52:37 -07001169
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001170<h3 id="Pointer_types">Pointer types</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001171
Rob Pike5af7de32009-02-24 15:17:59 -08001172<p>
Robert Griesemer6962c152014-10-16 15:08:49 -07001173A pointer type denotes the set of all pointers to <a href="#Variables">variables</a> of a given
Rob Pikeda389742009-03-02 19:13:40 -08001174type, called the <i>base type</i> of the pointer.
Peter Mundy5928e1d2010-11-09 10:10:57 -08001175The value of an uninitialized pointer is <code>nil</code>.
Rob Pike5af7de32009-02-24 15:17:59 -08001176</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001177
Robert Griesemerf7ac31362009-07-10 16:06:40 -07001178<pre class="ebnf">
Robert Griesemerc2d55862009-02-19 16:49:10 -08001179PointerType = "*" BaseType .
Robin Eklindcac006a2014-08-30 10:27:01 -07001180BaseType = Type .
Robert Griesemerc2d55862009-02-19 16:49:10 -08001181</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001182
Robert Griesemerc2d55862009-02-19 16:49:10 -08001183<pre>
Robert Griesemer953f2de2012-03-01 10:35:15 -08001184*Point
1185*[4]int
Robert Griesemerc2d55862009-02-19 16:49:10 -08001186</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001187
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001188<h3 id="Function_types">Function types</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001189
Rob Pike8f2330d2009-02-25 16:20:44 -08001190<p>
Robert Griesemer7231ceb2008-09-08 15:01:04 -07001191A function type denotes the set of all functions with the same parameter
Peter Mundy5928e1d2010-11-09 10:10:57 -08001192and result types. The value of an uninitialized variable of function type
Robert Griesemer7bc03712010-06-07 15:49:39 -07001193is <code>nil</code>.
Rob Pike8f2330d2009-02-25 16:20:44 -08001194</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001195
Robert Griesemerf7ac31362009-07-10 16:06:40 -07001196<pre class="ebnf">
Rob Pike8f2330d2009-02-25 16:20:44 -08001197FunctionType = "func" Signature .
1198Signature = Parameters [ Result ] .
Robert Griesemer4023dce2009-08-14 17:41:52 -07001199Result = Parameters | Type .
Robert Griesemer130ac742009-12-10 16:43:01 -08001200Parameters = "(" [ ParameterList [ "," ] ] ")" .
Rob Pike8f2330d2009-02-25 16:20:44 -08001201ParameterList = ParameterDecl { "," ParameterDecl } .
Russ Cox95625922010-06-12 11:37:13 -07001202ParameterDecl = [ IdentifierList ] [ "..." ] Type .
Robert Griesemerc2d55862009-02-19 16:49:10 -08001203</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001204
Robert Griesemerc2d55862009-02-19 16:49:10 -08001205<p>
Rob Pike8f2330d2009-02-25 16:20:44 -08001206Within a list of parameters or results, the names (IdentifierList)
1207must either all be present or all be absent. If present, each name
Robert Griesemer85e451e2012-11-29 14:47:47 -08001208stands for one item (parameter or result) of the specified type and
1209all non-<a href="#Blank_identifier">blank</a> names in the signature
1210must be <a href="#Uniqueness_of_identifiers">unique</a>.
1211If absent, each type stands for one item of that type.
1212Parameter and result
Rob Pike8f2330d2009-02-25 16:20:44 -08001213lists are always parenthesized except that if there is exactly
Robert Griesemer73ca1272010-07-09 13:02:54 -07001214one unnamed result it may be written as an unparenthesized type.
Rob Pike8f2330d2009-02-25 16:20:44 -08001215</p>
Russ Cox95625922010-06-12 11:37:13 -07001216
Robert Griesemerac771a82010-09-24 14:08:28 -07001217<p>
Robert Griesemer57c81ef2015-12-15 13:13:38 -08001218The final incoming parameter in a function signature may have
Robert Griesemerac771a82010-09-24 14:08:28 -07001219a type prefixed with <code>...</code>.
1220A function with such a parameter is called <i>variadic</i> and
1221may be invoked with zero or more arguments for that parameter.
Rob Pike8f2330d2009-02-25 16:20:44 -08001222</p>
Robert Griesemer2bfa9572008-10-24 13:13:12 -07001223
Robert Griesemerc2d55862009-02-19 16:49:10 -08001224<pre>
Russ Cox46871692010-01-26 10:25:56 -08001225func()
Robert Griesemer953f2de2012-03-01 10:35:15 -08001226func(x int) int
1227func(a, _ int, z float32) bool
Robert Griesemerb94c0d22011-01-19 23:07:21 -05001228func(a, b int, z float32) (bool)
Robert Griesemer953f2de2012-03-01 10:35:15 -08001229func(prefix string, values ...int)
Robert Griesemerb94c0d22011-01-19 23:07:21 -05001230func(a, b int, z float64, opt ...interface{}) (success bool)
1231func(int, int, float64) (float64, *[]int)
Russ Cox46871692010-01-26 10:25:56 -08001232func(n int) func(p *T)
Robert Griesemerc2d55862009-02-19 16:49:10 -08001233</pre>
Robert Griesemer2b9fe0e2009-01-30 14:48:29 -08001234
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001235
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001236<h3 id="Interface_types">Interface types</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001237
Rob Pike8f2330d2009-02-25 16:20:44 -08001238<p>
Robert Griesemer2a838d62011-02-08 13:31:01 -08001239An interface type specifies a <a href="#Method_sets">method set</a> called its <i>interface</i>.
Robert Griesemer56809d02009-05-20 11:02:48 -07001240A variable of interface type can store a value of any type with a method set
1241that is any superset of the interface. Such a type is said to
Robert Griesemer7bc03712010-06-07 15:49:39 -07001242<i>implement the interface</i>.
Peter Mundy5928e1d2010-11-09 10:10:57 -08001243The value of an uninitialized variable of interface type is <code>nil</code>.
Rob Pike8f2330d2009-02-25 16:20:44 -08001244</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001245
Robert Griesemerf7ac31362009-07-10 16:06:40 -07001246<pre class="ebnf">
Robert Griesemerbc405df2019-08-14 17:37:20 -07001247InterfaceType = "interface" "{" { ( MethodSpec | InterfaceTypeName ) ";" } "}" .
1248MethodSpec = MethodName Signature .
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07001249MethodName = identifier .
Rob Pike8f2330d2009-02-25 16:20:44 -08001250InterfaceTypeName = TypeName .
Robert Griesemerc2d55862009-02-19 16:49:10 -08001251</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001252
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07001253<p>
Robert Griesemerbc405df2019-08-14 17:37:20 -07001254An interface type may specify methods <i>explicitly</i> through method specifications,
1255or it may <i>embed</i> methods of other interfaces through interface type names.
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07001256</p>
1257
Robert Griesemerc2d55862009-02-19 16:49:10 -08001258<pre>
Robert Griesemer39d41782019-07-30 16:16:03 -07001259// A simple File interface.
Robert Griesemerc2d55862009-02-19 16:49:10 -08001260interface {
Robert Griesemer39d41782019-07-30 16:16:03 -07001261 Read([]byte) (int, error)
1262 Write([]byte) (int, error)
1263 Close() error
1264}
1265</pre>
1266
Robert Griesemerbc405df2019-08-14 17:37:20 -07001267<p>
1268The name of each explicitly specified method must be <a href="#Uniqueness_of_identifiers">unique</a>
1269and not <a href="#Blank_identifier">blank</a>.
1270</p>
1271
Robert Griesemer39d41782019-07-30 16:16:03 -07001272<pre>
1273interface {
1274 String() string
1275 String() string // illegal: String not unique
1276 _(x int) // illegal: method must have non-blank name
Robert Griesemerc2d55862009-02-19 16:49:10 -08001277}
1278</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001279
Rob Pike8f2330d2009-02-25 16:20:44 -08001280<p>
Robert Griesemer56809d02009-05-20 11:02:48 -07001281More than one type may implement an interface.
Rob Pike8f2330d2009-02-25 16:20:44 -08001282For instance, if two types <code>S1</code> and <code>S2</code>
Robert Griesemer56809d02009-05-20 11:02:48 -07001283have the method set
Rob Pike8f2330d2009-02-25 16:20:44 -08001284</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001285
Robert Griesemerc2d55862009-02-19 16:49:10 -08001286<pre>
Robert Griesemerbc405df2019-08-14 17:37:20 -07001287func (p T) Read(p []byte) (n int, err error)
1288func (p T) Write(p []byte) (n int, err error)
1289func (p T) Close() error
Robert Griesemerc2d55862009-02-19 16:49:10 -08001290</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001291
Rob Pike8f2330d2009-02-25 16:20:44 -08001292<p>
1293(where <code>T</code> stands for either <code>S1</code> or <code>S2</code>)
1294then the <code>File</code> interface is implemented by both <code>S1</code> and
1295<code>S2</code>, regardless of what other methods
1296<code>S1</code> and <code>S2</code> may have or share.
1297</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001298
Rob Pike8f2330d2009-02-25 16:20:44 -08001299<p>
1300A type implements any interface comprising any subset of its methods
1301and may therefore implement several distinct interfaces. For
1302instance, all types implement the <i>empty interface</i>:
1303</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001304
Robert Griesemerc2d55862009-02-19 16:49:10 -08001305<pre>
Robert Griesemer19b1d352009-09-24 19:36:48 -07001306interface{}
Robert Griesemerc2d55862009-02-19 16:49:10 -08001307</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001308
Rob Pike8f2330d2009-02-25 16:20:44 -08001309<p>
1310Similarly, consider this interface specification,
Robert Griesemer4ed666e2009-08-27 16:45:42 -07001311which appears within a <a href="#Type_declarations">type declaration</a>
Robert Griesemerbb29c5a2014-09-25 12:49:42 -07001312to define an interface called <code>Locker</code>:
Rob Pike8f2330d2009-02-25 16:20:44 -08001313</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001314
Robert Griesemerc2d55862009-02-19 16:49:10 -08001315<pre>
Robert Griesemerbb29c5a2014-09-25 12:49:42 -07001316type Locker interface {
Robert Griesemer130ac742009-12-10 16:43:01 -08001317 Lock()
1318 Unlock()
Robert Griesemerc2d55862009-02-19 16:49:10 -08001319}
1320</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001321
Rob Pike8f2330d2009-02-25 16:20:44 -08001322<p>
1323If <code>S1</code> and <code>S2</code> also implement
1324</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001325
Robert Griesemerc2d55862009-02-19 16:49:10 -08001326<pre>
Robert Griesemer3c7271f2011-05-24 14:18:44 -07001327func (p T) Lock() { … }
1328func (p T) Unlock() { … }
Robert Griesemerc2d55862009-02-19 16:49:10 -08001329</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07001330
Robert Griesemerc2d55862009-02-19 16:49:10 -08001331<p>
Robert Griesemerbb29c5a2014-09-25 12:49:42 -07001332they implement the <code>Locker</code> interface as well
Rob Pike8f2330d2009-02-25 16:20:44 -08001333as the <code>File</code> interface.
1334</p>
Robert Griesemerbb29c5a2014-09-25 12:49:42 -07001335
Rob Pike8f2330d2009-02-25 16:20:44 -08001336<p>
Robert Griesemerbb29c5a2014-09-25 12:49:42 -07001337An interface <code>T</code> may use a (possibly qualified) interface type
1338name <code>E</code> in place of a method specification. This is called
Robert Griesemerbc405df2019-08-14 17:37:20 -07001339<i>embedding</i> interface <code>E</code> in <code>T</code>.
1340The <a href="#Method_sets">method set</a> of <code>T</code> is the <i>union</i>
1341of the method sets of <code>T</code>’s explicitly declared methods and of
1342<code>T</code>’s embedded interfaces.
Rob Pike8f2330d2009-02-25 16:20:44 -08001343</p>
Robert Griesemer38c232f2009-02-11 15:09:15 -08001344
Robert Griesemerc2d55862009-02-19 16:49:10 -08001345<pre>
Robert Griesemerbc405df2019-08-14 17:37:20 -07001346type Reader interface {
1347 Read(p []byte) (n int, err error)
1348 Close() error
1349}
1350
1351type Writer interface {
1352 Write(p []byte) (n int, err error)
1353 Close() error
1354}
1355
1356// ReadWriter's methods are Read, Write, and Close.
Robert Griesemerbb29c5a2014-09-25 12:49:42 -07001357type ReadWriter interface {
Robert Griesemerbc405df2019-08-14 17:37:20 -07001358 Reader // includes methods of Reader in ReadWriter's method set
1359 Writer // includes methods of Writer in ReadWriter's method set
Robert Griesemerc2d55862009-02-19 16:49:10 -08001360}
Robert Griesemerbc405df2019-08-14 17:37:20 -07001361</pre>
Robert Griesemer38c232f2009-02-11 15:09:15 -08001362
Robert Griesemerbc405df2019-08-14 17:37:20 -07001363<p>
1364A <i>union</i> of method sets contains the (exported and non-exported)
1365methods of each method set exactly once, and methods with the
1366<a href="#Uniqueness_of_identifiers">same</a> names must
1367have <a href="#Type_identity">identical</a> signatures.
1368</p>
Robert Griesemerbb29c5a2014-09-25 12:49:42 -07001369
Robert Griesemerbc405df2019-08-14 17:37:20 -07001370<pre>
1371type ReadCloser interface {
1372 Reader // includes methods of Reader in ReadCloser's method set
1373 Close() // illegal: signatures of Reader.Close and Close are different
Robert Griesemerbb29c5a2014-09-25 12:49:42 -07001374}
Robert Griesemerc2d55862009-02-19 16:49:10 -08001375</pre>
Robert Griesemer38c232f2009-02-11 15:09:15 -08001376
Russ Cox388816a2012-02-08 14:35:00 -05001377<p>
Russ Cox7c5d6402012-02-08 15:37:58 -05001378An interface type <code>T</code> may not embed itself
1379or any interface type that embeds <code>T</code>, recursively.
Russ Cox388816a2012-02-08 14:35:00 -05001380</p>
1381
1382<pre>
1383// illegal: Bad cannot embed itself
1384type Bad interface {
1385 Bad
1386}
1387
1388// illegal: Bad1 cannot embed itself using Bad2
1389type Bad1 interface {
1390 Bad2
1391}
1392type Bad2 interface {
1393 Bad1
1394}
1395</pre>
1396
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001397<h3 id="Map_types">Map types</h3>
Robert Griesemera3294712009-01-05 11:17:26 -08001398
Rob Pike8f2330d2009-02-25 16:20:44 -08001399<p>
1400A map is an unordered group of elements of one type, called the
Robert Griesemer0660d242009-11-15 17:42:27 -08001401element type, indexed by a set of unique <i>keys</i> of another type,
Robert Griesemer4023dce2009-08-14 17:41:52 -07001402called the key type.
Robert Griesemer7bc03712010-06-07 15:49:39 -07001403The value of an uninitialized map is <code>nil</code>.
Rob Pike8f2330d2009-02-25 16:20:44 -08001404</p>
Robert Griesemera3294712009-01-05 11:17:26 -08001405
Robert Griesemerf7ac31362009-07-10 16:06:40 -07001406<pre class="ebnf">
Robert Griesemer19b1d352009-09-24 19:36:48 -07001407MapType = "map" "[" KeyType "]" ElementType .
Robert Griesemer4023dce2009-08-14 17:41:52 -07001408KeyType = Type .
Robert Griesemerc2d55862009-02-19 16:49:10 -08001409</pre>
Robert Griesemera3294712009-01-05 11:17:26 -08001410
Robert Griesemerc2d55862009-02-19 16:49:10 -08001411<p>
Robert Griesemer462a17e2013-03-22 15:36:04 -07001412The <a href="#Comparison_operators">comparison operators</a>
1413<code>==</code> and <code>!=</code> must be fully defined
Robert Griesemer9c3d8762012-01-30 15:31:33 -08001414for operands of the key type; thus the key type must not be a function, map, or
1415slice.
Robert Griesemer1d282a82010-06-03 16:55:50 -07001416If the key type is an interface type, these
Rob Pike8f2330d2009-02-25 16:20:44 -08001417comparison operators must be defined for the dynamic key values;
Rob Pike5bb29fb2010-03-25 17:59:59 -07001418failure will cause a <a href="#Run_time_panics">run-time panic</a>.
Rob Pike8f2330d2009-02-25 16:20:44 -08001419
1420</p>
Robert Griesemera3294712009-01-05 11:17:26 -08001421
Robert Griesemerc2d55862009-02-19 16:49:10 -08001422<pre>
David Symonds72a29792011-11-29 15:47:36 -08001423map[string]int
1424map[*T]struct{ x, y float64 }
1425map[string]interface{}
Robert Griesemerc2d55862009-02-19 16:49:10 -08001426</pre>
Robert Griesemera3294712009-01-05 11:17:26 -08001427
Rob Pike5af7de32009-02-24 15:17:59 -08001428<p>
Robert Griesemer0c2e6b32010-07-13 11:54:57 -07001429The number of map elements is called its length.
1430For a map <code>m</code>, it can be discovered using the
Robert Griesemercc065932012-09-14 11:31:56 -07001431built-in function <a href="#Length_and_capacity"><code>len</code></a>
Robert Griesemer3e0c0a82011-10-17 12:53:10 -07001432and may change during execution. Elements may be added during execution
1433using <a href="#Assignments">assignments</a> and retrieved with
Robert Griesemer9c9e8112012-12-10 11:55:57 -08001434<a href="#Index_expressions">index expressions</a>; they may be removed with the
Robert Griesemer3e0c0a82011-10-17 12:53:10 -07001435<a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function.
Rob Pike5af7de32009-02-24 15:17:59 -08001436</p>
Rob Pike8f2330d2009-02-25 16:20:44 -08001437<p>
Rob Pike8f2330d2009-02-25 16:20:44 -08001438A new, empty map value is made using the built-in
Robert Griesemer0c2e6b32010-07-13 11:54:57 -07001439function <a href="#Making_slices_maps_and_channels"><code>make</code></a>,
1440which takes the map type and an optional capacity hint as arguments:
Rob Pike8f2330d2009-02-25 16:20:44 -08001441</p>
1442
1443<pre>
David Symonds72a29792011-11-29 15:47:36 -08001444make(map[string]int)
1445make(map[string]int, 100)
Rob Pike8f2330d2009-02-25 16:20:44 -08001446</pre>
Robert Griesemera3294712009-01-05 11:17:26 -08001447
Rob Pikeda389742009-03-02 19:13:40 -08001448<p>
1449The initial capacity does not bound its size:
1450maps grow to accommodate the number of items
Robert Griesemer54731032011-05-12 09:15:59 -07001451stored in them, with the exception of <code>nil</code> maps.
1452A <code>nil</code> map is equivalent to an empty map except that no elements
1453may be added.
Rob Pikeda389742009-03-02 19:13:40 -08001454
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001455<h3 id="Channel_types">Channel types</h3>
Robert Griesemera3294712009-01-05 11:17:26 -08001456
Rob Pike8f2330d2009-02-25 16:20:44 -08001457<p>
Robert Griesemer97aa90d2014-05-07 10:40:39 -07001458A channel provides a mechanism for
1459<a href="#Go_statements">concurrently executing functions</a>
1460to communicate by
1461<a href="#Send_statements">sending</a> and
1462<a href="#Receive_operator">receiving</a>
1463values of a specified element type.
Robert Griesemer7bc03712010-06-07 15:49:39 -07001464The value of an uninitialized channel is <code>nil</code>.
Rob Pike8f2330d2009-02-25 16:20:44 -08001465</p>
Robert Griesemera3294712009-01-05 11:17:26 -08001466
Robert Griesemerf7ac31362009-07-10 16:06:40 -07001467<pre class="ebnf">
Robert Griesemer97aa90d2014-05-07 10:40:39 -07001468ChannelType = ( "chan" | "chan" "&lt;-" | "&lt;-" "chan" ) ElementType .
Robert Griesemerc2d55862009-02-19 16:49:10 -08001469</pre>
Robert Griesemera3294712009-01-05 11:17:26 -08001470
Rob Pike8f2330d2009-02-25 16:20:44 -08001471<p>
Robert Griesemer97aa90d2014-05-07 10:40:39 -07001472The optional <code>&lt;-</code> operator specifies the channel <i>direction</i>,
Robert Griesemer56ca6972010-05-07 18:22:40 -07001473<i>send</i> or <i>receive</i>. If no direction is given, the channel is
Robert Griesemer97aa90d2014-05-07 10:40:39 -07001474<i>bidirectional</i>.
Russ Coxb7ba5232018-11-13 10:23:01 -05001475A channel may be constrained only to send or only to receive by
1476<a href="#Assignments">assignment</a> or
1477explicit <a href="#Conversions">conversion</a>.
Robert Griesemer56ca6972010-05-07 18:22:40 -07001478</p>
1479
1480<pre>
David Symonds72a29792011-11-29 15:47:36 -08001481chan T // can be used to send and receive values of type T
1482chan&lt;- float64 // can only be used to send float64s
1483&lt;-chan int // can only be used to receive ints
Robert Griesemer56ca6972010-05-07 18:22:40 -07001484</pre>
1485
1486<p>
1487The <code>&lt;-</code> operator associates with the leftmost <code>chan</code>
1488possible:
Robert Griesemer1c369bd2010-01-27 09:35:39 -08001489</p>
1490
1491<pre>
David Symonds72a29792011-11-29 15:47:36 -08001492chan&lt;- chan int // same as chan&lt;- (chan int)
1493chan&lt;- &lt;-chan int // same as chan&lt;- (&lt;-chan int)
1494&lt;-chan &lt;-chan int // same as &lt;-chan (&lt;-chan int)
Robert Griesemer1c369bd2010-01-27 09:35:39 -08001495chan (&lt;-chan int)
1496</pre>
1497
1498<p>
Robert Griesemer7bc03712010-06-07 15:49:39 -07001499A new, initialized channel
Robert Griesemer56ca6972010-05-07 18:22:40 -07001500value can be made using the built-in function
1501<a href="#Making_slices_maps_and_channels"><code>make</code></a>,
Robert Griesemer97aa90d2014-05-07 10:40:39 -07001502which takes the channel type and an optional <i>capacity</i> as arguments:
Rob Pike8f2330d2009-02-25 16:20:44 -08001503</p>
Robert Griesemera3294712009-01-05 11:17:26 -08001504
Robert Griesemerc2d55862009-02-19 16:49:10 -08001505<pre>
Rob Pikeda389742009-03-02 19:13:40 -08001506make(chan int, 100)
Robert Griesemerc2d55862009-02-19 16:49:10 -08001507</pre>
Robert Griesemera3294712009-01-05 11:17:26 -08001508
Rob Pike8f2330d2009-02-25 16:20:44 -08001509<p>
Robert Griesemer97aa90d2014-05-07 10:40:39 -07001510The capacity, in number of elements, sets the size of the buffer in the channel.
1511If the capacity is zero or absent, the channel is unbuffered and communication
Robert Griesemer61d8a332014-05-14 11:47:19 -07001512succeeds only when both a sender and receiver are ready. Otherwise, the channel
1513is buffered and communication succeeds without blocking if the buffer
Robert Griesemer97aa90d2014-05-07 10:40:39 -07001514is not full (sends) or not empty (receives).
Robert Griesemer54731032011-05-12 09:15:59 -07001515A <code>nil</code> channel is never ready for communication.
Rob Pike8f2330d2009-02-25 16:20:44 -08001516</p>
Robert Griesemera3294712009-01-05 11:17:26 -08001517
Rob Pike94b67eb2009-03-24 17:40:47 -07001518<p>
Russ Cox9f2cb862011-03-11 14:47:02 -05001519A channel may be closed with the built-in function
Robert Griesemer97aa90d2014-05-07 10:40:39 -07001520<a href="#Close"><code>close</code></a>.
1521The multi-valued assignment form of the
Russ Cox9f2cb862011-03-11 14:47:02 -05001522<a href="#Receive_operator">receive operator</a>
Robert Griesemer97aa90d2014-05-07 10:40:39 -07001523reports whether a received value was sent before
1524the channel was closed.
1525</p>
1526
1527<p>
1528A single channel may be used in
1529<a href="#Send_statements">send statements</a>,
1530<a href="#Receive_operator">receive operations</a>,
1531and calls to the built-in functions
1532<a href="#Length_and_capacity"><code>cap</code></a> and
1533<a href="#Length_and_capacity"><code>len</code></a>
1534by any number of goroutines without further synchronization.
1535Channels act as first-in-first-out queues.
1536For example, if one goroutine sends values on a channel
1537and a second goroutine receives them, the values are
1538received in the order sent.
Rob Pike94b67eb2009-03-24 17:40:47 -07001539</p>
1540
Rob Pike83cbca52009-08-21 14:18:08 -07001541<h2 id="Properties_of_types_and_values">Properties of types and values</h2>
Robert Griesemer434c6052008-11-07 13:34:37 -08001542
Robert Griesemer7bc03712010-06-07 15:49:39 -07001543<h3 id="Type_identity">Type identity</h3>
1544
Rob Pike4501d342009-02-19 17:31:36 -08001545<p>
Robert Griesemer7bc03712010-06-07 15:49:39 -07001546Two types are either <i>identical</i> or <i>different</i>.
Robert Griesemer19b1d352009-09-24 19:36:48 -07001547</p>
Rob Pike8f2330d2009-02-25 16:20:44 -08001548
Robert Griesemerc2d55862009-02-19 16:49:10 -08001549<p>
Robert Griesemer56c9b512017-02-02 15:43:56 -08001550A <a href="#Type_definitions">defined type</a> is always different from any other type.
1551Otherwise, two types are identical if their <a href="#Types">underlying</a> type literals are
1552structurally equivalent; that is, they have the same literal structure and corresponding
1553components have identical types. In detail:
Rob Pike4501d342009-02-19 17:31:36 -08001554</p>
Rob Pike8f2330d2009-02-25 16:20:44 -08001555
Robert Griesemerc2d55862009-02-19 16:49:10 -08001556<ul>
Robert Griesemer533dfd62009-05-13 16:56:00 -07001557 <li>Two array types are identical if they have identical element types and
1558 the same array length.</li>
Robert Griesemer434c6052008-11-07 13:34:37 -08001559
Robert Griesemer533dfd62009-05-13 16:56:00 -07001560 <li>Two slice types are identical if they have identical element types.</li>
Robert Griesemer434c6052008-11-07 13:34:37 -08001561
Robert Griesemer533dfd62009-05-13 16:56:00 -07001562 <li>Two struct types are identical if they have the same sequence of fields,
Russ Coxe4953512010-06-21 12:42:33 -07001563 and if corresponding fields have the same names, and identical types,
1564 and identical tags.
Robert Griesemerf8b41232017-01-10 16:19:14 -08001565 <a href="#Exported_identifiers">Non-exported</a> field names from different
1566 packages are always different.</li>
Robert Griesemer434c6052008-11-07 13:34:37 -08001567
Robert Griesemer533dfd62009-05-13 16:56:00 -07001568 <li>Two pointer types are identical if they have identical base types.</li>
Robert Griesemer434c6052008-11-07 13:34:37 -08001569
Robert Griesemer533dfd62009-05-13 16:56:00 -07001570 <li>Two function types are identical if they have the same number of parameters
Russ Cox95625922010-06-12 11:37:13 -07001571 and result values, corresponding parameter and result types are
1572 identical, and either both functions are variadic or neither is.
Robert Griesemer533dfd62009-05-13 16:56:00 -07001573 Parameter and result names are not required to match.</li>
Robert Griesemera3294712009-01-05 11:17:26 -08001574
Robert Griesemer533dfd62009-05-13 16:56:00 -07001575 <li>Two interface types are identical if they have the same set of methods
Robert Griesemerf8b41232017-01-10 16:19:14 -08001576 with the same names and identical function types.
1577 <a href="#Exported_identifiers">Non-exported</a> method names from different
1578 packages are always different. The order of the methods is irrelevant.</li>
Robert Griesemer434c6052008-11-07 13:34:37 -08001579
Robert Griesemer4de1d1d2018-01-03 10:33:11 -08001580 <li>Two map types are identical if they have identical key and element types.</li>
Robert Griesemer434c6052008-11-07 13:34:37 -08001581
Robert Griesemer4de1d1d2018-01-03 10:33:11 -08001582 <li>Two channel types are identical if they have identical element types and
Robert Griesemer533dfd62009-05-13 16:56:00 -07001583 the same direction.</li>
Robert Griesemerc2d55862009-02-19 16:49:10 -08001584</ul>
Robert Griesemer434c6052008-11-07 13:34:37 -08001585
Robert Griesemerc2d55862009-02-19 16:49:10 -08001586<p>
Rob Pike8f2330d2009-02-25 16:20:44 -08001587Given the declarations
1588</p>
Robert Griesemer434c6052008-11-07 13:34:37 -08001589
Robert Griesemerc2d55862009-02-19 16:49:10 -08001590<pre>
1591type (
Robert Griesemer56c9b512017-02-02 15:43:56 -08001592 A0 = []string
1593 A1 = A0
1594 A2 = struct{ a, b int }
1595 A3 = int
1596 A4 = func(A3, float64) *A0
1597 A5 = func(x int, _ float64) *[]string
Robert Griesemerc2d55862009-02-19 16:49:10 -08001598)
Robert Griesemer56c9b512017-02-02 15:43:56 -08001599
1600type (
1601 B0 A0
1602 B1 []string
1603 B2 struct{ a, b int }
1604 B3 struct{ a, c int }
1605 B4 func(int, float64) *B0
1606 B5 func(x int, y float64) *A1
1607)
1608
1609type C0 = B0
Robert Griesemerc2d55862009-02-19 16:49:10 -08001610</pre>
Robert Griesemer434c6052008-11-07 13:34:37 -08001611
Rob Pike8f2330d2009-02-25 16:20:44 -08001612<p>
Robert Griesemer533dfd62009-05-13 16:56:00 -07001613these types are identical:
Rob Pike8f2330d2009-02-25 16:20:44 -08001614</p>
Robert Griesemer434c6052008-11-07 13:34:37 -08001615
Robert Griesemerc2d55862009-02-19 16:49:10 -08001616<pre>
Robert Griesemer56c9b512017-02-02 15:43:56 -08001617A0, A1, and []string
1618A2 and struct{ a, b int }
1619A3 and int
1620A4, func(int, float64) *[]string, and A5
1621
Robert Griesemerc13e0e82018-01-11 10:41:03 -08001622B0 and C0
Robert Griesemerc2d55862009-02-19 16:49:10 -08001623[]int and []int
David Symonds72a29792011-11-29 15:47:36 -08001624struct{ a, b *T5 } and struct{ a, b *T5 }
Robert Griesemer56c9b512017-02-02 15:43:56 -08001625func(x int, y float64) *[]string, func(int, float64) (result *[]string), and A5
Robert Griesemerc2d55862009-02-19 16:49:10 -08001626</pre>
Robert Griesemer434c6052008-11-07 13:34:37 -08001627
Rob Pike8f2330d2009-02-25 16:20:44 -08001628<p>
Robert Griesemer56c9b512017-02-02 15:43:56 -08001629<code>B0</code> and <code>B1</code> are different because they are new types
1630created by distinct <a href="#Type_definitions">type definitions</a>;
1631<code>func(int, float64) *B0</code> and <code>func(x int, y float64) *[]string</code>
1632are different because <code>B0</code> is different from <code>[]string</code>.
Robert Griesemer533dfd62009-05-13 16:56:00 -07001633</p>
1634
Robert Griesemer434c6052008-11-07 13:34:37 -08001635
Robert Griesemer440cc952010-06-07 17:40:21 -07001636<h3 id="Assignability">Assignability</h3>
Rob Pike5af7de32009-02-24 15:17:59 -08001637
Rob Pike5af7de32009-02-24 15:17:59 -08001638<p>
Robert Griesemer6962c152014-10-16 15:08:49 -07001639A value <code>x</code> is <i>assignable</i> to a <a href="#Variables">variable</a> of type <code>T</code>
griesemerb40831b2017-08-21 15:47:51 +02001640("<code>x</code> is assignable to <code>T</code>") if one of the following conditions applies:
Rob Pike5af7de32009-02-24 15:17:59 -08001641</p>
Robert Griesemer19b1d352009-09-24 19:36:48 -07001642
Rob Pike5af7de32009-02-24 15:17:59 -08001643<ul>
1644<li>
Robert Griesemer7bc03712010-06-07 15:49:39 -07001645<code>x</code>'s type is identical to <code>T</code>.
1646</li>
1647<li>
Rob Pike68f16092010-09-01 10:40:50 +10001648<code>x</code>'s type <code>V</code> and <code>T</code> have identical
1649<a href="#Types">underlying types</a> and at least one of <code>V</code>
Robert Griesemer56c9b512017-02-02 15:43:56 -08001650or <code>T</code> is not a <a href="#Type_definitions">defined</a> type.
Rob Pike5af7de32009-02-24 15:17:59 -08001651</li>
1652<li>
Robert Griesemer19b1d352009-09-24 19:36:48 -07001653<code>T</code> is an interface type and
Robert Griesemer7bc03712010-06-07 15:49:39 -07001654<code>x</code> <a href="#Interface_types">implements</a> <code>T</code>.
Robert Griesemere2cb60b2009-06-19 13:03:01 -07001655</li>
1656<li>
Robert Griesemer7bc03712010-06-07 15:49:39 -07001657<code>x</code> is a bidirectional channel value, <code>T</code> is a channel type,
1658<code>x</code>'s type <code>V</code> and <code>T</code> have identical element types,
Robert Griesemer56c9b512017-02-02 15:43:56 -08001659and at least one of <code>V</code> or <code>T</code> is not a defined type.
Robert Griesemer7bc03712010-06-07 15:49:39 -07001660</li>
1661<li>
1662<code>x</code> is the predeclared identifier <code>nil</code> and <code>T</code>
1663is a pointer, function, slice, map, channel, or interface type.
1664</li>
1665<li>
griesemerb40831b2017-08-21 15:47:51 +02001666<code>x</code> is an untyped <a href="#Constants">constant</a>
1667<a href="#Representability">representable</a>
Robert Griesemer7bc03712010-06-07 15:49:39 -07001668by a value of type <code>T</code>.
Robert Griesemer4e56b332009-09-10 10:14:00 -07001669</li>
Rob Pike5af7de32009-02-24 15:17:59 -08001670</ul>
1671
Rob Pikea9ed30f2009-02-23 19:26:07 -08001672
griesemerb40831b2017-08-21 15:47:51 +02001673<h3 id="Representability">Representability</h3>
1674
1675<p>
1676A <a href="#Constants">constant</a> <code>x</code> is <i>representable</i>
1677by a value of type <code>T</code> if one of the following conditions applies:
1678</p>
1679
1680<ul>
1681<li>
1682<code>x</code> is in the set of values <a href="#Types">determined</a> by <code>T</code>.
1683</li>
1684
1685<li>
1686<code>T</code> is a floating-point type and <code>x</code> can be rounded to <code>T</code>'s
1687precision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEE
1688negative zero further simplified to an unsigned zero. Note that constant values never result
1689in an IEEE negative zero, NaN, or infinity.
1690</li>
1691
1692<li>
1693<code>T</code> is a complex type, and <code>x</code>'s
1694<a href="#Complex_numbers">components</a> <code>real(x)</code> and <code>imag(x)</code>
1695are representable by values of <code>T</code>'s component type (<code>float32</code> or
1696<code>float64</code>).
1697</li>
1698</ul>
1699
1700<pre>
1701x T x is representable by a value of T because
1702
1703'a' byte 97 is in the set of byte values
170497 rune rune is an alias for int32, and 97 is in the set of 32-bit integers
1705"foo" string "foo" is in the set of string values
17061024 int16 1024 is in the set of 16-bit integers
170742.0 byte 42 is in the set of unsigned 8-bit integers
17081e10 uint64 10000000000 is in the set of unsigned 64-bit integers
17092.718281828459045 float32 2.718281828459045 rounds to 2.7182817 which is in the set of float32 values
1710-1e-1000 float64 -1e-1000 rounds to IEEE -0.0 which is further simplified to 0.0
17110i int 0 is an integer value
1712(42 + 0i) float32 42.0 (with zero imaginary part) is in the set of float32 values
1713</pre>
1714
1715<pre>
1716x T x is not representable by a value of T because
1717
17180 bool 0 is not in the set of boolean values
1719'a' string 'a' is a rune, it is not in the set of string values
17201024 byte 1024 is not in the set of unsigned 8-bit integers
1721-1 uint16 -1 is not in the set of unsigned 16-bit integers
17221.1 int 1.1 is not an integer value
172342i float32 (0 + 42i) is not in the set of float32 values
17241e1000 float64 1e1000 overflows to IEEE +Inf after rounding
1725</pre>
1726
1727
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001728<h2 id="Blocks">Blocks</h2>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001729
1730<p>
Robert Griesemer9905cec2013-03-04 13:55:35 -08001731A <i>block</i> is a possibly empty sequence of declarations and statements
1732within matching brace brackets.
Rob Pikea9ed30f2009-02-23 19:26:07 -08001733</p>
1734
Robert Griesemerf7ac31362009-07-10 16:06:40 -07001735<pre class="ebnf">
Robert Griesemer9905cec2013-03-04 13:55:35 -08001736Block = "{" StatementList "}" .
1737StatementList = { Statement ";" } .
Rob Pikea9ed30f2009-02-23 19:26:07 -08001738</pre>
Russ Cox5958dd62009-03-04 17:19:21 -08001739
Rob Pikea9ed30f2009-02-23 19:26:07 -08001740<p>
Robert Griesemer0a162a12009-08-19 16:44:04 -07001741In addition to explicit blocks in the source code, there are implicit blocks:
Rob Pikea9ed30f2009-02-23 19:26:07 -08001742</p>
1743
1744<ol>
Robert Griesemer0a162a12009-08-19 16:44:04 -07001745 <li>The <i>universe block</i> encompasses all Go source text.</li>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001746
Robert Griesemer4e56b332009-09-10 10:14:00 -07001747 <li>Each <a href="#Packages">package</a> has a <i>package block</i> containing all
Robert Griesemer0a162a12009-08-19 16:44:04 -07001748 Go source text for that package.</li>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001749
Robert Griesemer0a162a12009-08-19 16:44:04 -07001750 <li>Each file has a <i>file block</i> containing all Go source text
1751 in that file.</li>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001752
Robert Griesemer9905cec2013-03-04 13:55:35 -08001753 <li>Each <a href="#If_statements">"if"</a>,
1754 <a href="#For_statements">"for"</a>, and
1755 <a href="#Switch_statements">"switch"</a>
Robert Griesemer0a162a12009-08-19 16:44:04 -07001756 statement is considered to be in its own implicit block.</li>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001757
Robert Griesemer9905cec2013-03-04 13:55:35 -08001758 <li>Each clause in a <a href="#Switch_statements">"switch"</a>
1759 or <a href="#Select_statements">"select"</a> statement
Robert Griesemer0a162a12009-08-19 16:44:04 -07001760 acts as an implicit block.</li>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001761</ol>
1762
Robert Griesemer0a162a12009-08-19 16:44:04 -07001763<p>
Robert Griesemer4e56b332009-09-10 10:14:00 -07001764Blocks nest and influence <a href="#Declarations_and_scope">scoping</a>.
Robert Griesemer0a162a12009-08-19 16:44:04 -07001765</p>
1766
1767
Robert Griesemeraeaab592009-08-31 17:30:55 -07001768<h2 id="Declarations_and_scope">Declarations and scope</h2>
Robert Griesemer0a162a12009-08-19 16:44:04 -07001769
1770<p>
Robert Griesemer4cc71e32013-10-03 16:38:22 -07001771A <i>declaration</i> binds a non-<a href="#Blank_identifier">blank</a> identifier to a
1772<a href="#Constant_declarations">constant</a>,
1773<a href="#Type_declarations">type</a>,
1774<a href="#Variable_declarations">variable</a>,
1775<a href="#Function_declarations">function</a>,
1776<a href="#Labeled_statements">label</a>, or
1777<a href="#Import_declarations">package</a>.
Robert Griesemer0a162a12009-08-19 16:44:04 -07001778Every identifier in a program must be declared.
1779No identifier may be declared twice in the same block, and
1780no identifier may be declared in both the file and package block.
1781</p>
1782
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05001783<p>
1784The <a href="#Blank_identifier">blank identifier</a> may be used like any other identifier
1785in a declaration, but it does not introduce a binding and thus is not declared.
Robert Griesemera4366982014-05-20 13:51:39 -07001786In the package block, the identifier <code>init</code> may only be used for
1787<a href="#Package_initialization"><code>init</code> function</a> declarations,
1788and like the blank identifier it does not introduce a new binding.
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05001789</p>
1790
Robert Griesemer0a162a12009-08-19 16:44:04 -07001791<pre class="ebnf">
1792Declaration = ConstDecl | TypeDecl | VarDecl .
1793TopLevelDecl = Declaration | FunctionDecl | MethodDecl .
1794</pre>
1795
1796<p>
1797The <i>scope</i> of a declared identifier is the extent of source text in which
Robert Griesemer4cc71e32013-10-03 16:38:22 -07001798the identifier denotes the specified constant, type, variable, function, label, or package.
Robert Griesemer0a162a12009-08-19 16:44:04 -07001799</p>
1800
1801<p>
Robert Griesemer4cc71e32013-10-03 16:38:22 -07001802Go is lexically scoped using <a href="#Blocks">blocks</a>:
Robert Griesemer0a162a12009-08-19 16:44:04 -07001803</p>
1804
1805<ol>
Robert Griesemer4cc71e32013-10-03 16:38:22 -07001806 <li>The scope of a <a href="#Predeclared_identifiers">predeclared identifier</a> is the universe block.</li>
Robert Griesemer0a162a12009-08-19 16:44:04 -07001807
1808 <li>The scope of an identifier denoting a constant, type, variable,
Robert Griesemer967a2b32011-03-03 15:24:28 -08001809 or function (but not method) declared at top level (outside any
1810 function) is the package block.</li>
Robert Griesemer0a162a12009-08-19 16:44:04 -07001811
Robert Griesemere1267632012-11-21 14:40:50 -08001812 <li>The scope of the package name of an imported package is the file block
Robert Griesemer0a162a12009-08-19 16:44:04 -07001813 of the file containing the import declaration.</li>
1814
Robert Griesemer85e451e2012-11-29 14:47:47 -08001815 <li>The scope of an identifier denoting a method receiver, function parameter,
1816 or result variable is the function body.</li>
Robert Griesemer0a162a12009-08-19 16:44:04 -07001817
1818 <li>The scope of a constant or variable identifier declared
1819 inside a function begins at the end of the ConstSpec or VarSpec
Robert Griesemer95b81372011-06-12 12:09:50 -07001820 (ShortVarDecl for short variable declarations)
Robert Griesemer0a162a12009-08-19 16:44:04 -07001821 and ends at the end of the innermost containing block.</li>
1822
1823 <li>The scope of a type identifier declared inside a function
Russ Cox16b95ba2009-08-20 10:22:52 -07001824 begins at the identifier in the TypeSpec
Robert Griesemer0a162a12009-08-19 16:44:04 -07001825 and ends at the end of the innermost containing block.</li>
1826</ol>
1827
1828<p>
1829An identifier declared in a block may be redeclared in an inner block.
1830While the identifier of the inner declaration is in scope, it denotes
1831the entity declared by the inner declaration.
1832</p>
1833
1834<p>
Robert Griesemer506c0082009-09-08 15:41:14 -07001835The <a href="#Package_clause">package clause</a> is not a declaration; the package name
Robert Griesemer0a162a12009-08-19 16:44:04 -07001836does not appear in any scope. Its purpose is to identify the files belonging
Robert Griesemer997851e2009-09-25 15:36:25 -07001837to the same <a href="#Packages">package</a> and to specify the default package name for import
Robert Griesemer0a162a12009-08-19 16:44:04 -07001838declarations.
1839</p>
1840
1841
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001842<h3 id="Label_scopes">Label scopes</h3>
Robert Griesemer0a162a12009-08-19 16:44:04 -07001843
1844<p>
Robert Griesemer506c0082009-09-08 15:41:14 -07001845Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are
Robert Griesemer462a17e2013-03-22 15:36:04 -07001846used in the <a href="#Break_statements">"break"</a>,
1847<a href="#Continue_statements">"continue"</a>, and
1848<a href="#Goto_statements">"goto"</a> statements.
Russ Cox108564d2011-03-15 13:51:24 -04001849It is illegal to define a label that is never used.
Robert Griesemer0a162a12009-08-19 16:44:04 -07001850In contrast to other identifiers, labels are not block scoped and do
1851not conflict with identifiers that are not labels. The scope of a label
1852is the body of the function in which it is declared and excludes
1853the body of any nested function.
1854</p>
1855
1856
Robert Griesemer103c9db2012-03-01 13:57:49 -08001857<h3 id="Blank_identifier">Blank identifier</h3>
1858
1859<p>
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05001860The <i>blank identifier</i> is represented by the underscore character <code>_</code>.
1861It serves as an anonymous placeholder instead of a regular (non-blank)
1862identifier and has special meaning in <a href="#Declarations_and_scope">declarations</a>,
1863as an <a href="#Operands">operand</a>, and in <a href="#Assignments">assignments</a>.
Robert Griesemer103c9db2012-03-01 13:57:49 -08001864</p>
1865
1866
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001867<h3 id="Predeclared_identifiers">Predeclared identifiers</h3>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001868
1869<p>
Robert Griesemer103c9db2012-03-01 13:57:49 -08001870The following identifiers are implicitly declared in the
1871<a href="#Blocks">universe block</a>:
Rob Pikea9ed30f2009-02-23 19:26:07 -08001872</p>
1873<pre class="grammar">
Russ Coxd9877e22011-11-01 21:45:02 -04001874Types:
1875 bool byte complex64 complex128 error float32 float64
1876 int int8 int16 int32 int64 rune string
1877 uint uint8 uint16 uint32 uint64 uintptr
Rob Pikea9ed30f2009-02-23 19:26:07 -08001878
1879Constants:
Robert Griesemer19b1d352009-09-24 19:36:48 -07001880 true false iota
1881
1882Zero value:
1883 nil
Rob Pikea9ed30f2009-02-23 19:26:07 -08001884
1885Functions:
Robert Griesemerb910a272011-11-01 01:09:22 -04001886 append cap close complex copy delete imag len
Robert Griesemer07e983a2010-10-25 16:50:31 -07001887 make new panic print println real recover
Rob Pikea9ed30f2009-02-23 19:26:07 -08001888</pre>
1889
Robert Griesemeraeaab592009-08-31 17:30:55 -07001890
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001891<h3 id="Exported_identifiers">Exported identifiers</h3>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001892
1893<p>
Robert Griesemer103c9db2012-03-01 13:57:49 -08001894An identifier may be <i>exported</i> to permit access to it from another package.
1895An identifier is exported if both:
Rob Pikea9ed30f2009-02-23 19:26:07 -08001896</p>
1897<ol>
Robert Griesemer103c9db2012-03-01 13:57:49 -08001898 <li>the first character of the identifier's name is a Unicode upper case
1899 letter (Unicode class "Lu"); and</li>
1900 <li>the identifier is declared in the <a href="#Blocks">package block</a>
1901 or it is a <a href="#Struct_types">field name</a> or
1902 <a href="#MethodName">method name</a>.</li>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001903</ol>
1904<p>
Robert Griesemeraeaab592009-08-31 17:30:55 -07001905All other identifiers are not exported.
Rob Pikea9ed30f2009-02-23 19:26:07 -08001906</p>
1907
Robert Griesemeraeaab592009-08-31 17:30:55 -07001908
Robert Griesemer103c9db2012-03-01 13:57:49 -08001909<h3 id="Uniqueness_of_identifiers">Uniqueness of identifiers</h3>
Robert Griesemer4e56b332009-09-10 10:14:00 -07001910
1911<p>
Robert Griesemer103c9db2012-03-01 13:57:49 -08001912Given a set of identifiers, an identifier is called <i>unique</i> if it is
1913<i>different</i> from every other in the set.
1914Two identifiers are different if they are spelled differently, or if they
1915appear in different <a href="#Packages">packages</a> and are not
Shenghou Ma2195f1a2012-03-30 14:04:03 +08001916<a href="#Exported_identifiers">exported</a>. Otherwise, they are the same.
Robert Griesemer4e56b332009-09-10 10:14:00 -07001917</p>
1918
Robert Griesemer19b1d352009-09-24 19:36:48 -07001919<h3 id="Constant_declarations">Constant declarations</h3>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001920
1921<p>
1922A constant declaration binds a list of identifiers (the names of
Robert Griesemer506c0082009-09-08 15:41:14 -07001923the constants) to the values of a list of <a href="#Constant_expressions">constant expressions</a>.
1924The number of identifiers must be equal
1925to the number of expressions, and the <i>n</i>th identifier on
1926the left is bound to the value of the <i>n</i>th expression on the
Rob Pikea9ed30f2009-02-23 19:26:07 -08001927right.
1928</p>
1929
Robert Griesemerf7ac31362009-07-10 16:06:40 -07001930<pre class="ebnf">
Robert Griesemer87f4e362016-11-04 12:38:53 -07001931ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
Robert Griesemer4023dce2009-08-14 17:41:52 -07001932ConstSpec = IdentifierList [ [ Type ] "=" ExpressionList ] .
Rob Pikea9ed30f2009-02-23 19:26:07 -08001933
1934IdentifierList = identifier { "," identifier } .
1935ExpressionList = Expression { "," Expression } .
Rob Pikea9ed30f2009-02-23 19:26:07 -08001936</pre>
1937
1938<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -07001939If the type is present, all constants take the type specified, and
Robert Griesemer440cc952010-06-07 17:40:21 -07001940the expressions must be <a href="#Assignability">assignable</a> to that type.
Robert Griesemer4023dce2009-08-14 17:41:52 -07001941If the type is omitted, the constants take the
Robert Griesemer19b1d352009-09-24 19:36:48 -07001942individual types of the corresponding expressions.
1943If the expression values are untyped <a href="#Constants">constants</a>,
1944the declared constants remain untyped and the constant identifiers
1945denote the constant values. For instance, if the expression is a
1946floating-point literal, the constant identifier denotes a floating-point
1947constant, even if the literal's fractional part is zero.
Rob Pikea9ed30f2009-02-23 19:26:07 -08001948</p>
1949
1950<pre>
1951const Pi float64 = 3.14159265358979323846
David Symonds72a29792011-11-29 15:47:36 -08001952const zero = 0.0 // untyped floating-point constant
Rob Pikea9ed30f2009-02-23 19:26:07 -08001953const (
Robert Griesemer130ac742009-12-10 16:43:01 -08001954 size int64 = 1024
David Symonds72a29792011-11-29 15:47:36 -08001955 eof = -1 // untyped integer constant
Rob Pikea9ed30f2009-02-23 19:26:07 -08001956)
Robert Griesemer19b1d352009-09-24 19:36:48 -07001957const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constants
Robert Griesemerb94c0d22011-01-19 23:07:21 -05001958const u, v float32 = 0, 3 // u = 0.0, v = 3.0
Rob Pikea9ed30f2009-02-23 19:26:07 -08001959</pre>
1960
1961<p>
1962Within a parenthesized <code>const</code> declaration list the
griesemer85177f42017-10-19 11:48:54 -07001963expression list may be omitted from any but the first ConstSpec.
Rob Pikea9ed30f2009-02-23 19:26:07 -08001964Such an empty list is equivalent to the textual substitution of the
Rob Pike678625d2009-09-15 09:54:22 -07001965first preceding non-empty expression list and its type if any.
Russ Cox5958dd62009-03-04 17:19:21 -08001966Omitting the list of expressions is therefore equivalent to
1967repeating the previous list. The number of identifiers must be equal
1968to the number of expressions in the previous list.
Robert Griesemer506c0082009-09-08 15:41:14 -07001969Together with the <a href="#Iota"><code>iota</code> constant generator</a>
1970this mechanism permits light-weight declaration of sequential values:
Rob Pikea9ed30f2009-02-23 19:26:07 -08001971</p>
1972
1973<pre>
1974const (
Robert Griesemer130ac742009-12-10 16:43:01 -08001975 Sunday = iota
1976 Monday
1977 Tuesday
1978 Wednesday
1979 Thursday
1980 Friday
1981 Partyday
1982 numberOfDays // this constant is not exported
Rob Pikea9ed30f2009-02-23 19:26:07 -08001983)
1984</pre>
1985
1986
Russ Cox7c4f7cc2009-08-20 11:11:03 -07001987<h3 id="Iota">Iota</h3>
Rob Pikea9ed30f2009-02-23 19:26:07 -08001988
1989<p>
Robert Griesemer39f009c2010-04-29 10:57:27 -07001990Within a <a href="#Constant_declarations">constant declaration</a>, the predeclared identifier
Robert Griesemer19b1d352009-09-24 19:36:48 -07001991<code>iota</code> represents successive untyped integer <a href="#Constants">
griesemer52dd3992017-10-18 15:31:42 -07001992constants</a>. Its value is the index of the respective <a href="#ConstSpec">ConstSpec</a>
1993in that constant declaration, starting at zero.
Robert Griesemer39f009c2010-04-29 10:57:27 -07001994It can be used to construct a set of related constants:
Rob Pikea9ed30f2009-02-23 19:26:07 -08001995</p>
1996
1997<pre>
griesemer85177f42017-10-19 11:48:54 -07001998const (
Robert Griesemer130ac742009-12-10 16:43:01 -08001999 c0 = iota // c0 == 0
2000 c1 = iota // c1 == 1
2001 c2 = iota // c2 == 2
Rob Pikea9ed30f2009-02-23 19:26:07 -08002002)
2003
griesemer85177f42017-10-19 11:48:54 -07002004const (
2005 a = 1 &lt;&lt; iota // a == 1 (iota == 0)
2006 b = 1 &lt;&lt; iota // b == 2 (iota == 1)
2007 c = 3 // c == 3 (iota == 2, unused)
2008 d = 1 &lt;&lt; iota // d == 8 (iota == 3)
Rob Pikea9ed30f2009-02-23 19:26:07 -08002009)
2010
griesemer85177f42017-10-19 11:48:54 -07002011const (
Robert Griesemerb94c0d22011-01-19 23:07:21 -05002012 u = iota * 42 // u == 0 (untyped integer constant)
2013 v float64 = iota * 42 // v == 42.0 (float64 constant)
2014 w = iota * 42 // w == 84 (untyped integer constant)
Rob Pikea9ed30f2009-02-23 19:26:07 -08002015)
2016
griesemer85177f42017-10-19 11:48:54 -07002017const x = iota // x == 0
2018const y = iota // y == 0
Rob Pikea9ed30f2009-02-23 19:26:07 -08002019</pre>
2020
2021<p>
griesemer85177f42017-10-19 11:48:54 -07002022By definition, multiple uses of <code>iota</code> in the same ConstSpec all have the same value:
Rob Pikea9ed30f2009-02-23 19:26:07 -08002023</p>
2024
2025<pre>
2026const (
griesemer85177f42017-10-19 11:48:54 -07002027 bit0, mask0 = 1 &lt;&lt; iota, 1&lt;&lt;iota - 1 // bit0 == 1, mask0 == 0 (iota == 0)
2028 bit1, mask1 // bit1 == 2, mask1 == 1 (iota == 1)
2029 _, _ // (iota == 2, unused)
2030 bit3, mask3 // bit3 == 8, mask3 == 7 (iota == 3)
Rob Pikea9ed30f2009-02-23 19:26:07 -08002031)
2032</pre>
2033
2034<p>
griesemer85177f42017-10-19 11:48:54 -07002035This last example exploits the <a href="#Constant_declarations">implicit repetition</a>
2036of the last non-empty expression list.
Rob Pikea9ed30f2009-02-23 19:26:07 -08002037</p>
2038
2039
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002040<h3 id="Type_declarations">Type declarations</h3>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002041
2042<p>
Robert Griesemer56c9b512017-02-02 15:43:56 -08002043A type declaration binds an identifier, the <i>type name</i>, to a <a href="#Types">type</a>.
Robert Griesemerc0bd4f32017-02-06 15:57:00 -08002044Type declarations come in two forms: alias declarations and type definitions.
Rob Pikecae9a9f2020-01-13 16:03:12 +11002045</p>
Robert Griesemer56c9b512017-02-02 15:43:56 -08002046
2047<pre class="ebnf">
2048TypeDecl = "type" ( TypeSpec | "(" { TypeSpec ";" } ")" ) .
2049TypeSpec = AliasDecl | TypeDef .
2050</pre>
2051
2052<h4 id="Alias_declarations">Alias declarations</h4>
2053
2054<p>
2055An alias declaration binds an identifier to the given type.
Rob Pikea9ed30f2009-02-23 19:26:07 -08002056</p>
2057
Robert Griesemerf7ac31362009-07-10 16:06:40 -07002058<pre class="ebnf">
Robert Griesemer56c9b512017-02-02 15:43:56 -08002059AliasDecl = identifier "=" Type .
Rob Pikea9ed30f2009-02-23 19:26:07 -08002060</pre>
2061
Robert Griesemer56c9b512017-02-02 15:43:56 -08002062<p>
2063Within the <a href="#Declarations_and_scope">scope</a> of
2064the identifier, it serves as an <i>alias</i> for the type.
2065</p>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002066
Robert Griesemer56c9b512017-02-02 15:43:56 -08002067<pre>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002068type (
Robert Griesemer56c9b512017-02-02 15:43:56 -08002069 nodeList = []*Node // nodeList and []*Node are identical types
2070 Polar = polar // Polar and polar denote identical types
2071)
2072</pre>
2073
2074
2075<h4 id="Type_definitions">Type definitions</h4>
2076
2077<p>
Robert Griesemerc0bd4f32017-02-06 15:57:00 -08002078A type definition creates a new, distinct type with the same
2079<a href="#Types">underlying type</a> and operations as the given type,
2080and binds an identifier to it.
Robert Griesemer56c9b512017-02-02 15:43:56 -08002081</p>
2082
2083<pre class="ebnf">
2084TypeDef = identifier Type .
2085</pre>
2086
2087<p>
2088The new type is called a <i>defined type</i>.
2089It is <a href="#Type_identity">different</a> from any other type,
2090including the type it is created from.
2091</p>
2092
2093<pre>
2094type (
2095 Point struct{ x, y float64 } // Point and struct{ x, y float64 } are different types
2096 polar Point // polar and Point denote different types
Rob Pikea9ed30f2009-02-23 19:26:07 -08002097)
2098
2099type TreeNode struct {
Robert Griesemer130ac742009-12-10 16:43:01 -08002100 left, right *TreeNode
2101 value *Comparable
Rob Pikea9ed30f2009-02-23 19:26:07 -08002102}
2103
Rob Pike217408a2011-11-09 14:22:44 -08002104type Block interface {
Robert Griesemer130ac742009-12-10 16:43:01 -08002105 BlockSize() int
2106 Encrypt(src, dst []byte)
2107 Decrypt(src, dst []byte)
Rob Pikea9ed30f2009-02-23 19:26:07 -08002108}
2109</pre>
2110
Robert Griesemerfc61b772009-09-28 14:10:20 -07002111<p>
Robert Griesemer56c9b512017-02-02 15:43:56 -08002112A defined type may have <a href="#Method_declarations">methods</a> associated with it.
2113It does not inherit any methods bound to the given type,
2114but the <a href="#Method_sets">method set</a>
Robert Griesemerd4a16192010-04-01 12:48:34 -07002115of an interface type or of elements of a composite type remains unchanged:
Robert Griesemerfc61b772009-09-28 14:10:20 -07002116</p>
2117
2118<pre>
Rob Pikebdbe0de2011-05-25 06:00:07 +10002119// A Mutex is a data type with two methods, Lock and Unlock.
Robert Griesemerfc61b772009-09-28 14:10:20 -07002120type Mutex struct { /* Mutex fields */ }
2121func (m *Mutex) Lock() { /* Lock implementation */ }
2122func (m *Mutex) Unlock() { /* Unlock implementation */ }
2123
2124// NewMutex has the same composition as Mutex but its method set is empty.
2125type NewMutex Mutex
2126
griesemer5abc8c892017-08-11 16:51:40 +02002127// The method set of PtrMutex's underlying type *Mutex remains unchanged,
Robert Griesemer2a838d62011-02-08 13:31:01 -08002128// but the method set of PtrMutex is empty.
2129type PtrMutex *Mutex
2130
Robert Griesemerf5b3c142010-04-27 17:52:44 -07002131// The method set of *PrintableMutex contains the methods
Robert Griesemerf8b41232017-01-10 16:19:14 -08002132// Lock and Unlock bound to its embedded field Mutex.
Robert Griesemerfc61b772009-09-28 14:10:20 -07002133type PrintableMutex struct {
Robert Griesemer130ac742009-12-10 16:43:01 -08002134 Mutex
Robert Griesemerfc61b772009-09-28 14:10:20 -07002135}
Robert Griesemer735e00d2010-03-31 16:37:22 -07002136
Rob Pike217408a2011-11-09 14:22:44 -08002137// MyBlock is an interface type that has the same method set as Block.
2138type MyBlock Block
Robert Griesemerfc61b772009-09-28 14:10:20 -07002139</pre>
2140
2141<p>
Robert Griesemer56c9b512017-02-02 15:43:56 -08002142Type definitions may be used to define different boolean, numeric,
2143or string types and associate methods with them:
Robert Griesemerfc61b772009-09-28 14:10:20 -07002144</p>
2145
2146<pre>
2147type TimeZone int
2148
2149const (
Robert Griesemer130ac742009-12-10 16:43:01 -08002150 EST TimeZone = -(5 + iota)
2151 CST
2152 MST
2153 PST
Robert Griesemerfc61b772009-09-28 14:10:20 -07002154)
2155
2156func (tz TimeZone) String() string {
Robert Griesemer02d74482015-07-31 11:15:11 -07002157 return fmt.Sprintf("GMT%+dh", tz)
Robert Griesemerfc61b772009-09-28 14:10:20 -07002158}
2159</pre>
2160
2161
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002162<h3 id="Variable_declarations">Variable declarations</h3>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002163
2164<p>
Robert Griesemer56c9b512017-02-02 15:43:56 -08002165A variable declaration creates one or more <a href="#Variables">variables</a>,
2166binds corresponding identifiers to them, and gives each a type and an initial value.
Rob Pikea9ed30f2009-02-23 19:26:07 -08002167</p>
Robert Griesemer47094dc2014-09-30 11:44:29 -07002168
Robert Griesemerf7ac31362009-07-10 16:06:40 -07002169<pre class="ebnf">
Robert Griesemer87f4e362016-11-04 12:38:53 -07002170VarDecl = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
Robert Griesemer4023dce2009-08-14 17:41:52 -07002171VarSpec = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .
Rob Pikea9ed30f2009-02-23 19:26:07 -08002172</pre>
2173
2174<pre>
2175var i int
Robert Griesemerb94c0d22011-01-19 23:07:21 -05002176var U, V, W float64
Rob Pikea9ed30f2009-02-23 19:26:07 -08002177var k = 0
Robert Griesemerb94c0d22011-01-19 23:07:21 -05002178var x, y float32 = -1, -2
Rob Pikea9ed30f2009-02-23 19:26:07 -08002179var (
David Symonds72a29792011-11-29 15:47:36 -08002180 i int
Rob Pikea9ed30f2009-02-23 19:26:07 -08002181 u, v, s = 2.0, 3.0, "bar"
2182)
Robert Griesemer4e56b332009-09-10 10:14:00 -07002183var re, im = complexSqrt(-1)
Robert Griesemer130ac742009-12-10 16:43:01 -08002184var _, found = entries[name] // map lookup; only interested in "found"
Rob Pikea9ed30f2009-02-23 19:26:07 -08002185</pre>
2186
2187<p>
Robert Griesemeref45e642009-08-21 11:25:00 -07002188If a list of expressions is given, the variables are initialized
Robert Griesemer47094dc2014-09-30 11:44:29 -07002189with the expressions following the rules for <a href="#Assignments">assignments</a>.
Rob Pike4fe41922009-11-07 22:00:59 -08002190Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>.
Rob Pikea9ed30f2009-02-23 19:26:07 -08002191</p>
Robert Griesemeref45e642009-08-21 11:25:00 -07002192
Rob Pikea9ed30f2009-02-23 19:26:07 -08002193<p>
Robert Griesemer47094dc2014-09-30 11:44:29 -07002194If a type is present, each variable is given that type.
2195Otherwise, each variable is given the type of the corresponding
2196initialization value in the assignment.
Robert Griesemer26d22602018-10-02 15:55:38 -07002197If that value is an untyped constant, it is first implicitly
Robert Griesemer47094dc2014-09-30 11:44:29 -07002198<a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>;
Robert Griesemer26d22602018-10-02 15:55:38 -07002199if it is an untyped boolean value, it is first implicitly converted to type <code>bool</code>.
Robert Griesemer47094dc2014-09-30 11:44:29 -07002200The predeclared value <code>nil</code> cannot be used to initialize a variable
2201with no explicit type.
Rob Pikea9ed30f2009-02-23 19:26:07 -08002202</p>
Robert Griesemeref45e642009-08-21 11:25:00 -07002203
Robert Griesemer47094dc2014-09-30 11:44:29 -07002204<pre>
Brad Fitzpatrick5f029de2014-12-22 07:58:26 -08002205var d = math.Sin(0.5) // d is float64
Robert Griesemer47094dc2014-09-30 11:44:29 -07002206var i = 42 // i is int
2207var t, ok = x.(T) // t is T, ok is bool
2208var n = nil // illegal
2209</pre>
Robert Griesemer2c9e1632012-02-28 17:44:24 -08002210
2211<p>
2212Implementation restriction: A compiler may make it illegal to declare a variable
2213inside a <a href="#Function_declarations">function body</a> if the variable is
2214never used.
2215</p>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002216
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002217<h3 id="Short_variable_declarations">Short variable declarations</h3>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002218
Robert Griesemer997851e2009-09-25 15:36:25 -07002219<p>
Robert Griesemeref45e642009-08-21 11:25:00 -07002220A <i>short variable declaration</i> uses the syntax:
Robert Griesemer997851e2009-09-25 15:36:25 -07002221</p>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002222
Robert Griesemerf7ac31362009-07-10 16:06:40 -07002223<pre class="ebnf">
Robert Griesemere1b8cb82009-07-16 20:31:41 -07002224ShortVarDecl = IdentifierList ":=" ExpressionList .
Rob Pikea9ed30f2009-02-23 19:26:07 -08002225</pre>
2226
Robert Griesemer997851e2009-09-25 15:36:25 -07002227<p>
Robert Griesemer2961d222013-07-31 22:25:47 -07002228It is shorthand for a regular <a href="#Variable_declarations">variable declaration</a>
Robert Griesemer2c9e1632012-02-28 17:44:24 -08002229with initializer expressions but no types:
Robert Griesemer997851e2009-09-25 15:36:25 -07002230</p>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002231
2232<pre class="grammar">
2233"var" IdentifierList = ExpressionList .
2234</pre>
2235
2236<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08002237i, j := 0, 10
2238f := func() int { return 7 }
2239ch := make(chan int)
Dina Garmash8a2b5f12018-08-30 16:59:29 -04002240r, w, _ := os.Pipe() // os.Pipe() returns a connected pair of Files and an error, if any
2241_, y, _ := coord(p) // coord() returns three values; only interested in y coordinate
Rob Pikea9ed30f2009-02-23 19:26:07 -08002242</pre>
2243
2244<p>
Robert Griesemer85789da2015-08-04 11:29:28 -07002245Unlike regular variable declarations, a short variable declaration may <i>redeclare</i>
2246variables provided they were originally declared earlier in the same block
Robert Griesemer120cf672016-11-17 16:39:11 -08002247(or the parameter lists if the block is the function body) with the same type,
Robert Griesemer85789da2015-08-04 11:29:28 -07002248and at least one of the non-<a href="#Blank_identifier">blank</a> variables is new.
2249As a consequence, redeclaration can only appear in a multi-variable short declaration.
2250Redeclaration does not introduce a new variable; it just assigns a new value to the original.
Rob Pike2a1683a2009-04-19 20:04:15 -07002251</p>
2252
2253<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08002254field1, offset := nextField(str, 0)
2255field2, offset := nextField(str, offset) // redeclares offset
Robert Griesemerf1cc0f42013-01-09 11:31:32 -08002256a, a := 1, 2 // illegal: double declaration of a or no new variable if a was declared elsewhere
Rob Pike2a1683a2009-04-19 20:04:15 -07002257</pre>
2258
2259<p>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002260Short variable declarations may appear only inside functions.
Robert Griesemer462a17e2013-03-22 15:36:04 -07002261In some contexts such as the initializers for
2262<a href="#If_statements">"if"</a>,
2263<a href="#For_statements">"for"</a>, or
2264<a href="#Switch_statements">"switch"</a> statements,
2265they can be used to declare local temporary variables.
Rob Pikea9ed30f2009-02-23 19:26:07 -08002266</p>
2267
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002268<h3 id="Function_declarations">Function declarations</h3>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002269
2270<p>
Robert Griesemerb1d9ae92012-02-12 20:03:30 -08002271A function declaration binds an identifier, the <i>function name</i>,
2272to a function.
Rob Pikea9ed30f2009-02-23 19:26:07 -08002273</p>
2274
Robert Griesemerf7ac31362009-07-10 16:06:40 -07002275<pre class="ebnf">
Robert Griesemer851e98f2018-02-01 14:08:45 -08002276FunctionDecl = "func" FunctionName Signature [ FunctionBody ] .
Robert Griesemerb1d9ae92012-02-12 20:03:30 -08002277FunctionName = identifier .
Robert Griesemer9905cec2013-03-04 13:55:35 -08002278FunctionBody = Block .
Rob Pikea9ed30f2009-02-23 19:26:07 -08002279</pre>
2280
Robert Griesemer4023dce2009-08-14 17:41:52 -07002281<p>
Robert Griesemer9905cec2013-03-04 13:55:35 -08002282If the function's <a href="#Function_types">signature</a> declares
2283result parameters, the function body's statement list must end in
2284a <a href="#Terminating_statements">terminating statement</a>.
2285</p>
2286
Rob Piked0208912013-03-22 10:03:55 -07002287<pre>
Robert Griesemer02d74482015-07-31 11:15:11 -07002288func IndexRune(s string, r rune) int {
2289 for i, c := range s {
2290 if c == r {
2291 return i
Rob Piked0208912013-03-22 10:03:55 -07002292 }
2293 }
Robert Griesemer02d74482015-07-31 11:15:11 -07002294 // invalid: missing return statement
Rob Piked0208912013-03-22 10:03:55 -07002295}
2296</pre>
2297
Robert Griesemer9905cec2013-03-04 13:55:35 -08002298<p>
Robert Griesemer4023dce2009-08-14 17:41:52 -07002299A function declaration may omit the body. Such a declaration provides the
2300signature for a function implemented outside Go, such as an assembly routine.
2301</p>
2302
Rob Pikea9ed30f2009-02-23 19:26:07 -08002303<pre>
2304func min(x int, y int) int {
2305 if x &lt; y {
Robert Griesemer130ac742009-12-10 16:43:01 -08002306 return x
Rob Pikea9ed30f2009-02-23 19:26:07 -08002307 }
Robert Griesemer130ac742009-12-10 16:43:01 -08002308 return y
Rob Pikea9ed30f2009-02-23 19:26:07 -08002309}
Robert Griesemer4023dce2009-08-14 17:41:52 -07002310
2311func flushICache(begin, end uintptr) // implemented externally
Rob Pikea9ed30f2009-02-23 19:26:07 -08002312</pre>
2313
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002314<h3 id="Method_declarations">Method declarations</h3>
Rob Pikea9ed30f2009-02-23 19:26:07 -08002315
2316<p>
Robert Griesemer9905cec2013-03-04 13:55:35 -08002317A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>.
2318A method declaration binds an identifier, the <i>method name</i>, to a method,
2319and associates the method with the receiver's <i>base type</i>.
Rob Pikea9ed30f2009-02-23 19:26:07 -08002320</p>
Robert Griesemerb1d9ae92012-02-12 20:03:30 -08002321
Robert Griesemerf7ac31362009-07-10 16:06:40 -07002322<pre class="ebnf">
Robert Griesemer851e98f2018-02-01 14:08:45 -08002323MethodDecl = "func" Receiver MethodName Signature [ FunctionBody ] .
Robert Griesemer56c9b512017-02-02 15:43:56 -08002324Receiver = Parameters .
Rob Pikea9ed30f2009-02-23 19:26:07 -08002325</pre>
2326
2327<p>
Paolo Martini35491782015-07-17 17:26:08 +02002328The receiver is specified via an extra parameter section preceding the method
Robert Griesemer57c81ef2015-12-15 13:13:38 -08002329name. That parameter section must declare a single non-variadic parameter, the receiver.
Robert Griesemerbb3e2112018-10-16 16:50:25 -07002330Its type must be a <a href="#Type_definitions">defined</a> type <code>T</code> or a
2331pointer to a defined type <code>T</code>. <code>T</code> is called the receiver
2332<i>base type</i>. A receiver base type cannot be a pointer or interface type and
2333it must be defined in the same package as the method.
2334The method is said to be <i>bound</i> to its receiver base type and the method name
Robert Griesemer05614bf2015-08-04 11:52:01 -07002335is visible only within <a href="#Selectors">selectors</a> for type <code>T</code>
2336or <code>*T</code>.
Robert Griesemerb1d9ae92012-02-12 20:03:30 -08002337</p>
2338
2339<p>
Robert Griesemer85e451e2012-11-29 14:47:47 -08002340A non-<a href="#Blank_identifier">blank</a> receiver identifier must be
2341<a href="#Uniqueness_of_identifiers">unique</a> in the method signature.
2342If the receiver's value is not referenced inside the body of the method,
2343its identifier may be omitted in the declaration. The same applies in
2344general to parameters of functions and methods.
2345</p>
2346
2347<p>
2348For a base type, the non-blank names of methods bound to it must be unique.
Robert Griesemerb1d9ae92012-02-12 20:03:30 -08002349If the base type is a <a href="#Struct_types">struct type</a>,
2350the non-blank method and field names must be distinct.
Rob Pikea9ed30f2009-02-23 19:26:07 -08002351</p>
2352
2353<p>
Robert Griesemerbb3e2112018-10-16 16:50:25 -07002354Given defined type <code>Point</code>, the declarations
Rob Pikea9ed30f2009-02-23 19:26:07 -08002355</p>
2356
2357<pre>
Robert Griesemer777a96a2010-12-02 12:32:14 -08002358func (p *Point) Length() float64 {
2359 return math.Sqrt(p.x * p.x + p.y * p.y)
Rob Pikea9ed30f2009-02-23 19:26:07 -08002360}
2361
Robert Griesemer777a96a2010-12-02 12:32:14 -08002362func (p *Point) Scale(factor float64) {
2363 p.x *= factor
2364 p.y *= factor
Rob Pikea9ed30f2009-02-23 19:26:07 -08002365}
2366</pre>
2367
2368<p>
Rob Pike678625d2009-09-15 09:54:22 -07002369bind the methods <code>Length</code> and <code>Scale</code>,
2370with receiver type <code>*Point</code>,
Rob Pikea9ed30f2009-02-23 19:26:07 -08002371to the base type <code>Point</code>.
2372</p>
2373
2374<p>
Rob Pikedf3183f2009-02-26 16:37:23 -08002375The type of a method is the type of a function with the receiver as first
2376argument. For instance, the method <code>Scale</code> has type
2377</p>
2378
2379<pre>
Robert Griesemer777a96a2010-12-02 12:32:14 -08002380func(p *Point, factor float64)
Rob Pikedf3183f2009-02-26 16:37:23 -08002381</pre>
2382
2383<p>
2384However, a function declared this way is not a method.
2385</p>
2386
Rob Pikea9ed30f2009-02-23 19:26:07 -08002387
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002388<h2 id="Expressions">Expressions</h2>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002389
Rob Pikedf3183f2009-02-26 16:37:23 -08002390<p>
2391An expression specifies the computation of a value by applying
Robert Griesemer19b1d352009-09-24 19:36:48 -07002392operators and functions to operands.
Rob Pikedf3183f2009-02-26 16:37:23 -08002393</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002394
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002395<h3 id="Operands">Operands</h3>
Robert Griesemerad711102008-09-11 17:48:20 -07002396
Robert Griesemer997851e2009-09-25 15:36:25 -07002397<p>
Robert Griesemer809e06b2012-06-26 11:49:19 -07002398Operands denote the elementary values in an expression. An operand may be a
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05002399literal, a (possibly <a href="#Qualified_identifiers">qualified</a>)
2400non-<a href="#Blank_identifier">blank</a> identifier denoting a
Robert Griesemer809e06b2012-06-26 11:49:19 -07002401<a href="#Constant_declarations">constant</a>,
2402<a href="#Variable_declarations">variable</a>, or
2403<a href="#Function_declarations">function</a>,
Robert Griesemer809e06b2012-06-26 11:49:19 -07002404or a parenthesized expression.
Robert Griesemer997851e2009-09-25 15:36:25 -07002405</p>
Robert Griesemerad711102008-09-11 17:48:20 -07002406
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05002407<p>
2408The <a href="#Blank_identifier">blank identifier</a> may appear as an
2409operand only on the left-hand side of an <a href="#Assignments">assignment</a>.
2410</p>
2411
Robert Griesemerf7ac31362009-07-10 16:06:40 -07002412<pre class="ebnf">
griesemerf2d52512017-10-25 11:26:02 -07002413Operand = Literal | OperandName | "(" Expression ")" .
Robin Eklindcac006a2014-08-30 10:27:01 -07002414Literal = BasicLit | CompositeLit | FunctionLit .
2415BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
yah01ee55dd62020-01-15 01:34:43 +00002416OperandName = identifier | QualifiedIdent .
Robert Griesemerc2d55862009-02-19 16:49:10 -08002417</pre>
Robert Griesemerad711102008-09-11 17:48:20 -07002418
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002419<h3 id="Qualified_identifiers">Qualified identifiers</h3>
Robert Griesemerad711102008-09-11 17:48:20 -07002420
Robert Griesemerc2d55862009-02-19 16:49:10 -08002421<p>
Robert Griesemer809e06b2012-06-26 11:49:19 -07002422A qualified identifier is an identifier qualified with a package name prefix.
2423Both the package name and the identifier must not be
2424<a href="#Blank_identifier">blank</a>.
Rob Pikedf3183f2009-02-26 16:37:23 -08002425</p>
Robert Griesemer337af312008-11-17 18:11:36 -08002426
Robert Griesemerf7ac31362009-07-10 16:06:40 -07002427<pre class="ebnf">
Robert Griesemer809e06b2012-06-26 11:49:19 -07002428QualifiedIdent = PackageName "." identifier .
Robert Griesemerc2d55862009-02-19 16:49:10 -08002429</pre>
Robert Griesemerad711102008-09-11 17:48:20 -07002430
Rob Pikedf3183f2009-02-26 16:37:23 -08002431<p>
Robert Griesemerda633712012-02-29 09:06:05 -08002432A qualified identifier accesses an identifier in a different package, which
2433must be <a href="#Import_declarations">imported</a>.
Robert Griesemer103c9db2012-03-01 13:57:49 -08002434The identifier must be <a href="#Exported_identifiers">exported</a> and
2435declared in the <a href="#Blocks">package block</a> of that package.
Rob Pikedf3183f2009-02-26 16:37:23 -08002436</p>
Rob Pikedf3183f2009-02-26 16:37:23 -08002437
2438<pre>
Robert Griesemer103c9db2012-03-01 13:57:49 -08002439math.Sin // denotes the Sin function in package math
Rob Pikedf3183f2009-02-26 16:37:23 -08002440</pre>
Robert Griesemerad711102008-09-11 17:48:20 -07002441
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002442<h3 id="Composite_literals">Composite literals</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002443
Rob Pikedf3183f2009-02-26 16:37:23 -08002444<p>
2445Composite literals construct values for structs, arrays, slices, and maps
2446and create a new value each time they are evaluated.
Robert Griesemerc7208752015-09-22 17:47:38 -07002447They consist of the type of the literal followed by a brace-bound list of elements.
Robert Griesemer3b022422015-09-11 16:20:23 -07002448Each element may optionally be preceded by a corresponding key.
Rob Pikedf3183f2009-02-26 16:37:23 -08002449</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002450
Robert Griesemerf7ac31362009-07-10 16:06:40 -07002451<pre class="ebnf">
Robert Griesemera12141e2010-10-22 08:58:52 -07002452CompositeLit = LiteralType LiteralValue .
Rob Pikedf3183f2009-02-26 16:37:23 -08002453LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
Robert Griesemer07cc6442010-07-29 18:13:41 -07002454 SliceType | MapType | TypeName .
Robert Griesemera12141e2010-10-22 08:58:52 -07002455LiteralValue = "{" [ ElementList [ "," ] ] "}" .
Robert Griesemer3b022422015-09-11 16:20:23 -07002456ElementList = KeyedElement { "," KeyedElement } .
2457KeyedElement = [ Key ":" ] Element .
Robert Griesemer7727dee2015-01-08 16:01:31 -08002458Key = FieldName | Expression | LiteralValue .
Rob Pike678625d2009-09-15 09:54:22 -07002459FieldName = identifier .
Robert Griesemer3b022422015-09-11 16:20:23 -07002460Element = Expression | LiteralValue .
Robert Griesemerc2d55862009-02-19 16:49:10 -08002461</pre>
Robert Griesemer0976e342008-09-03 13:37:44 -07002462
Rob Pikedf3183f2009-02-26 16:37:23 -08002463<p>
Robert Griesemerc7208752015-09-22 17:47:38 -07002464The LiteralType's underlying type must be a struct, array, slice, or map type
Robert Griesemer838cf122009-05-22 10:25:06 -07002465(the grammar enforces this constraint except when the type is given
2466as a TypeName).
Robert Griesemer3b022422015-09-11 16:20:23 -07002467The types of the elements and keys must be <a href="#Assignability">assignable</a>
Robert Griesemerc7208752015-09-22 17:47:38 -07002468to the respective field, element, and key types of the literal type;
Russ Cox7a5e97b2009-03-03 15:40:30 -08002469there is no additional conversion.
Robert Griesemer838cf122009-05-22 10:25:06 -07002470The key is interpreted as a field name for struct literals,
Robert Griesemer9c9e8112012-12-10 11:55:57 -08002471an index for array and slice literals, and a key for map literals.
Robert Griesemer838cf122009-05-22 10:25:06 -07002472For map literals, all elements must have a key. It is an error
2473to specify multiple elements with the same field name or
Robert Griesemer369d1082017-03-24 09:19:46 -07002474constant key value. For non-constant map keys, see the section on
2475<a href="#Order_of_evaluation">evaluation order</a>.
Rob Pikedf3183f2009-02-26 16:37:23 -08002476</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002477
Robert Griesemer838cf122009-05-22 10:25:06 -07002478<p>
2479For struct literals the following rules apply:
Robert Griesemercfe92112009-06-18 13:29:40 -07002480</p>
Robert Griesemer838cf122009-05-22 10:25:06 -07002481<ul>
Robert Griesemerc7208752015-09-22 17:47:38 -07002482 <li>A key must be a field name declared in the struct type.
Robert Griesemerd3b15652009-11-16 08:58:55 -08002483 </li>
Robert Griesemer369a9742012-10-31 15:07:25 -07002484 <li>An element list that does not contain any keys must
Robert Griesemer838cf122009-05-22 10:25:06 -07002485 list an element for each struct field in the
2486 order in which the fields are declared.
2487 </li>
2488 <li>If any element has a key, every element must have a key.
2489 </li>
Robert Griesemer369a9742012-10-31 15:07:25 -07002490 <li>An element list that contains keys does not need to
Robert Griesemer838cf122009-05-22 10:25:06 -07002491 have an element for each struct field. Omitted fields
2492 get the zero value for that field.
2493 </li>
2494 <li>A literal may omit the element list; such a literal evaluates
Robert Griesemer369a9742012-10-31 15:07:25 -07002495 to the zero value for its type.
Robert Griesemer838cf122009-05-22 10:25:06 -07002496 </li>
2497 <li>It is an error to specify an element for a non-exported
2498 field of a struct belonging to a different package.
2499 </li>
2500</ul>
Robert Griesemer838cf122009-05-22 10:25:06 -07002501
2502<p>
2503Given the declarations
2504</p>
Robert Griesemerc2d55862009-02-19 16:49:10 -08002505<pre>
Robert Griesemer777a96a2010-12-02 12:32:14 -08002506type Point3D struct { x, y, z float64 }
2507type Line struct { p, q Point3D }
Robert Griesemerc2d55862009-02-19 16:49:10 -08002508</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002509
Rob Pikedf3183f2009-02-26 16:37:23 -08002510<p>
2511one may write
2512</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002513
Robert Griesemerc2d55862009-02-19 16:49:10 -08002514<pre>
Robert Griesemer777a96a2010-12-02 12:32:14 -08002515origin := Point3D{} // zero value for Point3D
2516line := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x
Rob Pike37ab8382009-03-18 22:58:36 -07002517</pre>
2518
Robert Griesemercfe92112009-06-18 13:29:40 -07002519<p>
2520For array and slice literals the following rules apply:
2521</p>
Robert Griesemer838cf122009-05-22 10:25:06 -07002522<ul>
2523 <li>Each element has an associated integer index marking
2524 its position in the array.
2525 </li>
Robert Griesemera016ecf2016-10-05 15:59:09 -07002526 <li>An element with a key uses the key as its index. The
griesemerb40831b2017-08-21 15:47:51 +02002527 key must be a non-negative constant
2528 <a href="#Representability">representable</a> by
Robert Griesemera016ecf2016-10-05 15:59:09 -07002529 a value of type <code>int</code>; and if it is typed
2530 it must be of integer type.
Robert Griesemer838cf122009-05-22 10:25:06 -07002531 </li>
2532 <li>An element without a key uses the previous element's index plus one.
2533 If the first element has no key, its index is zero.
2534 </li>
2535</ul>
Robert Griesemer838cf122009-05-22 10:25:06 -07002536
Rob Pike37ab8382009-03-18 22:58:36 -07002537<p>
Robert Griesemer462a17e2013-03-22 15:36:04 -07002538<a href="#Address_operators">Taking the address</a> of a composite literal
Robert Griesemer6962c152014-10-16 15:08:49 -07002539generates a pointer to a unique <a href="#Variables">variable</a> initialized
2540with the literal's value.
Rob Pike37ab8382009-03-18 22:58:36 -07002541</p>
Robert Griesemereebb9db2019-05-09 17:35:29 -07002542
Rob Pike37ab8382009-03-18 22:58:36 -07002543<pre>
Robert Griesemer777a96a2010-12-02 12:32:14 -08002544var pointer *Point3D = &amp;Point3D{y: 1000}
Robert Griesemerc2d55862009-02-19 16:49:10 -08002545</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002546
Rob Pikedf3183f2009-02-26 16:37:23 -08002547<p>
Robert Griesemereebb9db2019-05-09 17:35:29 -07002548Note that the <a href="#The_zero_value">zero value</a> for a slice or map
2549type is not the same as an initialized but empty value of the same type.
2550Consequently, taking the address of an empty slice or map composite literal
2551does not have the same effect as allocating a new slice or map value with
2552<a href="#Allocation">new</a>.
2553</p>
2554
2555<pre>
Rob Pikecae9a9f2020-01-13 16:03:12 +11002556p1 := &amp;[]int{} // p1 points to an initialized, empty slice with value []int{} and length 0
Robert Griesemereebb9db2019-05-09 17:35:29 -07002557p2 := new([]int) // p2 points to an uninitialized slice with value nil and length 0
2558</pre>
2559
2560<p>
Robert Griesemerc7208752015-09-22 17:47:38 -07002561The length of an array literal is the length specified in the literal type.
Robert Griesemera3294712009-01-05 11:17:26 -08002562If fewer elements than the length are provided in the literal, the missing
Rob Pike8f2330d2009-02-25 16:20:44 -08002563elements are set to the zero value for the array element type.
Robert Griesemer838cf122009-05-22 10:25:06 -07002564It is an error to provide elements with index values outside the index range
2565of the array. The notation <code>...</code> specifies an array length equal
2566to the maximum element index plus one.
Rob Pikedf3183f2009-02-26 16:37:23 -08002567</p>
Robert Griesemerb90b2132008-09-19 15:49:55 -07002568
Robert Griesemerc2d55862009-02-19 16:49:10 -08002569<pre>
David Symonds72a29792011-11-29 15:47:36 -08002570buffer := [10]string{} // len(buffer) == 10
2571intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6
2572days := [...]string{"Sat", "Sun"} // len(days) == 2
Robert Griesemerc2d55862009-02-19 16:49:10 -08002573</pre>
Robert Griesemer91bbd642009-01-07 09:31:35 -08002574
Rob Pikedf3183f2009-02-26 16:37:23 -08002575<p>
2576A slice literal describes the entire underlying array literal.
Robert Griesemera6563902016-08-25 21:01:17 -07002577Thus the length and capacity of a slice literal are the maximum
Robert Griesemer838cf122009-05-22 10:25:06 -07002578element index plus one. A slice literal has the form
Rob Pikedf3183f2009-02-26 16:37:23 -08002579</p>
Robert Griesemer91bbd642009-01-07 09:31:35 -08002580
Robert Griesemerc2d55862009-02-19 16:49:10 -08002581<pre>
Robert Griesemer3c7271f2011-05-24 14:18:44 -07002582[]T{x1, x2, … xn}
Robert Griesemerc2d55862009-02-19 16:49:10 -08002583</pre>
Robert Griesemer91bbd642009-01-07 09:31:35 -08002584
Rob Pikedf3183f2009-02-26 16:37:23 -08002585<p>
Robert Griesemer2961d222013-07-31 22:25:47 -07002586and is shorthand for a slice operation applied to an array:
Rob Pikedf3183f2009-02-26 16:37:23 -08002587</p>
Robert Griesemer91bbd642009-01-07 09:31:35 -08002588
Robert Griesemerc2d55862009-02-19 16:49:10 -08002589<pre>
Russ Cox4dfe9762011-12-02 12:30:20 -05002590tmp := [n]T{x1, x2, … xn}
2591tmp[0 : n]
Robert Griesemerc2d55862009-02-19 16:49:10 -08002592</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002593
Rob Pikedf3183f2009-02-26 16:37:23 -08002594<p>
Robert Griesemera12141e2010-10-22 08:58:52 -07002595Within a composite literal of array, slice, or map type <code>T</code>,
Robert Griesemer7727dee2015-01-08 16:01:31 -08002596elements or map keys that are themselves composite literals may elide the respective
2597literal type if it is identical to the element or key type of <code>T</code>.
2598Similarly, elements or keys that are addresses of composite literals may elide
2599the <code>&amp;T</code> when the element or key type is <code>*T</code>.
Robert Griesemera12141e2010-10-22 08:58:52 -07002600</p>
2601
2602<pre>
Robert Griesemer7727dee2015-01-08 16:01:31 -08002603[...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}}
2604[][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}}
2605[][]Point{{{0, 1}, {1, 2}}} // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}}
2606map[string]Point{"orig": {0, 0}} // same as map[string]Point{"orig": Point{0, 0}}
Robert Griesemer7727dee2015-01-08 16:01:31 -08002607map[Point]string{{0, 0}: "orig"} // same as map[Point]string{Point{0, 0}: "orig"}
Robert Griesemer120cf672016-11-17 16:39:11 -08002608
2609type PPoint *Point
2610[2]*Point{{1.5, -3.5}, {}} // same as [2]*Point{&amp;Point{1.5, -3.5}, &amp;Point{}}
2611[2]PPoint{{1.5, -3.5}, {}} // same as [2]PPoint{PPoint(&amp;Point{1.5, -3.5}), PPoint(&amp;Point{})}
Robert Griesemera12141e2010-10-22 08:58:52 -07002612</pre>
2613
2614<p>
Russ Cox7a5e97b2009-03-03 15:40:30 -08002615A parsing ambiguity arises when a composite literal using the
Robert Griesemera36b5b92014-02-27 08:57:30 -08002616TypeName form of the LiteralType appears as an operand between the
2617<a href="#Keywords">keyword</a> and the opening brace of the block
2618of an "if", "for", or "switch" statement, and the composite literal
2619is not enclosed in parentheses, square brackets, or curly braces.
2620In this rare case, the opening brace of the literal is erroneously parsed
2621as the one introducing the block of statements. To resolve the ambiguity,
2622the composite literal must appear within parentheses.
Russ Cox7a5e97b2009-03-03 15:40:30 -08002623</p>
2624
2625<pre>
Robert Griesemer3c7271f2011-05-24 14:18:44 -07002626if x == (T{a,b,c}[i]) { … }
2627if (x == T{a,b,c}[i]) { … }
Russ Cox7a5e97b2009-03-03 15:40:30 -08002628</pre>
2629
Robert Griesemer838cf122009-05-22 10:25:06 -07002630<p>
2631Examples of valid array, slice, and map literals:
2632</p>
2633
2634<pre>
2635// list of prime numbers
Andrew Bonventre7974f082018-03-19 21:50:42 +00002636primes := []int{2, 3, 5, 7, 9, 2147483647}
Robert Griesemer838cf122009-05-22 10:25:06 -07002637
2638// vowels[ch] is true if ch is a vowel
Robert Griesemer130ac742009-12-10 16:43:01 -08002639vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}
Robert Griesemer838cf122009-05-22 10:25:06 -07002640
Robert Griesemerb94c0d22011-01-19 23:07:21 -05002641// the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1}
2642filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1}
Robert Griesemer838cf122009-05-22 10:25:06 -07002643
2644// frequencies in Hz for equal-tempered scale (A4 = 440Hz)
Robert Griesemerb94c0d22011-01-19 23:07:21 -05002645noteFrequency := map[string]float32{
Robert Griesemer838cf122009-05-22 10:25:06 -07002646 "C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83,
2647 "G0": 24.50, "A0": 27.50, "B0": 30.87,
2648}
2649</pre>
2650
2651
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002652<h3 id="Function_literals">Function literals</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002653
Rob Pikedf3183f2009-02-26 16:37:23 -08002654<p>
Robert Griesemer9905cec2013-03-04 13:55:35 -08002655A function literal represents an anonymous <a href="#Function_declarations">function</a>.
Rob Pikedf3183f2009-02-26 16:37:23 -08002656</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002657
Robert Griesemerf7ac31362009-07-10 16:06:40 -07002658<pre class="ebnf">
Robert Griesemer851e98f2018-02-01 14:08:45 -08002659FunctionLit = "func" Signature FunctionBody .
Robert Griesemerc2d55862009-02-19 16:49:10 -08002660</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002661
Robert Griesemerc2d55862009-02-19 16:49:10 -08002662<pre>
Robert Griesemerb94c0d22011-01-19 23:07:21 -05002663func(a, b int, z float64) bool { return a*b &lt; int(z) }
Robert Griesemerc2d55862009-02-19 16:49:10 -08002664</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002665
Rob Pikedf3183f2009-02-26 16:37:23 -08002666<p>
2667A function literal can be assigned to a variable or invoked directly.
2668</p>
Robert Griesemer7231ceb2008-09-08 15:01:04 -07002669
Robert Griesemerc2d55862009-02-19 16:49:10 -08002670<pre>
Rob Pikedf3183f2009-02-26 16:37:23 -08002671f := func(x, y int) int { return x + y }
Russ Cox9c08d652012-02-21 22:04:30 -05002672func(ch chan int) { ch &lt;- ACK }(replyChan)
Robert Griesemerc2d55862009-02-19 16:49:10 -08002673</pre>
Robert Griesemer7231ceb2008-09-08 15:01:04 -07002674
Rob Pikedf3183f2009-02-26 16:37:23 -08002675<p>
2676Function literals are <i>closures</i>: they may refer to variables
Robert Griesemerd8a764c2009-02-06 17:01:10 -08002677defined in a surrounding function. Those variables are then shared between
2678the surrounding function and the function literal, and they survive as long
Rob Pikedf3183f2009-02-26 16:37:23 -08002679as they are accessible.
2680</p>
Robert Griesemer7231ceb2008-09-08 15:01:04 -07002681
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002682
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002683<h3 id="Primary_expressions">Primary expressions</h3>
Russ Cox5958dd62009-03-04 17:19:21 -08002684
Robert Griesemer164a7bc2009-09-30 12:00:25 -07002685<p>
2686Primary expressions are the operands for unary and binary expressions.
2687</p>
2688
Robert Griesemerf7ac31362009-07-10 16:06:40 -07002689<pre class="ebnf">
Robert Griesemerc2d55862009-02-19 16:49:10 -08002690PrimaryExpr =
2691 Operand |
Robert Griesemer5eb36242009-09-16 11:05:14 -07002692 Conversion |
griesemerf2d52512017-10-25 11:26:02 -07002693 MethodExpr |
Robert Griesemerc2d55862009-02-19 16:49:10 -08002694 PrimaryExpr Selector |
2695 PrimaryExpr Index |
2696 PrimaryExpr Slice |
Russ Cox5958dd62009-03-04 17:19:21 -08002697 PrimaryExpr TypeAssertion |
Robert Griesemerccc713c2014-10-27 16:31:15 -07002698 PrimaryExpr Arguments .
Robert Griesemer57b34612008-10-10 12:45:44 -07002699
Russ Cox5958dd62009-03-04 17:19:21 -08002700Selector = "." identifier .
2701Index = "[" Expression "]" .
Robert Griesemer5583e8a2016-02-23 10:42:06 -08002702Slice = "[" [ Expression ] ":" [ Expression ] "]" |
2703 "[" [ Expression ] ":" Expression ":" Expression "]" .
Russ Cox5958dd62009-03-04 17:19:21 -08002704TypeAssertion = "." "(" Type ")" .
Robert Griesemerccc713c2014-10-27 16:31:15 -07002705Arguments = "(" [ ( ExpressionList | Type [ "," ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
Robert Griesemerc2d55862009-02-19 16:49:10 -08002706</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002707
2708
Robert Griesemerc2d55862009-02-19 16:49:10 -08002709<pre>
2710x
27112
2712(s + ".txt")
2713f(3.1415, true)
Rob Pike426335f2009-03-02 17:52:52 -08002714Point{1, 2}
Robert Griesemerc2d55862009-02-19 16:49:10 -08002715m["foo"]
2716s[i : j + 1]
2717obj.color
Robert Griesemerc2d55862009-02-19 16:49:10 -08002718f.p[i].x()
2719</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002720
2721
Russ Cox7c4f7cc2009-08-20 11:11:03 -07002722<h3 id="Selectors">Selectors</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002723
Rob Pikedf3183f2009-02-26 16:37:23 -08002724<p>
Robert Griesemer71de83b2012-06-28 12:22:24 -07002725For a <a href="#Primary_expressions">primary expression</a> <code>x</code>
2726that is not a <a href="#Package_clause">package name</a>, the
2727<i>selector expression</i>
Rob Pikedf3183f2009-02-26 16:37:23 -08002728</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07002729
Robert Griesemerc2d55862009-02-19 16:49:10 -08002730<pre>
2731x.f
2732</pre>
Robert Griesemerbbfe3122008-10-09 17:12:09 -07002733
Robert Griesemerc2d55862009-02-19 16:49:10 -08002734<p>
Robert Griesemer71de83b2012-06-28 12:22:24 -07002735denotes the field or method <code>f</code> of the value <code>x</code>
2736(or sometimes <code>*x</code>; see below).
2737The identifier <code>f</code> is called the (field or method) <i>selector</i>;
2738it must not be the <a href="#Blank_identifier">blank identifier</a>.
2739The type of the selector expression is the type of <code>f</code>.
2740If <code>x</code> is a package name, see the section on
2741<a href="#Qualified_identifiers">qualified identifiers</a>.
Rob Pikedf3183f2009-02-26 16:37:23 -08002742</p>
Robert Griesemer71de83b2012-06-28 12:22:24 -07002743
Robert Griesemerc2d55862009-02-19 16:49:10 -08002744<p>
Rob Pikedf3183f2009-02-26 16:37:23 -08002745A selector <code>f</code> may denote a field or method <code>f</code> of
2746a type <code>T</code>, or it may refer
Robert Griesemer71de83b2012-06-28 12:22:24 -07002747to a field or method <code>f</code> of a nested
Robert Griesemerf8b41232017-01-10 16:19:14 -08002748<a href="#Struct_types">embedded field</a> of <code>T</code>.
2749The number of embedded fields traversed
Rob Pikedf3183f2009-02-26 16:37:23 -08002750to reach <code>f</code> is called its <i>depth</i> in <code>T</code>.
2751The depth of a field or method <code>f</code>
2752declared in <code>T</code> is zero.
2753The depth of a field or method <code>f</code> declared in
Robert Griesemerf8b41232017-01-10 16:19:14 -08002754an embedded field <code>A</code> in <code>T</code> is the
Rob Pikedf3183f2009-02-26 16:37:23 -08002755depth of <code>f</code> in <code>A</code> plus one.
2756</p>
Robert Griesemer71de83b2012-06-28 12:22:24 -07002757
Robert Griesemerc2d55862009-02-19 16:49:10 -08002758<p>
Robert Griesemer071c91b2008-10-23 12:04:45 -07002759The following rules apply to selectors:
Rob Pikedf3183f2009-02-26 16:37:23 -08002760</p>
Robert Griesemer71de83b2012-06-28 12:22:24 -07002761
Rob Pikedf3183f2009-02-26 16:37:23 -08002762<ol>
2763<li>
2764For a value <code>x</code> of type <code>T</code> or <code>*T</code>
Robert Griesemer40818cf2014-11-11 13:19:47 -08002765where <code>T</code> is not a pointer or interface type,
Rob Pikedf3183f2009-02-26 16:37:23 -08002766<code>x.f</code> denotes the field or method at the shallowest depth
2767in <code>T</code> where there
2768is such an <code>f</code>.
Robert Griesemer103c9db2012-03-01 13:57:49 -08002769If there is not exactly <a href="#Uniqueness_of_identifiers">one <code>f</code></a>
2770with shallowest depth, the selector expression is illegal.
Rob Pikedf3183f2009-02-26 16:37:23 -08002771</li>
Robert Griesemer40818cf2014-11-11 13:19:47 -08002772
Rob Pikedf3183f2009-02-26 16:37:23 -08002773<li>
Robert Griesemer40818cf2014-11-11 13:19:47 -08002774For a value <code>x</code> of type <code>I</code> where <code>I</code>
Robert Griesemer71de83b2012-06-28 12:22:24 -07002775is an interface type, <code>x.f</code> denotes the actual method with name
Robert Griesemer40818cf2014-11-11 13:19:47 -08002776<code>f</code> of the dynamic value of <code>x</code>.
Robert Griesemer71de83b2012-06-28 12:22:24 -07002777If there is no method with name <code>f</code> in the
2778<a href="#Method_sets">method set</a> of <code>I</code>, the selector
2779expression is illegal.
Rob Pikedf3183f2009-02-26 16:37:23 -08002780</li>
Robert Griesemer40818cf2014-11-11 13:19:47 -08002781
2782<li>
Robert Griesemer9b49ac02018-01-22 16:20:01 -08002783As an exception, if the type of <code>x</code> is a <a href="#Type_definitions">defined</a>
2784pointer type and <code>(*x).f</code> is a valid selector expression denoting a field
Robert Griesemer40818cf2014-11-11 13:19:47 -08002785(but not a method), <code>x.f</code> is shorthand for <code>(*x).f</code>.
2786</li>
2787
Rob Pikedf3183f2009-02-26 16:37:23 -08002788<li>
2789In all other cases, <code>x.f</code> is illegal.
Robert Griesemer3af480372010-05-14 13:11:48 -07002790</li>
Robert Griesemer40818cf2014-11-11 13:19:47 -08002791
Robert Griesemer71de83b2012-06-28 12:22:24 -07002792<li>
Russ Cox6e156832013-03-20 16:54:07 -04002793If <code>x</code> is of pointer type and has the value
2794<code>nil</code> and <code>x.f</code> denotes a struct field,
2795assigning to or evaluating <code>x.f</code>
2796causes a <a href="#Run_time_panics">run-time panic</a>.
2797</li>
Robert Griesemer40818cf2014-11-11 13:19:47 -08002798
Russ Cox6e156832013-03-20 16:54:07 -04002799<li>
2800If <code>x</code> is of interface type and has the value
2801<code>nil</code>, <a href="#Calls">calling</a> or
2802<a href="#Method_values">evaluating</a> the method <code>x.f</code>
Robert Griesemer71de83b2012-06-28 12:22:24 -07002803causes a <a href="#Run_time_panics">run-time panic</a>.
Rob Pike9dfc6f62012-08-29 14:46:57 -07002804</li>
Rob Pikedf3183f2009-02-26 16:37:23 -08002805</ol>
Robert Griesemer71de83b2012-06-28 12:22:24 -07002806
Robert Griesemerc2d55862009-02-19 16:49:10 -08002807<p>
Rob Pikedf3183f2009-02-26 16:37:23 -08002808For example, given the declarations:
2809</p>
Robert Griesemer071c91b2008-10-23 12:04:45 -07002810
Robert Griesemerc2d55862009-02-19 16:49:10 -08002811<pre>
2812type T0 struct {
Robert Griesemer130ac742009-12-10 16:43:01 -08002813 x int
Robert Griesemerc2d55862009-02-19 16:49:10 -08002814}
Robert Griesemer071c91b2008-10-23 12:04:45 -07002815
Robert Griesemer40818cf2014-11-11 13:19:47 -08002816func (*T0) M0()
Robert Griesemer071c91b2008-10-23 12:04:45 -07002817
Robert Griesemerc2d55862009-02-19 16:49:10 -08002818type T1 struct {
Robert Griesemer130ac742009-12-10 16:43:01 -08002819 y int
Robert Griesemerc2d55862009-02-19 16:49:10 -08002820}
Robert Griesemer071c91b2008-10-23 12:04:45 -07002821
Robert Griesemer40818cf2014-11-11 13:19:47 -08002822func (T1) M1()
Robert Griesemer071c91b2008-10-23 12:04:45 -07002823
Robert Griesemerc2d55862009-02-19 16:49:10 -08002824type T2 struct {
Robert Griesemer130ac742009-12-10 16:43:01 -08002825 z int
2826 T1
2827 *T0
Robert Griesemerc2d55862009-02-19 16:49:10 -08002828}
Robert Griesemer071c91b2008-10-23 12:04:45 -07002829
Robert Griesemer40818cf2014-11-11 13:19:47 -08002830func (*T2) M2()
Robert Griesemer071c91b2008-10-23 12:04:45 -07002831
Robert Griesemer40818cf2014-11-11 13:19:47 -08002832type Q *T2
2833
2834var t T2 // with t.T0 != nil
2835var p *T2 // with p != nil and (*p).T0 != nil
2836var q Q = p
Robert Griesemerc2d55862009-02-19 16:49:10 -08002837</pre>
Robert Griesemer071c91b2008-10-23 12:04:45 -07002838
Rob Pikedf3183f2009-02-26 16:37:23 -08002839<p>
2840one may write:
2841</p>
Robert Griesemer071c91b2008-10-23 12:04:45 -07002842
Robert Griesemerc2d55862009-02-19 16:49:10 -08002843<pre>
Robert Griesemer40818cf2014-11-11 13:19:47 -08002844t.z // t.z
2845t.y // t.T1.y
Robert Griesemerf9ec9292015-05-18 11:18:58 -07002846t.x // (*t.T0).x
Robert Griesemer071c91b2008-10-23 12:04:45 -07002847
Robert Griesemer40818cf2014-11-11 13:19:47 -08002848p.z // (*p).z
2849p.y // (*p).T1.y
2850p.x // (*(*p).T0).x
2851
2852q.x // (*(*q).T0).x (*q).x is a valid field selector
2853
Robert Griesemer02d74482015-07-31 11:15:11 -07002854p.M0() // ((*p).T0).M0() M0 expects *T0 receiver
Robert Griesemer40818cf2014-11-11 13:19:47 -08002855p.M1() // ((*p).T1).M1() M1 expects T1 receiver
Robert Griesemer02d74482015-07-31 11:15:11 -07002856p.M2() // p.M2() M2 expects *T2 receiver
2857t.M2() // (&amp;t).M2() M2 expects *T2 receiver, see section on Calls
Robert Griesemer40818cf2014-11-11 13:19:47 -08002858</pre>
2859
2860<p>
2861but the following is invalid:
2862</p>
2863
2864<pre>
2865q.M0() // (*q).M0 is valid but not a field selector
Robert Griesemerc2d55862009-02-19 16:49:10 -08002866</pre>
Robert Griesemerbbfe3122008-10-09 17:12:09 -07002867
2868
Robert Griesemerf8520342014-08-28 08:53:25 -07002869<h3 id="Method_expressions">Method expressions</h3>
2870
2871<p>
2872If <code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
2873<code>T.M</code> is a function that is callable as a regular function
2874with the same arguments as <code>M</code> prefixed by an additional
2875argument that is the receiver of the method.
2876</p>
2877
2878<pre class="ebnf">
2879MethodExpr = ReceiverType "." MethodName .
griesemerf2d52512017-10-25 11:26:02 -07002880ReceiverType = Type .
Robert Griesemerf8520342014-08-28 08:53:25 -07002881</pre>
2882
2883<p>
2884Consider a struct type <code>T</code> with two methods,
2885<code>Mv</code>, whose receiver is of type <code>T</code>, and
2886<code>Mp</code>, whose receiver is of type <code>*T</code>.
2887</p>
2888
2889<pre>
2890type T struct {
2891 a int
2892}
2893func (tv T) Mv(a int) int { return 0 } // value receiver
2894func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
2895
2896var t T
2897</pre>
2898
2899<p>
2900The expression
2901</p>
2902
2903<pre>
2904T.Mv
2905</pre>
2906
2907<p>
2908yields a function equivalent to <code>Mv</code> but
2909with an explicit receiver as its first argument; it has signature
2910</p>
2911
2912<pre>
2913func(tv T, a int) int
2914</pre>
2915
2916<p>
2917That function may be called normally with an explicit receiver, so
2918these five invocations are equivalent:
2919</p>
2920
2921<pre>
2922t.Mv(7)
2923T.Mv(t, 7)
2924(T).Mv(t, 7)
2925f1 := T.Mv; f1(t, 7)
2926f2 := (T).Mv; f2(t, 7)
2927</pre>
2928
2929<p>
2930Similarly, the expression
2931</p>
2932
2933<pre>
2934(*T).Mp
2935</pre>
2936
2937<p>
2938yields a function value representing <code>Mp</code> with signature
2939</p>
2940
2941<pre>
2942func(tp *T, f float32) float32
2943</pre>
2944
2945<p>
2946For a method with a value receiver, one can derive a function
2947with an explicit pointer receiver, so
2948</p>
2949
2950<pre>
2951(*T).Mv
2952</pre>
2953
2954<p>
2955yields a function value representing <code>Mv</code> with signature
2956</p>
2957
2958<pre>
2959func(tv *T, a int) int
2960</pre>
2961
2962<p>
2963Such a function indirects through the receiver to create a value
2964to pass as the receiver to the underlying method;
2965the method does not overwrite the value whose address is passed in
2966the function call.
2967</p>
2968
2969<p>
2970The final case, a value-receiver function for a pointer-receiver method,
2971is illegal because pointer-receiver methods are not in the method set
2972of the value type.
2973</p>
2974
2975<p>
2976Function values derived from methods are called with function call syntax;
2977the receiver is provided as the first argument to the call.
2978That is, given <code>f := T.Mv</code>, <code>f</code> is invoked
2979as <code>f(t, 7)</code> not <code>t.f(7)</code>.
2980To construct a function that binds the receiver, use a
2981<a href="#Function_literals">function literal</a> or
2982<a href="#Method_values">method value</a>.
2983</p>
2984
2985<p>
2986It is legal to derive a function value from a method of an interface type.
2987The resulting function takes an explicit receiver of that interface type.
2988</p>
2989
2990<h3 id="Method_values">Method values</h3>
2991
2992<p>
2993If the expression <code>x</code> has static type <code>T</code> and
2994<code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
2995<code>x.M</code> is called a <i>method value</i>.
2996The method value <code>x.M</code> is a function value that is callable
2997with the same arguments as a method call of <code>x.M</code>.
2998The expression <code>x</code> is evaluated and saved during the evaluation of the
2999method value; the saved copy is then used as the receiver in any calls,
3000which may be executed later.
3001</p>
3002
3003<p>
3004The type <code>T</code> may be an interface or non-interface type.
3005</p>
3006
3007<p>
3008As in the discussion of <a href="#Method_expressions">method expressions</a> above,
3009consider a struct type <code>T</code> with two methods,
3010<code>Mv</code>, whose receiver is of type <code>T</code>, and
3011<code>Mp</code>, whose receiver is of type <code>*T</code>.
3012</p>
3013
3014<pre>
3015type T struct {
3016 a int
3017}
3018func (tv T) Mv(a int) int { return 0 } // value receiver
3019func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
3020
3021var t T
3022var pt *T
3023func makeT() T
3024</pre>
3025
3026<p>
3027The expression
3028</p>
3029
3030<pre>
3031t.Mv
3032</pre>
3033
3034<p>
3035yields a function value of type
3036</p>
3037
3038<pre>
3039func(int) int
3040</pre>
3041
3042<p>
3043These two invocations are equivalent:
3044</p>
3045
3046<pre>
3047t.Mv(7)
3048f := t.Mv; f(7)
3049</pre>
3050
3051<p>
3052Similarly, the expression
3053</p>
3054
3055<pre>
3056pt.Mp
3057</pre>
3058
3059<p>
3060yields a function value of type
3061</p>
3062
3063<pre>
3064func(float32) float32
3065</pre>
3066
3067<p>
3068As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver
3069using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>.
3070</p>
3071
3072<p>
3073As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver
3074using an addressable value will automatically take the address of that value: <code>t.Mp</code> is equivalent to <code>(&amp;t).Mp</code>.
3075</p>
3076
3077<pre>
3078f := t.Mv; f(7) // like t.Mv(7)
3079f := pt.Mp; f(7) // like pt.Mp(7)
3080f := pt.Mv; f(7) // like (*pt).Mv(7)
3081f := t.Mp; f(7) // like (&amp;t).Mp(7)
3082f := makeT().Mp // invalid: result of makeT() is not addressable
3083</pre>
3084
3085<p>
3086Although the examples above use non-interface types, it is also legal to create a method value
3087from a value of interface type.
3088</p>
3089
3090<pre>
3091var i interface { M(int) } = myVal
3092f := i.M; f(7) // like i.M(7)
3093</pre>
3094
3095
Robert Griesemer9c9e8112012-12-10 11:55:57 -08003096<h3 id="Index_expressions">Index expressions</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003097
Rob Pikedf3183f2009-02-26 16:37:23 -08003098<p>
Robert Griesemerbbfe3122008-10-09 17:12:09 -07003099A primary expression of the form
Rob Pikedf3183f2009-02-26 16:37:23 -08003100</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003101
Robert Griesemerc2d55862009-02-19 16:49:10 -08003102<pre>
3103a[x]
3104</pre>
Robert Griesemerbbfe3122008-10-09 17:12:09 -07003105
Rob Pike4501d342009-02-19 17:31:36 -08003106<p>
Robert Griesemer2961d222013-07-31 22:25:47 -07003107denotes the element of the array, pointer to array, slice, string or map <code>a</code> indexed by <code>x</code>.
3108The value <code>x</code> is called the <i>index</i> or <i>map key</i>, respectively.
3109The following rules apply:
Rob Pike4501d342009-02-19 17:31:36 -08003110</p>
Russ Coxeaa92e02009-06-25 14:43:55 -07003111
Robert Griesemerc2d55862009-02-19 16:49:10 -08003112<p>
Robert Griesemer39067062012-12-12 11:06:26 -08003113If <code>a</code> is not a map:
3114</p>
3115<ul>
griesemer9690d242017-08-30 15:10:12 +02003116 <li>the index <code>x</code> must be of integer type or an untyped constant</li>
3117 <li>a constant index must be non-negative and
3118 <a href="#Representability">representable</a> by a value of type <code>int</code></li>
3119 <li>a constant index that is untyped is given type <code>int</code></li>
3120 <li>the index <code>x</code> is <i>in range</i> if <code>0 &lt;= x &lt; len(a)</code>,
Robert Griesemer39067062012-12-12 11:06:26 -08003121 otherwise it is <i>out of range</i></li>
Robert Griesemer39067062012-12-12 11:06:26 -08003122</ul>
3123
3124<p>
Robert Griesemer2961d222013-07-31 22:25:47 -07003125For <code>a</code> of <a href="#Array_types">array type</a> <code>A</code>:
Rob Pike4501d342009-02-19 17:31:36 -08003126</p>
Robert Griesemerc2d55862009-02-19 16:49:10 -08003127<ul>
Robert Griesemerea7c57a2012-10-17 11:08:42 -07003128 <li>a <a href="#Constants">constant</a> index must be in range</li>
Robert Griesemer2961d222013-07-31 22:25:47 -07003129 <li>if <code>x</code> is out of range at run time,
Robert Griesemerea7c57a2012-10-17 11:08:42 -07003130 a <a href="#Run_time_panics">run-time panic</a> occurs</li>
Rob Pikedf3183f2009-02-26 16:37:23 -08003131 <li><code>a[x]</code> is the array element at index <code>x</code> and the type of
Oling Cat018e89f2013-01-24 20:46:33 +11003132 <code>a[x]</code> is the element type of <code>A</code></li>
Robert Griesemerea7c57a2012-10-17 11:08:42 -07003133</ul>
3134
3135<p>
Robert Griesemer2961d222013-07-31 22:25:47 -07003136For <code>a</code> of <a href="#Pointer_types">pointer</a> to array type:
Robert Griesemerea7c57a2012-10-17 11:08:42 -07003137</p>
3138<ul>
Robert Griesemer2961d222013-07-31 22:25:47 -07003139 <li><code>a[x]</code> is shorthand for <code>(*a)[x]</code></li>
3140</ul>
3141
3142<p>
3143For <code>a</code> of <a href="#Slice_types">slice type</a> <code>S</code>:
3144</p>
3145<ul>
3146 <li>if <code>x</code> is out of range at run time,
Robert Griesemerea7c57a2012-10-17 11:08:42 -07003147 a <a href="#Run_time_panics">run-time panic</a> occurs</li>
3148 <li><code>a[x]</code> is the slice element at index <code>x</code> and the type of
Oling Cat018e89f2013-01-24 20:46:33 +11003149 <code>a[x]</code> is the element type of <code>S</code></li>
Robert Griesemerc2d55862009-02-19 16:49:10 -08003150</ul>
Russ Coxeaa92e02009-06-25 14:43:55 -07003151
Robert Griesemerc2d55862009-02-19 16:49:10 -08003152<p>
Robert Griesemer2961d222013-07-31 22:25:47 -07003153For <code>a</code> of <a href="#String_types">string type</a>:
Russ Coxeaa92e02009-06-25 14:43:55 -07003154</p>
3155<ul>
Robert Griesemer39067062012-12-12 11:06:26 -08003156 <li>a <a href="#Constants">constant</a> index must be in range
Robert Griesemerea7c57a2012-10-17 11:08:42 -07003157 if the string <code>a</code> is also constant</li>
3158 <li>if <code>x</code> is out of range at run time,
3159 a <a href="#Run_time_panics">run-time panic</a> occurs</li>
Robert Griesemer2961d222013-07-31 22:25:47 -07003160 <li><code>a[x]</code> is the non-constant byte value at index <code>x</code> and the type of
Oling Cat018e89f2013-01-24 20:46:33 +11003161 <code>a[x]</code> is <code>byte</code></li>
Robert Griesemer3af480372010-05-14 13:11:48 -07003162 <li><code>a[x]</code> may not be assigned to</li>
Russ Coxeaa92e02009-06-25 14:43:55 -07003163</ul>
3164
3165<p>
Robert Griesemer2961d222013-07-31 22:25:47 -07003166For <code>a</code> of <a href="#Map_types">map type</a> <code>M</code>:
Rob Pike4501d342009-02-19 17:31:36 -08003167</p>
Robert Griesemerc2d55862009-02-19 16:49:10 -08003168<ul>
Robert Griesemer29f1ca52010-03-23 14:01:51 -07003169 <li><code>x</code>'s type must be
Oling Cat018e89f2013-01-24 20:46:33 +11003170 <a href="#Assignability">assignable</a>
3171 to the key type of <code>M</code></li>
Robert Griesemer29f1ca52010-03-23 14:01:51 -07003172 <li>if the map contains an entry with key <code>x</code>,
Robert Griesemer4de1d1d2018-01-03 10:33:11 -08003173 <code>a[x]</code> is the map element with key <code>x</code>
3174 and the type of <code>a[x]</code> is the element type of <code>M</code></li>
Robert Griesemer54731032011-05-12 09:15:59 -07003175 <li>if the map is <code>nil</code> or does not contain such an entry,
Oling Cat018e89f2013-01-24 20:46:33 +11003176 <code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
Robert Griesemer4de1d1d2018-01-03 10:33:11 -08003177 for the element type of <code>M</code></li>
Robert Griesemerc2d55862009-02-19 16:49:10 -08003178</ul>
Robert Griesemerbbfe3122008-10-09 17:12:09 -07003179
Robert Griesemerc2d55862009-02-19 16:49:10 -08003180<p>
Robert Griesemer29f1ca52010-03-23 14:01:51 -07003181Otherwise <code>a[x]</code> is illegal.
Rob Pikedf3183f2009-02-26 16:37:23 -08003182</p>
Robert Griesemer7abfcd92008-10-07 17:14:30 -07003183
Rob Pikedf3183f2009-02-26 16:37:23 -08003184<p>
Robert Griesemer29f1ca52010-03-23 14:01:51 -07003185An index expression on a map <code>a</code> of type <code>map[K]V</code>
Robert Griesemerc0fca132014-08-05 11:31:32 -07003186used in an <a href="#Assignments">assignment</a> or initialization of the special form
Rob Pikedf3183f2009-02-26 16:37:23 -08003187</p>
3188
3189<pre>
Robert Griesemer29f1ca52010-03-23 14:01:51 -07003190v, ok = a[x]
3191v, ok := a[x]
3192var v, ok = a[x]
Rob Pikedf3183f2009-02-26 16:37:23 -08003193</pre>
3194
3195<p>
Robert Griesemerc0fca132014-08-05 11:31:32 -07003196yields an additional untyped boolean value. The value of <code>ok</code> is
Robert Griesemer29f1ca52010-03-23 14:01:51 -07003197<code>true</code> if the key <code>x</code> is present in the map, and
Robert Griesemerc0fca132014-08-05 11:31:32 -07003198<code>false</code> otherwise.
Rob Pikedf3183f2009-02-26 16:37:23 -08003199</p>
3200
3201<p>
Robert Griesemer54731032011-05-12 09:15:59 -07003202Assigning to an element of a <code>nil</code> map causes a
3203<a href="#Run_time_panics">run-time panic</a>.
3204</p>
3205
Robert Griesemer29f1ca52010-03-23 14:01:51 -07003206
Robert Griesemere333b962013-09-11 17:18:52 -07003207<h3 id="Slice_expressions">Slice expressions</h3>
3208
3209<p>
3210Slice expressions construct a substring or slice from a string, array, pointer
3211to array, or slice. There are two variants: a simple form that specifies a low
3212and high bound, and a full form that also specifies a bound on the capacity.
3213</p>
3214
3215<h4>Simple slice expressions</h4>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003216
Rob Pikedf3183f2009-02-26 16:37:23 -08003217<p>
Russ Cox8a8445b2011-12-02 13:11:30 -05003218For a string, array, pointer to array, or slice <code>a</code>, the primary expression
Rob Pikedf3183f2009-02-26 16:37:23 -08003219</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003220
Robert Griesemerc2d55862009-02-19 16:49:10 -08003221<pre>
Robert Griesemer9e5bf272010-09-07 16:32:35 -07003222a[low : high]
Robert Griesemerc2d55862009-02-19 16:49:10 -08003223</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003224
Rob Pikedf3183f2009-02-26 16:37:23 -08003225<p>
Robert Griesemer2961d222013-07-31 22:25:47 -07003226constructs a substring or slice. The <i>indices</i> <code>low</code> and
3227<code>high</code> select which elements of operand <code>a</code> appear
3228in the result. The result has indices starting at 0 and length equal to
Robert Griesemer9e5bf272010-09-07 16:32:35 -07003229<code>high</code>&nbsp;-&nbsp;<code>low</code>.
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08003230After slicing the array <code>a</code>
3231</p>
3232
3233<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08003234a := [5]int{1, 2, 3, 4, 5}
3235s := a[1:4]
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08003236</pre>
3237
3238<p>
3239the slice <code>s</code> has type <code>[]int</code>, length 3, capacity 4, and elements
Rob Pikedf3183f2009-02-26 16:37:23 -08003240</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003241
Robert Griesemerc2d55862009-02-19 16:49:10 -08003242<pre>
3243s[0] == 2
3244s[1] == 3
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08003245s[2] == 4
Robert Griesemerc2d55862009-02-19 16:49:10 -08003246</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003247
Rob Pikedf3183f2009-02-26 16:37:23 -08003248<p>
Robert Griesemer9c9e8112012-12-10 11:55:57 -08003249For convenience, any of the indices may be omitted. A missing <code>low</code>
Robert Griesemer9e5bf272010-09-07 16:32:35 -07003250index defaults to zero; a missing <code>high</code> index defaults to the length of the
3251sliced operand:
Scott Lawrence0c1695b2010-09-07 14:30:17 -07003252</p>
3253
Robert Griesemer9e5bf272010-09-07 16:32:35 -07003254<pre>
Robert Hencke58d18e22013-10-03 12:46:02 -07003255a[2:] // same as a[2 : len(a)]
David Symonds72a29792011-11-29 15:47:36 -08003256a[:3] // same as a[0 : 3]
3257a[:] // same as a[0 : len(a)]
Robert Griesemer9e5bf272010-09-07 16:32:35 -07003258</pre>
3259
Scott Lawrence0c1695b2010-09-07 14:30:17 -07003260<p>
Robert Griesemer2961d222013-07-31 22:25:47 -07003261If <code>a</code> is a pointer to an array, <code>a[low : high]</code> is shorthand for
3262<code>(*a)[low : high]</code>.
3263</p>
3264
3265<p>
3266For arrays or strings, the indices are <i>in range</i> if
3267<code>0</code> &lt;= <code>low</code> &lt;= <code>high</code> &lt;= <code>len(a)</code>,
Robert Griesemerea7c57a2012-10-17 11:08:42 -07003268otherwise they are <i>out of range</i>.
3269For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length.
griesemerb40831b2017-08-21 15:47:51 +02003270A <a href="#Constants">constant</a> index must be non-negative and
3271<a href="#Representability">representable</a> by a value of type
Robert Griesemer6ffd2352014-03-06 17:11:13 -08003272<code>int</code>; for arrays or constant strings, constant indices must also be in range.
Robert Griesemer2961d222013-07-31 22:25:47 -07003273If both indices are constant, they must satisfy <code>low &lt;= high</code>.
3274If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
Robert Griesemer19b1d352009-09-24 19:36:48 -07003275</p>
3276
Robert Griesemerc2d55862009-02-19 16:49:10 -08003277<p>
Robert Griesemer2961d222013-07-31 22:25:47 -07003278Except for <a href="#Constants">untyped strings</a>, if the sliced operand is a string or slice,
3279the result of the slice operation is a non-constant value of the same type as the operand.
3280For untyped string operands the result is a non-constant value of type <code>string</code>.
Robert Griesemerc423e952010-09-02 10:16:31 -07003281If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>
3282and the result of the slice operation is a slice with the same element type as the array.
Rob Pikedf3183f2009-02-26 16:37:23 -08003283</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003284
Robert Griesemer2961d222013-07-31 22:25:47 -07003285<p>
3286If the sliced operand of a valid slice expression is a <code>nil</code> slice, the result
griesemer2ac43d52017-08-29 15:48:07 +02003287is a <code>nil</code> slice. Otherwise, if the result is a slice, it shares its underlying
3288array with the operand.
Rob Pike15e6ce22013-08-15 13:15:55 +10003289</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003290
Robert Griesemer1e3ffb02019-05-14 10:22:04 -07003291<pre>
3292var a [10]int
Rob Pikecae9a9f2020-01-13 16:03:12 +11003293s1 := a[3:7] // underlying array of s1 is array a; &amp;s1[2] == &amp;a[5]
3294s2 := s1[1:4] // underlying array of s2 is underlying array of s1 which is array a; &amp;s2[1] == &amp;a[5]
Robert Griesemer1e3ffb02019-05-14 10:22:04 -07003295s2[1] = 42 // s2[1] == s1[2] == a[5] == 42; they all refer to the same underlying array element
3296</pre>
3297
3298
Robert Griesemere333b962013-09-11 17:18:52 -07003299<h4>Full slice expressions</h4>
3300
3301<p>
3302For an array, pointer to array, or slice <code>a</code> (but not a string), the primary expression
3303</p>
3304
3305<pre>
3306a[low : high : max]
3307</pre>
3308
3309<p>
3310constructs a slice of the same type, and with the same length and elements as the simple slice
3311expression <code>a[low : high]</code>. Additionally, it controls the resulting slice's capacity
3312by setting it to <code>max - low</code>. Only the first index may be omitted; it defaults to 0.
3313After slicing the array <code>a</code>
3314</p>
3315
3316<pre>
3317a := [5]int{1, 2, 3, 4, 5}
3318t := a[1:3:5]
3319</pre>
3320
3321<p>
3322the slice <code>t</code> has type <code>[]int</code>, length 2, capacity 4, and elements
3323</p>
3324
3325<pre>
3326t[0] == 2
3327t[1] == 3
3328</pre>
3329
3330<p>
3331As for simple slice expressions, if <code>a</code> is a pointer to an array,
3332<code>a[low : high : max]</code> is shorthand for <code>(*a)[low : high : max]</code>.
3333If the sliced operand is an array, it must be <a href="#Address_operators">addressable</a>.
3334</p>
3335
3336<p>
3337The indices are <i>in range</i> if <code>0 &lt;= low &lt;= high &lt;= max &lt;= cap(a)</code>,
3338otherwise they are <i>out of range</i>.
griesemerb40831b2017-08-21 15:47:51 +02003339A <a href="#Constants">constant</a> index must be non-negative and
3340<a href="#Representability">representable</a> by a value of type
Robert Griesemer6ffd2352014-03-06 17:11:13 -08003341<code>int</code>; for arrays, constant indices must also be in range.
Robert Griesemere333b962013-09-11 17:18:52 -07003342If multiple indices are constant, the constants that are present must be in range relative to each
3343other.
3344If the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3345</p>
3346
Russ Cox7c4f7cc2009-08-20 11:11:03 -07003347<h3 id="Type_assertions">Type assertions</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003348
Rob Pikedf3183f2009-02-26 16:37:23 -08003349<p>
Robert Griesemere9192752009-12-01 16:15:53 -08003350For an expression <code>x</code> of <a href="#Interface_types">interface type</a>
3351and a type <code>T</code>, the primary expression
Rob Pikedf3183f2009-02-26 16:37:23 -08003352</p>
Robert Griesemer434c6052008-11-07 13:34:37 -08003353
Robert Griesemerc2d55862009-02-19 16:49:10 -08003354<pre>
3355x.(T)
3356</pre>
Robert Griesemer434c6052008-11-07 13:34:37 -08003357
Robert Griesemerc2d55862009-02-19 16:49:10 -08003358<p>
Robert Griesemere9192752009-12-01 16:15:53 -08003359asserts that <code>x</code> is not <code>nil</code>
Russ Coxb89a54e2009-05-20 18:16:04 -07003360and that the value stored in <code>x</code> is of type <code>T</code>.
Russ Cox5958dd62009-03-04 17:19:21 -08003361The notation <code>x.(T)</code> is called a <i>type assertion</i>.
Rob Pikedf3183f2009-02-26 16:37:23 -08003362</p>
3363<p>
Russ Cox5958dd62009-03-04 17:19:21 -08003364More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
Robert Griesemer7bc03712010-06-07 15:49:39 -07003365that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a>
3366to the type <code>T</code>.
Robert Griesemer48567312012-12-06 09:17:20 -08003367In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>;
3368otherwise the type assertion is invalid since it is not possible for <code>x</code>
3369to store a value of type <code>T</code>.
Russ Cox5958dd62009-03-04 17:19:21 -08003370If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
Robert Griesemer48567312012-12-06 09:17:20 -08003371of <code>x</code> implements the interface <code>T</code>.
Rob Pikedf3183f2009-02-26 16:37:23 -08003372</p>
Robert Griesemerc2d55862009-02-19 16:49:10 -08003373<p>
Russ Cox5958dd62009-03-04 17:19:21 -08003374If the type assertion holds, the value of the expression is the value
Rob Pike5bb29fb2010-03-25 17:59:59 -07003375stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false,
3376a <a href="#Run_time_panics">run-time panic</a> occurs.
3377In other words, even though the dynamic type of <code>x</code>
Robert Griesemerea7c57a2012-10-17 11:08:42 -07003378is known only at run time, the type of <code>x.(T)</code> is
Rob Pikedf3183f2009-02-26 16:37:23 -08003379known to be <code>T</code> in a correct program.
3380</p>
Robert Griesemer48567312012-12-06 09:17:20 -08003381
3382<pre>
Robert Griesemer023bb032016-10-19 09:56:53 -07003383var x interface{} = 7 // x has dynamic type int and value 7
3384i := x.(int) // i has type int and value 7
Robert Griesemer48567312012-12-06 09:17:20 -08003385
3386type I interface { m() }
Robert Griesemer023bb032016-10-19 09:56:53 -07003387
3388func f(y I) {
3389 s := y.(string) // illegal: string does not implement I (missing method m)
3390 r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader
3391
3392}
Robert Griesemer48567312012-12-06 09:17:20 -08003393</pre>
3394
Robert Griesemerc2d55862009-02-19 16:49:10 -08003395<p>
Robert Griesemerc0fca132014-08-05 11:31:32 -07003396A type assertion used in an <a href="#Assignments">assignment</a> or initialization of the special form
Rob Pikedf3183f2009-02-26 16:37:23 -08003397</p>
Robert Griesemer434c6052008-11-07 13:34:37 -08003398
Robert Griesemerc2d55862009-02-19 16:49:10 -08003399<pre>
3400v, ok = x.(T)
3401v, ok := x.(T)
Rob Piked5537072009-08-22 00:04:04 -07003402var v, ok = x.(T)
Robert Griesemer507051d2016-08-24 11:33:55 -07003403var v, ok T1 = x.(T)
Robert Griesemerc2d55862009-02-19 16:49:10 -08003404</pre>
Robert Griesemer434c6052008-11-07 13:34:37 -08003405
Robert Griesemerc2d55862009-02-19 16:49:10 -08003406<p>
Robert Griesemerc0fca132014-08-05 11:31:32 -07003407yields an additional untyped boolean value. The value of <code>ok</code> is <code>true</code>
3408if the assertion holds. Otherwise it is <code>false</code> and the value of <code>v</code> is
3409the <a href="#The_zero_value">zero value</a> for type <code>T</code>.
Robert Griesemer1e38ecd2018-10-23 14:54:59 -07003410No <a href="#Run_time_panics">run-time panic</a> occurs in this case.
Rob Pikedf3183f2009-02-26 16:37:23 -08003411</p>
Robert Griesemer7a4ed4f2008-09-03 15:15:51 -07003412
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003413
Russ Cox7c4f7cc2009-08-20 11:11:03 -07003414<h3 id="Calls">Calls</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003415
Robert Griesemerc2d55862009-02-19 16:49:10 -08003416<p>
Rob Pike96750f12009-02-27 16:47:48 -08003417Given an expression <code>f</code> of function type
3418<code>F</code>,
Rob Pikedf3183f2009-02-26 16:37:23 -08003419</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003420
Robert Griesemerc2d55862009-02-19 16:49:10 -08003421<pre>
Robert Griesemer3c7271f2011-05-24 14:18:44 -07003422f(a1, a2, … an)
Robert Griesemerc2d55862009-02-19 16:49:10 -08003423</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003424
Robert Griesemerc2d55862009-02-19 16:49:10 -08003425<p>
Robert Griesemer3c7271f2011-05-24 14:18:44 -07003426calls <code>f</code> with arguments <code>a1, a2, … an</code>.
Rob Pike4fe41922009-11-07 22:00:59 -08003427Except for one special case, arguments must be single-valued expressions
Robert Griesemer440cc952010-06-07 17:40:21 -07003428<a href="#Assignability">assignable</a> to the parameter types of
Rob Pikedf3183f2009-02-26 16:37:23 -08003429<code>F</code> and are evaluated before the function is called.
3430The type of the expression is the result type
3431of <code>F</code>.
3432A method invocation is similar but the method itself
3433is specified as a selector upon a value of the receiver type for
3434the method.
3435</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003436
Robert Griesemerc2d55862009-02-19 16:49:10 -08003437<pre>
David Symonds72a29792011-11-29 15:47:36 -08003438math.Atan2(x, y) // function call
Robert Griesemer130ac742009-12-10 16:43:01 -08003439var pt *Point
Robert Griesemerccc713c2014-10-27 16:31:15 -07003440pt.Scale(3.5) // method call with receiver pt
Robert Griesemerc2d55862009-02-19 16:49:10 -08003441</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003442
Rob Pikedf3183f2009-02-26 16:37:23 -08003443<p>
Rob Pike633a2ce2012-01-23 08:40:13 -08003444In a function call, the function value and arguments are evaluated in
3445<a href="#Order_of_evaluation">the usual order</a>.
3446After they are evaluated, the parameters of the call are passed by value to the function
3447and the called function begins execution.
3448The return parameters of the function are passed by value
3449back to the calling function when the function returns.
3450</p>
3451
3452<p>
Hong Ruiqi8374e672012-04-05 22:37:07 +10003453Calling a <code>nil</code> function value
Rob Pike633a2ce2012-01-23 08:40:13 -08003454causes a <a href="#Run_time_panics">run-time panic</a>.
3455</p>
3456
3457<p>
Russ Cox1b3083e2013-02-09 14:46:55 -05003458As a special case, if the return values of a function or method
Robert Griesemer440cc952010-06-07 17:40:21 -07003459<code>g</code> are equal in number and individually
3460assignable to the parameters of another function or method
Rob Pike4fe41922009-11-07 22:00:59 -08003461<code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code>
3462will invoke <code>f</code> after binding the return values of
3463<code>g</code> to the parameters of <code>f</code> in order. The call
Russ Cox1b3083e2013-02-09 14:46:55 -05003464of <code>f</code> must contain no parameters other than the call of <code>g</code>,
3465and <code>g</code> must have at least one return value.
Rob Pike4fe41922009-11-07 22:00:59 -08003466If <code>f</code> has a final <code>...</code> parameter, it is
3467assigned the return values of <code>g</code> that remain after
3468assignment of regular parameters.
3469</p>
3470
3471<pre>
3472func Split(s string, pos int) (string, string) {
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08003473 return s[0:pos], s[pos:]
Rob Pike4fe41922009-11-07 22:00:59 -08003474}
3475
3476func Join(s, t string) string {
3477 return s + t
3478}
3479
3480if Join(Split(value, len(value)/2)) != value {
Robert Griesemer7fc4e372011-02-01 12:51:10 -08003481 log.Panic("test fails")
Rob Pike4fe41922009-11-07 22:00:59 -08003482}
3483</pre>
3484
3485<p>
Robert Griesemer2a838d62011-02-08 13:31:01 -08003486A method call <code>x.m()</code> is valid if the <a href="#Method_sets">method set</a>
3487of (the type of) <code>x</code> contains <code>m</code> and the
Robert Griesemer63f01492010-05-28 14:17:30 -07003488argument list can be assigned to the parameter list of <code>m</code>.
Rob Pike678625d2009-09-15 09:54:22 -07003489If <code>x</code> is <a href="#Address_operators">addressable</a> and <code>&amp;x</code>'s method
Robert Griesemer56809d02009-05-20 11:02:48 -07003490set contains <code>m</code>, <code>x.m()</code> is shorthand
3491for <code>(&amp;x).m()</code>:
Rob Pikedf3183f2009-02-26 16:37:23 -08003492</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003493
Robert Griesemerc2d55862009-02-19 16:49:10 -08003494<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08003495var p Point
Rob Pikedf3183f2009-02-26 16:37:23 -08003496p.Scale(3.5)
Robert Griesemerc2d55862009-02-19 16:49:10 -08003497</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003498
Robert Griesemerc2d55862009-02-19 16:49:10 -08003499<p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003500There is no distinct method type and there are no method literals.
Rob Pikedf3183f2009-02-26 16:37:23 -08003501</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003502
Russ Cox7c4f7cc2009-08-20 11:11:03 -07003503<h3 id="Passing_arguments_to_..._parameters">Passing arguments to <code>...</code> parameters</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003504
Robert Griesemerc2d55862009-02-19 16:49:10 -08003505<p>
Robert Griesemera7662772014-03-06 10:35:05 -08003506If <code>f</code> is <a href="#Function_types">variadic</a> with a final
3507parameter <code>p</code> of type <code>...T</code>, then within <code>f</code>
3508the type of <code>p</code> is equivalent to type <code>[]T</code>.
3509If <code>f</code> is invoked with no actual arguments for <code>p</code>,
3510the value passed to <code>p</code> is <code>nil</code>.
3511Otherwise, the value passed is a new slice
3512of type <code>[]T</code> with a new underlying array whose successive elements
3513are the actual arguments, which all must be <a href="#Assignability">assignable</a>
3514to <code>T</code>. The length and capacity of the slice is therefore
3515the number of arguments bound to <code>p</code> and may differ for each
3516call site.
Rob Pikeb81065d2010-01-27 13:14:40 -08003517</p>
Robert Griesemer69e26bf2008-11-04 16:46:45 -08003518
Rob Pikedf3183f2009-02-26 16:37:23 -08003519<p>
Robert Griesemera7662772014-03-06 10:35:05 -08003520Given the function and calls
Rob Pikeb81065d2010-01-27 13:14:40 -08003521</p>
3522<pre>
Robert Griesemer3c7271f2011-05-24 14:18:44 -07003523func Greeting(prefix string, who ...string)
Robert Griesemera7662772014-03-06 10:35:05 -08003524Greeting("nobody")
Rob Pikeb81065d2010-01-27 13:14:40 -08003525Greeting("hello:", "Joe", "Anna", "Eileen")
3526</pre>
3527
3528<p>
Robert Griesemerac771a82010-09-24 14:08:28 -07003529within <code>Greeting</code>, <code>who</code> will have the value
Robert Griesemera7662772014-03-06 10:35:05 -08003530<code>nil</code> in the first call, and
3531<code>[]string{"Joe", "Anna", "Eileen"}</code> in the second.
Rob Pikeb81065d2010-01-27 13:14:40 -08003532</p>
3533
Robert Griesemerac771a82010-09-24 14:08:28 -07003534<p>
Robert Griesemer1024b252019-03-13 09:48:33 -07003535If the final argument is assignable to a slice type <code>[]T</code>, it is
Robert Griesemer904adfd2010-10-27 10:44:31 -07003536passed unchanged as the value for a <code>...T</code> parameter if the argument
3537is followed by <code>...</code>. In this case no new slice is created.
Robert Griesemerac771a82010-09-24 14:08:28 -07003538</p>
Rob Pikeb81065d2010-01-27 13:14:40 -08003539
3540<p>
Robert Griesemerac771a82010-09-24 14:08:28 -07003541Given the slice <code>s</code> and call
Rob Pikeb81065d2010-01-27 13:14:40 -08003542</p>
Robert Griesemer69e26bf2008-11-04 16:46:45 -08003543
Robert Griesemerac771a82010-09-24 14:08:28 -07003544<pre>
3545s := []string{"James", "Jasmine"}
3546Greeting("goodbye:", s...)
3547</pre>
3548
3549<p>
3550within <code>Greeting</code>, <code>who</code> will have the same value as <code>s</code>
3551with the same underlying array.
3552</p>
3553
3554
Russ Cox7c4f7cc2009-08-20 11:11:03 -07003555<h3 id="Operators">Operators</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003556
Rob Pikedf3183f2009-02-26 16:37:23 -08003557<p>
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003558Operators combine operands into expressions.
Rob Pikedf3183f2009-02-26 16:37:23 -08003559</p>
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003560
Robert Griesemerf7ac31362009-07-10 16:06:40 -07003561<pre class="ebnf">
Matthew Dempskyabb818b2015-04-20 17:17:24 -07003562Expression = UnaryExpr | Expression binary_op Expression .
Rob Pikedf3183f2009-02-26 16:37:23 -08003563UnaryExpr = PrimaryExpr | unary_op UnaryExpr .
Robert Griesemer57b34612008-10-10 12:45:44 -07003564
Robert Griesemerb50ed022011-02-01 12:02:49 -08003565binary_op = "||" | "&amp;&amp;" | rel_op | add_op | mul_op .
Rob Pikedf3183f2009-02-26 16:37:23 -08003566rel_op = "==" | "!=" | "&lt;" | "&lt;=" | ">" | ">=" .
3567add_op = "+" | "-" | "|" | "^" .
Robert Griesemer4ed666e2009-08-27 16:45:42 -07003568mul_op = "*" | "/" | "%" | "&lt;&lt;" | "&gt;&gt;" | "&amp;" | "&amp;^" .
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003569
Rob Pikedf3183f2009-02-26 16:37:23 -08003570unary_op = "+" | "-" | "!" | "^" | "*" | "&amp;" | "&lt;-" .
Robert Griesemerc2d55862009-02-19 16:49:10 -08003571</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003572
Robert Griesemerc2d55862009-02-19 16:49:10 -08003573<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -07003574Comparisons are discussed <a href="#Comparison_operators">elsewhere</a>.
Robert Griesemer7bc03712010-06-07 15:49:39 -07003575For other binary operators, the operand types must be <a href="#Type_identity">identical</a>
Robert Griesemer32d12782011-05-23 14:12:42 -07003576unless the operation involves shifts or untyped <a href="#Constants">constants</a>.
Robert Griesemer19b1d352009-09-24 19:36:48 -07003577For operations involving constants only, see the section on
3578<a href="#Constant_expressions">constant expressions</a>.
Rob Pike4501d342009-02-19 17:31:36 -08003579</p>
Robert Griesemerc8e18762008-09-12 12:26:22 -07003580
Rob Pike83cbca52009-08-21 14:18:08 -07003581<p>
Robert Griesemer32d12782011-05-23 14:12:42 -07003582Except for shift operations, if one operand is an untyped <a href="#Constants">constant</a>
Robert Griesemer26d22602018-10-02 15:55:38 -07003583and the other operand is not, the constant is implicitly <a href="#Conversions">converted</a>
Robert Griesemer19b1d352009-09-24 19:36:48 -07003584to the type of the other operand.
Rob Pike83cbca52009-08-21 14:18:08 -07003585</p>
Robert Griesemer7539c852009-07-31 18:05:07 -07003586
Rob Pike83cbca52009-08-21 14:18:08 -07003587<p>
Robert Griesemera10b4cf2019-02-05 14:33:24 -08003588The right operand in a shift expression must have integer type
griesemerb40831b2017-08-21 15:47:51 +02003589or be an untyped constant <a href="#Representability">representable</a> by a
3590value of type <code>uint</code>.
Robert Griesemer32d12782011-05-23 14:12:42 -07003591If the left operand of a non-constant shift expression is an untyped constant,
Robert Griesemer26d22602018-10-02 15:55:38 -07003592it is first implicitly converted to the type it would assume if the shift expression were
Robert Griesemer58e21dd2013-03-15 13:55:50 -07003593replaced by its left operand alone.
Rob Pike83cbca52009-08-21 14:18:08 -07003594</p>
Robert Griesemera6b546f2008-10-20 11:46:40 -07003595
Rob Pike83cbca52009-08-21 14:18:08 -07003596<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08003597var s uint = 33
griesemer9690d242017-08-30 15:10:12 +02003598var i = 1&lt;&lt;s // 1 has type int
3599var j int32 = 1&lt;&lt;s // 1 has type int32; j == 0
3600var k = uint64(1&lt;&lt;s) // 1 has type uint64; k == 1&lt;&lt;33
3601var m int = 1.0&lt;&lt;s // 1.0 has type int; m == 0 if ints are 32bits in size
3602var n = 1.0&lt;&lt;s == j // 1.0 has type int32; n == true
3603var o = 1&lt;&lt;s == 2&lt;&lt;s // 1 and 2 have type int; o == true if ints are 32bits in size
3604var p = 1&lt;&lt;s == 1&lt;&lt;33 // illegal if ints are 32bits in size: 1 has type int, but 1&lt;&lt;33 overflows int
3605var u = 1.0&lt;&lt;s // illegal: 1.0 has type float64, cannot shift
3606var u1 = 1.0&lt;&lt;s != 0 // illegal: 1.0 has type float64, cannot shift
3607var u2 = 1&lt;&lt;s != 1.0 // illegal: 1 has type float64, cannot shift
3608var v float32 = 1&lt;&lt;s // illegal: 1 has type float32, cannot shift
3609var w int64 = 1.0&lt;&lt;33 // 1.0&lt;&lt;33 is a constant shift expression
3610var x = a[1.0&lt;&lt;s] // 1.0 has type int; x == a[0] if ints are 32bits in size
3611var a = make([]byte, 1.0&lt;&lt;s) // 1.0 has type int; len(a) == 0 if ints are 32bits in size
Rob Pike83cbca52009-08-21 14:18:08 -07003612</pre>
Robert Griesemer18b05c12009-01-26 09:34:19 -08003613
Robert Griesemer3dd3ab42015-08-04 15:04:39 -07003614
3615<h4 id="Operator_precedence">Operator precedence</h4>
Robert Griesemerc2d55862009-02-19 16:49:10 -08003616<p>
Russ Coxec9b0422009-07-09 16:44:13 -07003617Unary operators have the highest precedence.
3618As the <code>++</code> and <code>--</code> operators form
Rob Pikedf3183f2009-02-26 16:37:23 -08003619statements, not expressions, they fall
Russ Coxec9b0422009-07-09 16:44:13 -07003620outside the operator hierarchy.
Rob Pikedf3183f2009-02-26 16:37:23 -08003621As a consequence, statement <code>*p++</code> is the same as <code>(*p)++</code>.
3622<p>
Robert Griesemerb50ed022011-02-01 12:02:49 -08003623There are five precedence levels for binary operators.
Rob Pikedf3183f2009-02-26 16:37:23 -08003624Multiplication operators bind strongest, followed by addition
Russ Cox1b4e37a2012-09-12 12:05:24 -04003625operators, comparison operators, <code>&amp;&amp;</code> (logical AND),
3626and finally <code>||</code> (logical OR):
Rob Pikedf3183f2009-02-26 16:37:23 -08003627</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003628
Rob Pikeff70f092009-02-20 13:36:14 -08003629<pre class="grammar">
Robert Griesemerc2d55862009-02-19 16:49:10 -08003630Precedence Operator
Robert Griesemerb50ed022011-02-01 12:02:49 -08003631 5 * / % &lt;&lt; &gt;&gt; &amp; &amp;^
3632 4 + - | ^
Robert Griesemera1368a62011-02-22 15:31:57 -08003633 3 == != &lt; &lt;= &gt; &gt;=
Robert Griesemerc2d55862009-02-19 16:49:10 -08003634 2 &amp;&amp;
3635 1 ||
3636</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003637
Robert Griesemerc2d55862009-02-19 16:49:10 -08003638<p>
Rob Pikedf3183f2009-02-26 16:37:23 -08003639Binary operators of the same precedence associate from left to right.
Robert Griesemerd36d1912009-09-18 11:58:35 -07003640For instance, <code>x / y * z</code> is the same as <code>(x / y) * z</code>.
Rob Pikedf3183f2009-02-26 16:37:23 -08003641</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003642
Robert Griesemerc2d55862009-02-19 16:49:10 -08003643<pre>
3644+x
364523 + 3*x[i]
3646x &lt;= f()
Robert Griesemer4ed666e2009-08-27 16:45:42 -07003647^a &gt;&gt; b
Robert Griesemerc2d55862009-02-19 16:49:10 -08003648f() || g()
Russ Cox9c08d652012-02-21 22:04:30 -05003649x == y+1 &amp;&amp; &lt;-chanPtr &gt; 0
Robert Griesemerc2d55862009-02-19 16:49:10 -08003650</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003651
3652
Russ Cox7c4f7cc2009-08-20 11:11:03 -07003653<h3 id="Arithmetic_operators">Arithmetic operators</h3>
Robert Griesemerc2d55862009-02-19 16:49:10 -08003654<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -07003655Arithmetic operators apply to numeric values and yield a result of the same
Rob Pikedf3183f2009-02-26 16:37:23 -08003656type as the first operand. The four standard arithmetic operators (<code>+</code>,
Robert Griesemer3dd3ab42015-08-04 15:04:39 -07003657<code>-</code>, <code>*</code>, <code>/</code>) apply to integer,
3658floating-point, and complex types; <code>+</code> also applies to strings.
3659The bitwise logical and shift operators apply to integers only.
Rob Pikedf3183f2009-02-26 16:37:23 -08003660</p>
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003661
Rob Pikeff70f092009-02-20 13:36:14 -08003662<pre class="grammar">
Rob Pike72970872010-03-04 12:35:16 -08003663+ sum integers, floats, complex values, strings
3664- difference integers, floats, complex values
3665* product integers, floats, complex values
3666/ quotient integers, floats, complex values
Rob Pike307ec212009-03-12 15:53:56 -07003667% remainder integers
Robert Griesemerc2d55862009-02-19 16:49:10 -08003668
Russ Cox1b4e37a2012-09-12 12:05:24 -04003669&amp; bitwise AND integers
3670| bitwise OR integers
3671^ bitwise XOR integers
3672&amp;^ bit clear (AND NOT) integers
Robert Griesemerc2d55862009-02-19 16:49:10 -08003673
Robert Griesemer4ed666e2009-08-27 16:45:42 -07003674&lt;&lt; left shift integer &lt;&lt; unsigned integer
3675&gt;&gt; right shift integer &gt;&gt; unsigned integer
Robert Griesemerc2d55862009-02-19 16:49:10 -08003676</pre>
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003677
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003678
Robert Griesemer3dd3ab42015-08-04 15:04:39 -07003679<h4 id="Integer_operators">Integer operators</h4>
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003680
Robert Griesemerc2d55862009-02-19 16:49:10 -08003681<p>
Robert Griesemerbb7eb402011-05-02 17:23:18 -07003682For two integer values <code>x</code> and <code>y</code>, the integer quotient
3683<code>q = x / y</code> and remainder <code>r = x % y</code> satisfy the following
3684relationships:
Rob Pikedf3183f2009-02-26 16:37:23 -08003685</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003686
Robert Griesemerc2d55862009-02-19 16:49:10 -08003687<pre>
Robert Griesemerbb7eb402011-05-02 17:23:18 -07003688x = q*y + r and |r| &lt; |y|
Robert Griesemerc2d55862009-02-19 16:49:10 -08003689</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003690
Rob Pikedf3183f2009-02-26 16:37:23 -08003691<p>
Robert Griesemerbb7eb402011-05-02 17:23:18 -07003692with <code>x / y</code> truncated towards zero
Suriyaa Sundararuban1041ac82018-06-13 07:06:04 +00003693(<a href="https://en.wikipedia.org/wiki/Modulo_operation">"truncated division"</a>).
Rob Pikedf3183f2009-02-26 16:37:23 -08003694</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003695
Robert Griesemerc2d55862009-02-19 16:49:10 -08003696<pre>
3697 x y x / y x % y
3698 5 3 1 2
3699-5 3 -1 -2
3700 5 -3 -1 2
3701-5 -3 1 -2
3702</pre>
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003703
Rob Pikedf3183f2009-02-26 16:37:23 -08003704<p>
Robert Griesemer18d527b2018-01-16 21:30:46 -08003705The one exception to this rule is that if the dividend <code>x</code> is
3706the most negative value for the int type of <code>x</code>, the quotient
3707<code>q = x / -1</code> is equal to <code>x</code> (and <code>r = 0</code>)
3708due to two's-complement <a href="#Integer_overflow">integer overflow</a>:
Robert Griesemerbb7eb402011-05-02 17:23:18 -07003709</p>
3710
3711<pre>
3712 x, q
3713int8 -128
3714int16 -32768
3715int32 -2147483648
3716int64 -9223372036854775808
3717</pre>
3718
3719<p>
Robert Griesemerddddd392012-10-19 10:12:09 -07003720If the divisor is a <a href="#Constants">constant</a>, it must not be zero.
3721If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
Matthew Dempsky80a87a92013-01-06 16:56:06 -08003722If the dividend is non-negative and the divisor is a constant power of 2,
Rob Pikef3a33bc2009-09-14 17:39:17 -07003723the division may be replaced by a right shift, and computing the remainder may
Russ Cox1b4e37a2012-09-12 12:05:24 -04003724be replaced by a bitwise AND operation:
Rob Pikedf3183f2009-02-26 16:37:23 -08003725</p>
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003726
Robert Griesemerc2d55862009-02-19 16:49:10 -08003727<pre>
Robert Griesemer4ed666e2009-08-27 16:45:42 -07003728 x x / 4 x % 4 x &gt;&gt; 2 x &amp; 3
Robert Griesemerc2d55862009-02-19 16:49:10 -08003729 11 2 3 2 3
3730-11 -2 -3 -3 1
3731</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003732
Rob Pikedf3183f2009-02-26 16:37:23 -08003733<p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003734The shift operators shift the left operand by the shift count specified by the
Robert Griesemer6fcc2d82019-09-04 08:42:12 -07003735right operand, which must be non-negative. If the shift count is negative at run time,
Robert Griesemera10b4cf2019-02-05 14:33:24 -08003736a <a href="#Run_time_panics">run-time panic</a> occurs.
3737The shift operators implement arithmetic shifts if the left operand is a signed
Robert Griesemer32d12782011-05-23 14:12:42 -07003738integer and logical shifts if it is an unsigned integer.
3739There is no upper limit on the shift count. Shifts behave
Rob Pikedf3183f2009-02-26 16:37:23 -08003740as if the left operand is shifted <code>n</code> times by 1 for a shift
3741count of <code>n</code>.
Robert Griesemer4ed666e2009-08-27 16:45:42 -07003742As a result, <code>x &lt;&lt; 1</code> is the same as <code>x*2</code>
3743and <code>x &gt;&gt; 1</code> is the same as
Robert Griesemere9192752009-12-01 16:15:53 -08003744<code>x/2</code> but truncated towards negative infinity.
Rob Pikedf3183f2009-02-26 16:37:23 -08003745</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003746
Rob Pikedf3183f2009-02-26 16:37:23 -08003747<p>
3748For integer operands, the unary operators
3749<code>+</code>, <code>-</code>, and <code>^</code> are defined as
Robert Griesemer9dfb2ea2008-12-12 10:30:10 -08003750follows:
Rob Pikedf3183f2009-02-26 16:37:23 -08003751</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003752
Rob Pikeff70f092009-02-20 13:36:14 -08003753<pre class="grammar">
Robert Griesemerc2d55862009-02-19 16:49:10 -08003754+x is 0 + x
3755-x negation is 0 - x
Russ Coxd83dc4f2009-05-29 16:04:16 -07003756^x bitwise complement is m ^ x with m = "all bits set to 1" for unsigned x
3757 and m = -1 for signed x
Robert Griesemerc2d55862009-02-19 16:49:10 -08003758</pre>
Robert Griesemer9dfb2ea2008-12-12 10:30:10 -08003759
3760
Robert Griesemer3dd3ab42015-08-04 15:04:39 -07003761<h4 id="Integer_overflow">Integer overflow</h4>
Robert Griesemer9dfb2ea2008-12-12 10:30:10 -08003762
Rob Pikedf3183f2009-02-26 16:37:23 -08003763<p>
3764For unsigned integer values, the operations <code>+</code>,
3765<code>-</code>, <code>*</code>, and <code>&lt;&lt;</code> are
3766computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of
Robert Griesemer462a17e2013-03-22 15:36:04 -07003767the <a href="#Numeric_types">unsigned integer</a>'s type.
3768Loosely speaking, these unsigned integer operations
Robert Griesemer8c916a22018-01-09 12:42:28 -08003769discard high bits upon overflow, and programs may rely on "wrap around".
Rob Pikedf3183f2009-02-26 16:37:23 -08003770</p>
Robert Griesemerc2d55862009-02-19 16:49:10 -08003771<p>
Rob Pikedf3183f2009-02-26 16:37:23 -08003772For signed integers, the operations <code>+</code>,
Robert Griesemer18d527b2018-01-16 21:30:46 -08003773<code>-</code>, <code>*</code>, <code>/</code>, and <code>&lt;&lt;</code> may legally
Robert Griesemer9dfb2ea2008-12-12 10:30:10 -08003774overflow and the resulting value exists and is deterministically defined
3775by the signed integer representation, the operation, and its operands.
Russ Coxb7ba5232018-11-13 10:23:01 -05003776Overflow does not cause a <a href="#Run_time_panics">run-time panic</a>.
Robert Griesemer18d527b2018-01-16 21:30:46 -08003777A compiler may not optimize code under the assumption that overflow does
Rob Pikedf3183f2009-02-26 16:37:23 -08003778not occur. For instance, it may not assume that <code>x &lt; x + 1</code> is always true.
3779</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003780
3781
Robert Griesemer3dd3ab42015-08-04 15:04:39 -07003782<h4 id="Floating_point_operators">Floating-point operators</h4>
3783
3784<p>
3785For floating-point and complex numbers,
3786<code>+x</code> is the same as <code>x</code>,
3787while <code>-x</code> is the negation of <code>x</code>.
3788The result of a floating-point or complex division by zero is not specified beyond the
3789IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a>
3790occurs is implementation-specific.
3791</p>
3792
Robert Griesemer94b60112017-04-11 13:39:24 -07003793<p>
3794An implementation may combine multiple floating-point operations into a single
3795fused operation, possibly across statements, and produce a result that differs
3796from the value obtained by executing and rounding the instructions individually.
Robert Griesemer26d22602018-10-02 15:55:38 -07003797An explicit floating-point type <a href="#Conversions">conversion</a> rounds to
Robert Griesemer94b60112017-04-11 13:39:24 -07003798the precision of the target type, preventing fusion that would discard that rounding.
3799</p>
3800
3801<p>
3802For instance, some architectures provide a "fused multiply and add" (FMA) instruction
3803that computes <code>x*y + z</code> without rounding the intermediate result <code>x*y</code>.
3804These examples show when a Go implementation can use that instruction:
3805</p>
3806
3807<pre>
3808// FMA allowed for computing r, because x*y is not explicitly rounded:
3809r = x*y + z
3810r = z; r += x*y
3811t = x*y; r = t + z
3812*p = x*y; r = *p + z
3813r = x*y + float64(z)
3814
3815// FMA disallowed for computing r, because it would omit rounding of x*y:
3816r = float64(x*y) + z
3817r = z; r += float64(x*y)
3818t = float64(x*y); r = t + z
3819</pre>
Robert Griesemer3dd3ab42015-08-04 15:04:39 -07003820
3821<h4 id="String_concatenation">String concatenation</h4>
3822
3823<p>
3824Strings can be concatenated using the <code>+</code> operator
3825or the <code>+=</code> assignment operator:
3826</p>
3827
3828<pre>
3829s := "hi" + string(c)
3830s += " and good bye"
3831</pre>
3832
3833<p>
3834String addition creates a new string by concatenating the operands.
3835</p>
3836
3837
Russ Cox7c4f7cc2009-08-20 11:11:03 -07003838<h3 id="Comparison_operators">Comparison operators</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003839
Rob Pike5af7de32009-02-24 15:17:59 -08003840<p>
Robert Griesemerc729ed62013-03-11 09:16:29 -07003841Comparison operators compare two operands and yield an untyped boolean value.
Rob Pike5af7de32009-02-24 15:17:59 -08003842</p>
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003843
Rob Pikeff70f092009-02-20 13:36:14 -08003844<pre class="grammar">
Robert Griesemerc2d55862009-02-19 16:49:10 -08003845== equal
3846!= not equal
Anthony Martin0122a662011-02-08 14:51:15 -08003847&lt; less
3848&lt;= less or equal
Russ Cox83f648c2011-12-12 22:21:46 -05003849&gt; greater
3850&gt;= greater or equal
Robert Griesemerc2d55862009-02-19 16:49:10 -08003851</pre>
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003852
Rob Pike5af7de32009-02-24 15:17:59 -08003853<p>
Russ Cox83f648c2011-12-12 22:21:46 -05003854In any comparison, the first operand
Robert Griesemer440cc952010-06-07 17:40:21 -07003855must be <a href="#Assignability">assignable</a>
3856to the type of the second operand, or vice versa.
Rob Pike5af7de32009-02-24 15:17:59 -08003857</p>
Robert Griesemer7bc03712010-06-07 15:49:39 -07003858<p>
Russ Cox83f648c2011-12-12 22:21:46 -05003859The equality operators <code>==</code> and <code>!=</code> apply
3860to operands that are <i>comparable</i>.
3861The ordering operators <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code>
3862apply to operands that are <i>ordered</i>.
3863These terms and the result of the comparisons are defined as follows:
Rob Pike5af7de32009-02-24 15:17:59 -08003864</p>
Robert Griesemer1d282a82010-06-03 16:55:50 -07003865
3866<ul>
3867 <li>
Russ Cox83f648c2011-12-12 22:21:46 -05003868 Boolean values are comparable.
3869 Two boolean values are equal if they are either both
3870 <code>true</code> or both <code>false</code>.
Robert Griesemer1d282a82010-06-03 16:55:50 -07003871 </li>
Russ Cox83f648c2011-12-12 22:21:46 -05003872
Robert Griesemer1d282a82010-06-03 16:55:50 -07003873 <li>
Russ Cox83f648c2011-12-12 22:21:46 -05003874 Integer values are comparable and ordered, in the usual way.
Robert Griesemer1d282a82010-06-03 16:55:50 -07003875 </li>
Hong Ruiqi8374e672012-04-05 22:37:07 +10003876
Robert Griesemer1d282a82010-06-03 16:55:50 -07003877 <li>
Robert Griesemer94b60112017-04-11 13:39:24 -07003878 Floating-point values are comparable and ordered,
Russ Cox83f648c2011-12-12 22:21:46 -05003879 as defined by the IEEE-754 standard.
3880 </li>
Hong Ruiqi8374e672012-04-05 22:37:07 +10003881
Russ Cox83f648c2011-12-12 22:21:46 -05003882 <li>
3883 Complex values are comparable.
3884 Two complex values <code>u</code> and <code>v</code> are
Robert Griesemer1d282a82010-06-03 16:55:50 -07003885 equal if both <code>real(u) == real(v)</code> and
3886 <code>imag(u) == imag(v)</code>.
3887 </li>
Hong Ruiqi8374e672012-04-05 22:37:07 +10003888
Robert Griesemer1d282a82010-06-03 16:55:50 -07003889 <li>
Russ Cox83f648c2011-12-12 22:21:46 -05003890 String values are comparable and ordered, lexically byte-wise.
Robert Griesemer1d282a82010-06-03 16:55:50 -07003891 </li>
Hong Ruiqi8374e672012-04-05 22:37:07 +10003892
Robert Griesemer1d282a82010-06-03 16:55:50 -07003893 <li>
Russ Cox83f648c2011-12-12 22:21:46 -05003894 Pointer values are comparable.
Robert Griesemer1320ce02012-01-09 16:54:24 -08003895 Two pointer values are equal if they point to the same variable or if both have value <code>nil</code>.
3896 Pointers to distinct <a href="#Size_and_alignment_guarantees">zero-size</a> variables may or may not be equal.
Robert Griesemer1d282a82010-06-03 16:55:50 -07003897 </li>
Hong Ruiqi8374e672012-04-05 22:37:07 +10003898
Robert Griesemer1d282a82010-06-03 16:55:50 -07003899 <li>
Russ Cox83f648c2011-12-12 22:21:46 -05003900 Channel values are comparable.
Robert Griesemer462a17e2013-03-22 15:36:04 -07003901 Two channel values are equal if they were created by the same call to
3902 <a href="#Making_slices_maps_and_channels"><code>make</code></a>
Russ Cox83f648c2011-12-12 22:21:46 -05003903 or if both have value <code>nil</code>.
Robert Griesemer1d282a82010-06-03 16:55:50 -07003904 </li>
Russ Cox83f648c2011-12-12 22:21:46 -05003905
Robert Griesemer1d282a82010-06-03 16:55:50 -07003906 <li>
Russ Cox83f648c2011-12-12 22:21:46 -05003907 Interface values are comparable.
3908 Two interface values are equal if they have <a href="#Type_identity">identical</a> dynamic types
3909 and equal dynamic values or if both have value <code>nil</code>.
Robert Griesemer1d282a82010-06-03 16:55:50 -07003910 </li>
Hong Ruiqi8374e672012-04-05 22:37:07 +10003911
Robert Griesemer1d282a82010-06-03 16:55:50 -07003912 <li>
Russ Cox83f648c2011-12-12 22:21:46 -05003913 A value <code>x</code> of non-interface type <code>X</code> and
3914 a value <code>t</code> of interface type <code>T</code> are comparable when values
3915 of type <code>X</code> are comparable and
3916 <code>X</code> implements <code>T</code>.
3917 They are equal if <code>t</code>'s dynamic type is identical to <code>X</code>
3918 and <code>t</code>'s dynamic value is equal to <code>x</code>.
Robert Griesemer1d282a82010-06-03 16:55:50 -07003919 </li>
Russ Cox83f648c2011-12-12 22:21:46 -05003920
Robert Griesemer1d282a82010-06-03 16:55:50 -07003921 <li>
Robert Griesemer39084672012-02-16 14:13:17 -08003922 Struct values are comparable if all their fields are comparable.
3923 Two struct values are equal if their corresponding
3924 non-<a href="#Blank_identifier">blank</a> fields are equal.
Russ Cox83f648c2011-12-12 22:21:46 -05003925 </li>
Hong Ruiqi8374e672012-04-05 22:37:07 +10003926
Russ Cox83f648c2011-12-12 22:21:46 -05003927 <li>
3928 Array values are comparable if values of the array element type are comparable.
3929 Two array values are equal if their corresponding elements are equal.
Robert Griesemer1d282a82010-06-03 16:55:50 -07003930 </li>
3931</ul>
Robert Griesemera3294712009-01-05 11:17:26 -08003932
Russ Cox83f648c2011-12-12 22:21:46 -05003933<p>
3934A comparison of two interface values with identical dynamic types
3935causes a <a href="#Run_time_panics">run-time panic</a> if values
3936of that type are not comparable. This behavior applies not only to direct interface
3937value comparisons but also when comparing arrays of interface values
3938or structs with interface-valued fields.
3939</p>
3940
3941<p>
3942Slice, map, and function values are not comparable.
3943However, as a special case, a slice, map, or function value may
3944be compared to the predeclared identifier <code>nil</code>.
3945Comparison of pointer, channel, and interface values to <code>nil</code>
3946is also allowed and follows from the general rules above.
3947</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003948
Russ Cox9c08d652012-02-21 22:04:30 -05003949<pre>
Matthew Dempskyff85f862015-10-20 15:05:22 -07003950const c = 3 &lt; 4 // c is the untyped boolean constant true
Russ Cox9c08d652012-02-21 22:04:30 -05003951
Robert Griesemerc729ed62013-03-11 09:16:29 -07003952type MyBool bool
Russ Cox9c08d652012-02-21 22:04:30 -05003953var x, y int
3954var (
Matthew Dempskyff85f862015-10-20 15:05:22 -07003955 // The result of a comparison is an untyped boolean.
Robert Griesemerc729ed62013-03-11 09:16:29 -07003956 // The usual assignment rules apply.
3957 b3 = x == y // b3 has type bool
3958 b4 bool = x == y // b4 has type bool
3959 b5 MyBool = x == y // b5 has type MyBool
Russ Cox9c08d652012-02-21 22:04:30 -05003960)
3961</pre>
3962
Russ Cox7c4f7cc2009-08-20 11:11:03 -07003963<h3 id="Logical_operators">Logical operators</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003964
Rob Pikedf3183f2009-02-26 16:37:23 -08003965<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -07003966Logical operators apply to <a href="#Boolean_types">boolean</a> values
3967and yield a result of the same type as the operands.
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003968The right operand is evaluated conditionally.
Rob Pikedf3183f2009-02-26 16:37:23 -08003969</p>
Robert Griesemer41d65ac2008-09-04 15:17:27 -07003970
Rob Pikeff70f092009-02-20 13:36:14 -08003971<pre class="grammar">
Russ Cox1b4e37a2012-09-12 12:05:24 -04003972&amp;&amp; conditional AND p &amp;&amp; q is "if p then q else false"
3973|| conditional OR p || q is "if p then true else q"
3974! NOT !p is "not p"
Robert Griesemerc2d55862009-02-19 16:49:10 -08003975</pre>
Robert Griesemer7a4ed4f2008-09-03 15:15:51 -07003976
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003977
Russ Cox7c4f7cc2009-08-20 11:11:03 -07003978<h3 id="Address_operators">Address operators</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07003979
Rob Pikedf3183f2009-02-26 16:37:23 -08003980<p>
Robert Griesemer0e1d9412011-01-26 11:21:23 -08003981For an operand <code>x</code> of type <code>T</code>, the address operation
3982<code>&amp;x</code> generates a pointer of type <code>*T</code> to <code>x</code>.
3983The operand must be <i>addressable</i>,
Russ Coxe7561de2010-05-24 14:31:43 -07003984that is, either a variable, pointer indirection, or slice indexing
Robert Griesemer0e1d9412011-01-26 11:21:23 -08003985operation; or a field selector of an addressable struct operand;
Russ Coxe7561de2010-05-24 14:31:43 -07003986or an array indexing operation of an addressable array.
Robert Griesemer0e1d9412011-01-26 11:21:23 -08003987As an exception to the addressability requirement, <code>x</code> may also be a
Robert Griesemer614b02d2013-01-02 18:11:49 -08003988(possibly parenthesized)
Robert Griesemer0e1d9412011-01-26 11:21:23 -08003989<a href="#Composite_literals">composite literal</a>.
Robin Eklindcac006a2014-08-30 10:27:01 -07003990If the evaluation of <code>x</code> would cause a <a href="#Run_time_panics">run-time panic</a>,
Rob Pikecec09542013-09-17 07:41:11 +10003991then the evaluation of <code>&amp;x</code> does too.
Robert Griesemer0e1d9412011-01-26 11:21:23 -08003992</p>
Russ Cox5ce78b72013-08-15 14:33:26 -04003993
Robert Griesemer0e1d9412011-01-26 11:21:23 -08003994<p>
3995For an operand <code>x</code> of pointer type <code>*T</code>, the pointer
Robert Griesemer6962c152014-10-16 15:08:49 -07003996indirection <code>*x</code> denotes the <a href="#Variables">variable</a> of type <code>T</code> pointed
Robert Griesemer0e1d9412011-01-26 11:21:23 -08003997to by <code>x</code>.
Rob Pike633a2ce2012-01-23 08:40:13 -08003998If <code>x</code> is <code>nil</code>, an attempt to evaluate <code>*x</code>
3999will cause a <a href="#Run_time_panics">run-time panic</a>.
Rob Pikeafee1c52009-03-20 17:41:25 -07004000</p>
4001
4002<pre>
4003&amp;x
4004&amp;a[f(2)]
Robert Griesemer614b02d2013-01-02 18:11:49 -08004005&amp;Point{2, 3}
Rob Pikeafee1c52009-03-20 17:41:25 -07004006*p
4007*pf(x)
Russ Cox5ce78b72013-08-15 14:33:26 -04004008
4009var x *int = nil
4010*x // causes a run-time panic
Rob Pikecec09542013-09-17 07:41:11 +10004011&amp;*x // causes a run-time panic
Rob Pikeafee1c52009-03-20 17:41:25 -07004012</pre>
4013
Robert Griesemerb50ed022011-02-01 12:02:49 -08004014
4015<h3 id="Receive_operator">Receive operator</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004016
Robert Griesemerc2d55862009-02-19 16:49:10 -08004017<p>
Robert Griesemerb50ed022011-02-01 12:02:49 -08004018For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>,
4019the value of the receive operation <code>&lt;-ch</code> is the value received
Robert Griesemercc3f21c2012-12-03 14:23:41 -08004020from the channel <code>ch</code>. The channel direction must permit receive operations,
4021and the type of the receive operation is the element type of the channel.
4022The expression blocks until a value is available.
Robert Griesemer54731032011-05-12 09:15:59 -07004023Receiving from a <code>nil</code> channel blocks forever.
Robert Griesemerab5c7622013-05-31 11:21:37 -07004024A receive operation on a <a href="#Close">closed</a> channel can always proceed
Robert Griesemer97aa90d2014-05-07 10:40:39 -07004025immediately, yielding the element type's <a href="#The_zero_value">zero value</a>
4026after any previously sent values have been received.
Rob Pikedf3183f2009-02-26 16:37:23 -08004027</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004028
Robert Griesemerc2d55862009-02-19 16:49:10 -08004029<pre>
Robert Griesemere1e76192009-09-25 14:11:03 -07004030v1 := &lt;-ch
4031v2 = &lt;-ch
4032f(&lt;-ch)
Robert Griesemerb50ed022011-02-01 12:02:49 -08004033&lt;-strobe // wait until clock pulse and discard received value
Robert Griesemerc2d55862009-02-19 16:49:10 -08004034</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004035
Rob Pikedf3183f2009-02-26 16:37:23 -08004036<p>
Robert Griesemerc0fca132014-08-05 11:31:32 -07004037A receive expression used in an <a href="#Assignments">assignment</a> or initialization of the special form
Rob Pikedf3183f2009-02-26 16:37:23 -08004038</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004039
Robert Griesemerc2d55862009-02-19 16:49:10 -08004040<pre>
Robert Griesemere1e76192009-09-25 14:11:03 -07004041x, ok = &lt;-ch
4042x, ok := &lt;-ch
4043var x, ok = &lt;-ch
Robert Griesemer507051d2016-08-24 11:33:55 -07004044var x, ok T = &lt;-ch
Robert Griesemerc2d55862009-02-19 16:49:10 -08004045</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004046
Rob Pikedf3183f2009-02-26 16:37:23 -08004047<p>
Robert Griesemerc0fca132014-08-05 11:31:32 -07004048yields an additional untyped boolean result reporting whether the
Robert Griesemer689931c2012-06-25 11:28:24 -07004049communication succeeded. The value of <code>ok</code> is <code>true</code>
4050if the value received was delivered by a successful send operation to the
4051channel, or <code>false</code> if it is a zero value generated because the
4052channel is closed and empty.
Rob Pikedf3183f2009-02-26 16:37:23 -08004053</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004054
Robert Griesemerb50ed022011-02-01 12:02:49 -08004055
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004056<h3 id="Conversions">Conversions</h3>
4057
4058<p>
Robert Griesemer26d22602018-10-02 15:55:38 -07004059A conversion changes the <a href="#Types">type</a> of an expression
4060to the type specified by the conversion.
4061A conversion may appear literally in the source, or it may be <i>implied</i>
4062by the context in which an expression appears.
4063</p>
4064
4065<p>
4066An <i>explicit</i> conversion is an expression of the form <code>T(x)</code>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004067where <code>T</code> is a type and <code>x</code> is an expression
4068that can be converted to type <code>T</code>.
4069</p>
4070
4071<pre class="ebnf">
Robert Griesemer60a6ae82012-09-26 10:31:57 -07004072Conversion = Type "(" Expression [ "," ] ")" .
Robert Griesemer934a5202010-05-24 14:58:26 -07004073</pre>
4074
4075<p>
Robert Griesemer3188ffc2012-10-03 13:46:37 -07004076If the type starts with the operator <code>*</code> or <code>&lt;-</code>,
Russ Cox71c941b2013-02-11 07:48:14 -05004077or if the type starts with the keyword <code>func</code>
4078and has no result list, it must be parenthesized when
4079necessary to avoid ambiguity:
Robert Griesemer934a5202010-05-24 14:58:26 -07004080</p>
4081
4082<pre>
4083*Point(p) // same as *(Point(p))
Russ Cox71c941b2013-02-11 07:48:14 -05004084(*Point)(p) // p is converted to *Point
Robert Griesemer934a5202010-05-24 14:58:26 -07004085&lt;-chan int(c) // same as &lt;-(chan int(c))
Russ Cox71c941b2013-02-11 07:48:14 -05004086(&lt;-chan int)(c) // c is converted to &lt;-chan int
Robert Griesemer3188ffc2012-10-03 13:46:37 -07004087func()(x) // function signature func() x
Russ Cox71c941b2013-02-11 07:48:14 -05004088(func())(x) // x is converted to func()
4089(func() int)(x) // x is converted to func() int
4090func() int(x) // x is converted to func() int (unambiguous)
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004091</pre>
4092
4093<p>
Robert Griesemer27693562011-06-13 16:47:33 -07004094A <a href="#Constants">constant</a> value <code>x</code> can be converted to
griesemerb40831b2017-08-21 15:47:51 +02004095type <code>T</code> if <code>x</code> is <a href="#Representability">representable</a>
4096by a value of <code>T</code>.
Robert Griesemer26d22602018-10-02 15:55:38 -07004097As a special case, an integer constant <code>x</code> can be explicitly converted to a
griesemerb40831b2017-08-21 15:47:51 +02004098<a href="#String_types">string type</a> using the
4099<a href="#Conversions_to_and_from_a_string_type">same rule</a>
4100as for non-constant <code>x</code>.
Robert Griesemer27693562011-06-13 16:47:33 -07004101</p>
4102
Robert Griesemer27693562011-06-13 16:47:33 -07004103<p>
4104Converting a constant yields a typed constant as result.
4105</p>
4106
4107<pre>
4108uint(iota) // iota value of type uint
4109float32(2.718281828) // 2.718281828 of type float32
4110complex128(1) // 1.0 + 0.0i of type complex128
Russ Cox75761792013-02-11 07:47:41 -05004111float32(0.49999999) // 0.5 of type float32
Robert Griesemer55ecda42015-09-17 18:10:20 -07004112float64(-1e-1000) // 0.0 of type float64
Robert Griesemer27693562011-06-13 16:47:33 -07004113string('x') // "x" of type string
4114string(0x266c) // "♬" of type string
4115MyString("foo" + "bar") // "foobar" of type MyString
4116string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant
4117(*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
4118int(1.2) // illegal: 1.2 cannot be represented as an int
4119string(65.0) // illegal: 65.0 is not an integer constant
4120</pre>
4121
4122<p>
4123A non-constant value <code>x</code> can be converted to type <code>T</code>
4124in any of these cases:
Robert Griesemer63f01492010-05-28 14:17:30 -07004125</p>
Robert Griesemer7bc03712010-06-07 15:49:39 -07004126
4127<ul>
4128 <li>
Robert Griesemer440cc952010-06-07 17:40:21 -07004129 <code>x</code> is <a href="#Assignability">assignable</a>
Robert Griesemer7bc03712010-06-07 15:49:39 -07004130 to <code>T</code>.
4131 </li>
4132 <li>
Robert Griesemer5c7a0052016-06-03 13:21:55 -07004133 ignoring struct tags (see below),
4134 <code>x</code>'s type and <code>T</code> have <a href="#Type_identity">identical</a>
Robert Griesemer7bc03712010-06-07 15:49:39 -07004135 <a href="#Types">underlying types</a>.
4136 </li>
4137 <li>
Robert Griesemer5c7a0052016-06-03 13:21:55 -07004138 ignoring struct tags (see below),
Robert Griesemer866f63e2017-02-09 13:22:37 -08004139 <code>x</code>'s type and <code>T</code> are pointer types
4140 that are not <a href="#Type_definitions">defined types</a>,
Robert Griesemer7bc03712010-06-07 15:49:39 -07004141 and their pointer base types have identical underlying types.
4142 </li>
4143 <li>
4144 <code>x</code>'s type and <code>T</code> are both integer or floating
4145 point types.
4146 </li>
4147 <li>
4148 <code>x</code>'s type and <code>T</code> are both complex types.
4149 </li>
4150 <li>
Robert Griesemer60a6ae82012-09-26 10:31:57 -07004151 <code>x</code> is an integer or a slice of bytes or runes
4152 and <code>T</code> is a string type.
Robert Griesemer7bc03712010-06-07 15:49:39 -07004153 </li>
4154 <li>
Robert Griesemer60a6ae82012-09-26 10:31:57 -07004155 <code>x</code> is a string and <code>T</code> is a slice of bytes or runes.
Robert Griesemer7bc03712010-06-07 15:49:39 -07004156 </li>
4157</ul>
4158
4159<p>
Robert Griesemer5c7a0052016-06-03 13:21:55 -07004160<a href="#Struct_types">Struct tags</a> are ignored when comparing struct types
4161for identity for the purpose of conversion:
4162</p>
4163
4164<pre>
4165type Person struct {
4166 Name string
4167 Address *struct {
4168 Street string
4169 City string
4170 }
4171}
4172
4173var data *struct {
4174 Name string `json:"name"`
4175 Address *struct {
4176 Street string `json:"street"`
4177 City string `json:"city"`
4178 } `json:"address"`
4179}
4180
4181var person = (*Person)(data) // ignoring tags, the underlying types are identical
4182</pre>
4183
4184<p>
Robert Griesemer27693562011-06-13 16:47:33 -07004185Specific rules apply to (non-constant) conversions between numeric types or
4186to and from a string type.
Robert Griesemer7bc03712010-06-07 15:49:39 -07004187These conversions may change the representation of <code>x</code>
4188and incur a run-time cost.
4189All other conversions only change the type but not the representation
4190of <code>x</code>.
4191</p>
4192
Robert Griesemer27693562011-06-13 16:47:33 -07004193<p>
4194There is no linguistic mechanism to convert between pointers and integers.
4195The package <a href="#Package_unsafe"><code>unsafe</code></a>
4196implements this functionality under
4197restricted circumstances.
4198</p>
4199
Robert Griesemer7bc03712010-06-07 15:49:39 -07004200<h4>Conversions between numeric types</h4>
Robert Griesemer27693562011-06-13 16:47:33 -07004201
4202<p>
4203For the conversion of non-constant numeric values, the following rules apply:
4204</p>
4205
Robert Griesemer63f01492010-05-28 14:17:30 -07004206<ol>
4207<li>
Robert Griesemer7bc03712010-06-07 15:49:39 -07004208When converting between integer types, if the value is a signed integer, it is
4209sign extended to implicit infinite precision; otherwise it is zero extended.
4210It is then truncated to fit in the result type's size.
4211For example, if <code>v := uint16(0x10F0)</code>, then <code>uint32(int8(v)) == 0xFFFFFFF0</code>.
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004212The conversion always yields a valid value; there is no indication of overflow.
Robert Griesemer7bc03712010-06-07 15:49:39 -07004213</li>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004214<li>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004215When converting a floating-point number to an integer, the fraction is discarded
4216(truncation towards zero).
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004217</li>
4218<li>
Robert Griesemer7bc03712010-06-07 15:49:39 -07004219When converting an integer or floating-point number to a floating-point type,
4220or a complex number to another complex type, the result value is rounded
Rob Pike72970872010-03-04 12:35:16 -08004221to the precision specified by the destination type.
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07004222For instance, the value of a variable <code>x</code> of type <code>float32</code>
4223may be stored using additional precision beyond that of an IEEE-754 32-bit number,
4224but float32(x) represents the result of rounding <code>x</code>'s value to
422532-bit precision. Similarly, <code>x + 0.1</code> may use more than 32 bits
Evan Shawcb4e9f82010-05-23 11:21:47 -07004226of precision, but <code>float32(x + 0.1)</code> does not.
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004227</li>
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07004228</ol>
4229
4230<p>
Robert Griesemer27693562011-06-13 16:47:33 -07004231In all non-constant conversions involving floating-point or complex values,
Rob Pike72970872010-03-04 12:35:16 -08004232if the result type cannot represent the value the conversion
Robert Griesemer27693562011-06-13 16:47:33 -07004233succeeds but the result value is implementation-dependent.
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07004234</p>
4235
Robert Griesemer27693562011-06-13 16:47:33 -07004236<h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4>
Rob Pike1811fac2010-02-17 11:26:09 +11004237
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07004238<ol>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004239<li>
Rob Pike1811fac2010-02-17 11:26:09 +11004240Converting a signed or unsigned integer value to a string type yields a
Robert Griesemer7bc03712010-06-07 15:49:39 -07004241string containing the UTF-8 representation of the integer. Values outside
4242the range of valid Unicode code points are converted to <code>"\uFFFD"</code>.
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004243
4244<pre>
David Symonds72a29792011-11-29 15:47:36 -08004245string('a') // "a"
Rémy Oudompheng2b4cc6c2012-07-11 20:26:51 +02004246string(-1) // "\ufffd" == "\xef\xbf\xbd"
David Symonds72a29792011-11-29 15:47:36 -08004247string(0xf8) // "\u00f8" == "ø" == "\xc3\xb8"
Rob Pike1811fac2010-02-17 11:26:09 +11004248type MyString string
David Symonds72a29792011-11-29 15:47:36 -08004249MyString(0x65e5) // "\u65e5" == "日" == "\xe6\x97\xa5"
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004250</pre>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004251</li>
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07004252
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004253<li>
Russ Cox6e3e3802011-11-22 12:30:02 -05004254Converting a slice of bytes to a string type yields
Robert Griesemerde47f682013-06-21 16:11:13 -07004255a string whose successive bytes are the elements of the slice.
Rob Pike1811fac2010-02-17 11:26:09 +11004256
4257<pre>
Robert Griesemerde47f682013-06-21 16:11:13 -07004258string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
4259string([]byte{}) // ""
4260string([]byte(nil)) // ""
Russ Cox6e3e3802011-11-22 12:30:02 -05004261
4262type MyBytes []byte
4263string(MyBytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"
Rob Pike1811fac2010-02-17 11:26:09 +11004264</pre>
4265</li>
4266
4267<li>
Russ Cox6e3e3802011-11-22 12:30:02 -05004268Converting a slice of runes to a string type yields
Robert Griesemerb910a272011-11-01 01:09:22 -04004269a string that is the concatenation of the individual rune values
Robert Griesemerde47f682013-06-21 16:11:13 -07004270converted to strings.
Robert Griesemerb910a272011-11-01 01:09:22 -04004271
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004272<pre>
Robert Griesemerde47f682013-06-21 16:11:13 -07004273string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
4274string([]rune{}) // ""
4275string([]rune(nil)) // ""
Russ Cox6e3e3802011-11-22 12:30:02 -05004276
4277type MyRunes []rune
4278string(MyRunes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07004279</pre>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004280</li>
4281
4282<li>
Russ Cox6e3e3802011-11-22 12:30:02 -05004283Converting a value of a string type to a slice of bytes type
Rob Pike1811fac2010-02-17 11:26:09 +11004284yields a slice whose successive elements are the bytes of the string.
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004285
4286<pre>
David Symonds72a29792011-11-29 15:47:36 -08004287[]byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
Robert Griesemerde47f682013-06-21 16:11:13 -07004288[]byte("") // []byte{}
4289
David Symonds72a29792011-11-29 15:47:36 -08004290MyBytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}
Rob Pike1811fac2010-02-17 11:26:09 +11004291</pre>
4292</li>
4293
4294<li>
Russ Cox6e3e3802011-11-22 12:30:02 -05004295Converting a value of a string type to a slice of runes type
4296yields a slice containing the individual Unicode code points of the string.
Robert Griesemerde47f682013-06-21 16:11:13 -07004297
Rob Pike1811fac2010-02-17 11:26:09 +11004298<pre>
Robert Griesemerb910a272011-11-01 01:09:22 -04004299[]rune(MyString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4}
Robert Griesemerde47f682013-06-21 16:11:13 -07004300[]rune("") // []rune{}
4301
Russ Cox6e3e3802011-11-22 12:30:02 -05004302MyRunes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4}
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004303</pre>
4304</li>
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07004305</ol>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004306
Robert Griesemer164a7bc2009-09-30 12:00:25 -07004307
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004308<h3 id="Constant_expressions">Constant expressions</h3>
Robert Griesemerb90b2132008-09-19 15:49:55 -07004309
Rob Pikef27e9f02009-02-23 19:22:05 -08004310<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -07004311Constant expressions may contain only <a href="#Constants">constant</a>
Robert Griesemerea7c57a2012-10-17 11:08:42 -07004312operands and are evaluated at compile time.
Rob Pikef27e9f02009-02-23 19:22:05 -08004313</p>
4314
4315<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -07004316Untyped boolean, numeric, and string constants may be used as operands
4317wherever it is legal to use an operand of boolean, numeric, or string type,
Russ Coxa9336352011-12-08 21:48:19 -05004318respectively.
Robert Griesemer19b1d352009-09-24 19:36:48 -07004319</p>
Robert Griesemer997851e2009-09-25 15:36:25 -07004320
4321<p>
Robert Griesemer32d12782011-05-23 14:12:42 -07004322A constant <a href="#Comparison_operators">comparison</a> always yields
Russ Cox9c08d652012-02-21 22:04:30 -05004323an untyped boolean constant. If the left operand of a constant
Robert Griesemer32d12782011-05-23 14:12:42 -07004324<a href="#Operators">shift expression</a> is an untyped constant, the
4325result is an integer constant; otherwise it is a constant of the same
Robert Griesemer462a17e2013-03-22 15:36:04 -07004326type as the left operand, which must be of
4327<a href="#Numeric_types">integer type</a>.
Bryan C. Millsdf480032018-04-13 11:57:13 -04004328</p>
4329
4330<p>
4331Any other operation on untyped constants results in an untyped constant of the
4332same kind; that is, a boolean, integer, floating-point, complex, or string
4333constant.
4334If the untyped operands of a binary operation (other than a shift) are of
4335different kinds, the result is of the operand's kind that appears later in this
4336list: integer, rune, floating-point, complex.
4337For example, an untyped integer constant divided by an
4338untyped complex constant yields an untyped complex constant.
Robert Griesemer19b1d352009-09-24 19:36:48 -07004339</p>
4340
Robert Griesemer32d12782011-05-23 14:12:42 -07004341<pre>
Russ Coxa9336352011-12-08 21:48:19 -05004342const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant)
4343const b = 15 / 4 // b == 3 (untyped integer constant)
4344const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant)
Robert Griesemer2ae61d52012-11-17 11:16:07 -08004345const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division)
4346const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division)
Russ Coxa9336352011-12-08 21:48:19 -05004347const d = 1 &lt;&lt; 3.0 // d == 8 (untyped integer constant)
4348const e = 1.0 &lt;&lt; 3 // e == 8 (untyped integer constant)
Robert Griesemer2d846f62013-05-08 10:42:08 -07004349const f = int32(1) &lt;&lt; 33 // illegal (constant 8589934592 overflows int32)
Robert Griesemer32d12782011-05-23 14:12:42 -07004350const g = float64(2) &gt;&gt; 1 // illegal (float64(2) is a typed floating-point constant)
Russ Coxef1c5352011-12-09 00:13:19 -05004351const h = "foo" &gt; "bar" // h == true (untyped boolean constant)
4352const j = true // j == true (untyped boolean constant)
Rob Pike9dfc6f62012-08-29 14:46:57 -07004353const k = 'w' + 1 // k == 'x' (untyped rune constant)
Russ Coxef1c5352011-12-09 00:13:19 -05004354const l = "hi" // l == "hi" (untyped string constant)
4355const m = string(k) // m == "x" (type string)
Robert Hencke1084ab92011-12-10 10:04:33 -08004356const Σ = 1 - 0.707i // (untyped complex constant)
Russ Coxa9336352011-12-08 21:48:19 -05004357const Δ = Σ + 2.0e-4 // (untyped complex constant)
4358const Φ = iota*1i - 1/1i // (untyped complex constant)
Robert Griesemer32d12782011-05-23 14:12:42 -07004359</pre>
4360
Robert Griesemer19b1d352009-09-24 19:36:48 -07004361<p>
Russ Coxa9336352011-12-08 21:48:19 -05004362Applying the built-in function <code>complex</code> to untyped
Rob Pike9dfc6f62012-08-29 14:46:57 -07004363integer, rune, or floating-point constants yields
Russ Coxa9336352011-12-08 21:48:19 -05004364an untyped complex constant.
Rob Pike72970872010-03-04 12:35:16 -08004365</p>
4366
4367<pre>
Robert Griesemer462860b2012-12-12 14:25:40 -08004368const ic = complex(0, c) // ic == 3.75i (untyped complex constant)
Mihai Borobocea8183ed12013-12-30 13:29:56 -08004369const iΘ = complex(0, Θ) // iΘ == 1i (type complex128)
Rob Pike72970872010-03-04 12:35:16 -08004370</pre>
4371
4372<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -07004373Constant expressions are always evaluated exactly; intermediate values and the
4374constants themselves may require precision significantly larger than supported
4375by any predeclared type in the language. The following are legal declarations:
Rob Pikef27e9f02009-02-23 19:22:05 -08004376</p>
4377
4378<pre>
Robert Griesemer462860b2012-12-12 14:25:40 -08004379const Huge = 1 &lt;&lt; 100 // Huge == 1267650600228229401496703205376 (untyped integer constant)
4380const Four int8 = Huge &gt;&gt; 98 // Four == 4 (type int8)
Rob Pikef27e9f02009-02-23 19:22:05 -08004381</pre>
4382
4383<p>
Robert Griesemerddddd392012-10-19 10:12:09 -07004384The divisor of a constant division or remainder operation must not be zero:
4385</p>
4386
4387<pre>
43883.14 / 0.0 // illegal: division by zero
4389</pre>
4390
4391<p>
griesemerb40831b2017-08-21 15:47:51 +02004392The values of <i>typed</i> constants must always be accurately
4393<a href="#Representability">representable</a> by values
Robert Griesemer19b1d352009-09-24 19:36:48 -07004394of the constant type. The following constant expressions are illegal:
Rob Pike21d03492009-03-24 19:16:42 -07004395</p>
4396
4397<pre>
David Symonds72a29792011-11-29 15:47:36 -08004398uint(-1) // -1 cannot be represented as a uint
4399int(3.14) // 3.14 cannot be represented as an int
Robert Griesemer462860b2012-12-12 14:25:40 -08004400int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64
4401Four * 300 // operand 300 cannot be represented as an int8 (type of Four)
4402Four * 100 // product 400 cannot be represented as an int8 (type of Four)
Rob Pike21d03492009-03-24 19:16:42 -07004403</pre>
4404
4405<p>
Robert Griesemer19b1d352009-09-24 19:36:48 -07004406The mask used by the unary bitwise complement operator <code>^</code> matches
Rob Pike678625d2009-09-15 09:54:22 -07004407the rule for non-constants: the mask is all 1s for unsigned constants
Robert Griesemer19b1d352009-09-24 19:36:48 -07004408and -1 for signed and untyped constants.
Rob Pike21d03492009-03-24 19:16:42 -07004409</p>
4410
4411<pre>
David Symonds72a29792011-11-29 15:47:36 -08004412^1 // untyped integer constant, equal to -2
Robert Griesemer462860b2012-12-12 14:25:40 -08004413uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8
David Symonds72a29792011-11-29 15:47:36 -08004414^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)
4415int8(^1) // same as int8(-2)
4416^int8(1) // same as -1 ^ int8(1) = -2
Rob Pike21d03492009-03-24 19:16:42 -07004417</pre>
4418
Ian Lance Taylor9126c652012-02-13 11:25:56 -08004419<p>
4420Implementation restriction: A compiler may use rounding while
4421computing untyped floating-point or complex constant expressions; see
4422the implementation restriction in the section
4423on <a href="#Constants">constants</a>. This rounding may cause a
4424floating-point constant expression to be invalid in an integer
4425context, even if it would be integral when calculated using infinite
Robert Griesemerd8c6dac2015-06-23 14:17:59 -07004426precision, and vice versa.
Ian Lance Taylor9126c652012-02-13 11:25:56 -08004427</p>
4428
Robert Griesemer19b1d352009-09-24 19:36:48 -07004429
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004430<h3 id="Order_of_evaluation">Order of evaluation</h3>
Rob Pikec956e902009-04-14 20:10:49 -07004431
4432<p>
Robert Griesemera4366982014-05-20 13:51:39 -07004433At package level, <a href="#Package_initialization">initialization dependencies</a>
Robert Griesemerdbe5f882014-05-07 08:50:52 -07004434determine the evaluation order of individual initialization expressions in
4435<a href="#Variable_declarations">variable declarations</a>.
4436Otherwise, when evaluating the <a href="#Operands">operands</a> of an
4437expression, assignment, or
Robert Griesemerf05a91e2012-08-09 11:50:16 -07004438<a href="#Return_statements">return statement</a>,
4439all function calls, method calls, and
Rob Pikec956e902009-04-14 20:10:49 -07004440communication operations are evaluated in lexical left-to-right
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07004441order.
4442</p>
4443
4444<p>
Robert Griesemerdbe5f882014-05-07 08:50:52 -07004445For example, in the (function-local) assignment
Rob Pikec956e902009-04-14 20:10:49 -07004446</p>
4447<pre>
David Symonds72a29792011-11-29 15:47:36 -08004448y[f()], ok = g(h(), i()+x[j()], &lt;-c), k()
Rob Pikec956e902009-04-14 20:10:49 -07004449</pre>
4450<p>
Robert Griesemer4f185492009-05-01 17:00:16 -07004451the function calls and communication happen in the order
4452<code>f()</code>, <code>h()</code>, <code>i()</code>, <code>j()</code>,
Robert Griesemere1e76192009-09-25 14:11:03 -07004453<code>&lt;-c</code>, <code>g()</code>, and <code>k()</code>.
Robert Griesemer4f185492009-05-01 17:00:16 -07004454However, the order of those events compared to the evaluation
4455and indexing of <code>x</code> and the evaluation
4456of <code>y</code> is not specified.
Rob Pikec956e902009-04-14 20:10:49 -07004457</p>
4458
Robert Griesemerf05a91e2012-08-09 11:50:16 -07004459<pre>
4460a := 1
Shenghou Mabdac9892013-06-11 02:52:07 +08004461f := func() int { a++; return a }
Robert Griesemerdbe5f882014-05-07 08:50:52 -07004462x := []int{a, f()} // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specified
4463m := 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
4464n := map[int]int{a: f()} // n may be {2: 3} or {3: 3}: evaluation order between the key and the value is not specified
Robert Griesemerf05a91e2012-08-09 11:50:16 -07004465</pre>
4466
Rob Pike4fe41922009-11-07 22:00:59 -08004467<p>
Robert Griesemerdbe5f882014-05-07 08:50:52 -07004468At package level, initialization dependencies override the left-to-right rule
4469for individual initialization expressions, but not for operands within each
Robin Eklindcac006a2014-08-30 10:27:01 -07004470expression:
Robert Griesemerdbe5f882014-05-07 08:50:52 -07004471</p>
4472
4473<pre>
4474var a, b, c = f() + v(), g(), sqr(u()) + v()
4475
4476func f() int { return c }
4477func g() int { return a }
4478func sqr(x int) int { return x*x }
4479
4480// functions u and v are independent of all other variables and functions
4481</pre>
4482
4483<p>
4484The function calls happen in the order
4485<code>u()</code>, <code>sqr()</code>, <code>v()</code>,
4486<code>f()</code>, <code>v()</code>, and <code>g()</code>.
4487</p>
4488
4489<p>
Rob Pike4fe41922009-11-07 22:00:59 -08004490Floating-point operations within a single expression are evaluated according to
4491the associativity of the operators. Explicit parentheses affect the evaluation
4492by overriding the default associativity.
4493In the expression <code>x + (y + z)</code> the addition <code>y + z</code>
4494is performed before adding <code>x</code>.
4495</p>
4496
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004497<h2 id="Statements">Statements</h2>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004498
Rob Pike96750f12009-02-27 16:47:48 -08004499<p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004500Statements control execution.
Rob Pike96750f12009-02-27 16:47:48 -08004501</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004502
Robert Griesemerf7ac31362009-07-10 16:06:40 -07004503<pre class="ebnf">
Robert Griesemerdea43942009-03-16 17:36:52 -07004504Statement =
Rob Pikef3a33bc2009-09-14 17:39:17 -07004505 Declaration | LabeledStmt | SimpleStmt |
4506 GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
Rob Pike11417162009-03-24 17:45:53 -07004507 FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
4508 DeferStmt .
Robert Griesemer7abfcd92008-10-07 17:14:30 -07004509
Robert Griesemerb50ed022011-02-01 12:02:49 -08004510SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
Robert Griesemerc2d55862009-02-19 16:49:10 -08004511</pre>
Robert Griesemer7271e042008-10-09 20:05:24 -07004512
Robert Griesemer9905cec2013-03-04 13:55:35 -08004513<h3 id="Terminating_statements">Terminating statements</h3>
4514
4515<p>
Robert Griesemerf3f507b2017-12-21 15:17:35 -08004516A <i>terminating statement</i> prevents execution of all statements that lexically
4517appear after it in the same <a href="#Blocks">block</a>. The following statements
4518are terminating:
Robert Griesemer9905cec2013-03-04 13:55:35 -08004519</p>
4520
4521<ol>
4522<li>
4523 A <a href="#Return_statements">"return"</a> or
4524 <a href="#Goto_statements">"goto"</a> statement.
4525 <!-- ul below only for regular layout -->
4526 <ul> </ul>
4527</li>
4528
4529<li>
4530 A call to the built-in function
4531 <a href="#Handling_panics"><code>panic</code></a>.
4532 <!-- ul below only for regular layout -->
4533 <ul> </ul>
4534</li>
4535
4536<li>
4537 A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement.
4538 <!-- ul below only for regular layout -->
4539 <ul> </ul>
4540</li>
4541
4542<li>
4543 An <a href="#If_statements">"if" statement</a> in which:
4544 <ul>
4545 <li>the "else" branch is present, and</li>
4546 <li>both branches are terminating statements.</li>
4547 </ul>
4548</li>
4549
4550<li>
4551 A <a href="#For_statements">"for" statement</a> in which:
4552 <ul>
4553 <li>there are no "break" statements referring to the "for" statement, and</li>
4554 <li>the loop condition is absent.</li>
4555 </ul>
4556</li>
4557
4558<li>
4559 A <a href="#Switch_statements">"switch" statement</a> in which:
4560 <ul>
4561 <li>there are no "break" statements referring to the "switch" statement,</li>
4562 <li>there is a default case, and</li>
4563 <li>the statement lists in each case, including the default, end in a terminating
4564 statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough"
4565 statement</a>.</li>
4566 </ul>
4567</li>
4568
4569<li>
4570 A <a href="#Select_statements">"select" statement</a> in which:
4571 <ul>
4572 <li>there are no "break" statements referring to the "select" statement, and</li>
4573 <li>the statement lists in each case, including the default if present,
4574 end in a terminating statement.</li>
4575 </ul>
4576</li>
4577
4578<li>
4579 A <a href="#Labeled_statements">labeled statement</a> labeling
4580 a terminating statement.
4581</li>
4582</ol>
4583
4584<p>
4585All other statements are not terminating.
4586</p>
4587
4588<p>
4589A <a href="#Blocks">statement list</a> ends in a terminating statement if the list
Robert Griesemerb5ddbb92016-02-26 15:52:13 -08004590is not empty and its final non-empty statement is terminating.
Robert Griesemer9905cec2013-03-04 13:55:35 -08004591</p>
4592
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004593
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004594<h3 id="Empty_statements">Empty statements</h3>
Robert Griesemeraed247f2008-10-08 17:05:30 -07004595
Rob Pike96750f12009-02-27 16:47:48 -08004596<p>
Robert Griesemeraed247f2008-10-08 17:05:30 -07004597The empty statement does nothing.
Rob Pike96750f12009-02-27 16:47:48 -08004598</p>
Robert Griesemeraed247f2008-10-08 17:05:30 -07004599
Robert Griesemerf7ac31362009-07-10 16:06:40 -07004600<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07004601EmptyStmt = .
Robert Griesemerc2d55862009-02-19 16:49:10 -08004602</pre>
Robert Griesemeraed247f2008-10-08 17:05:30 -07004603
4604
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004605<h3 id="Labeled_statements">Labeled statements</h3>
Robert Griesemerdea43942009-03-16 17:36:52 -07004606
4607<p>
4608A labeled statement may be the target of a <code>goto</code>,
4609<code>break</code> or <code>continue</code> statement.
4610</p>
4611
Robert Griesemerf7ac31362009-07-10 16:06:40 -07004612<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07004613LabeledStmt = Label ":" Statement .
Robert Griesemerdea43942009-03-16 17:36:52 -07004614Label = identifier .
4615</pre>
4616
4617<pre>
Robert Griesemer7fc4e372011-02-01 12:51:10 -08004618Error: log.Panic("error encountered")
Robert Griesemerdea43942009-03-16 17:36:52 -07004619</pre>
4620
4621
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004622<h3 id="Expression_statements">Expression statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004623
Rob Pike96750f12009-02-27 16:47:48 -08004624<p>
Robert Griesemer8c058b32012-09-18 11:25:53 -07004625With the exception of specific built-in functions,
4626function and method <a href="#Calls">calls</a> and
4627<a href="#Receive_operator">receive operations</a>
Robert Griesemer6af887e2011-05-02 09:16:31 -07004628can appear in statement context. Such statements may be parenthesized.
Rob Pike96750f12009-02-27 16:47:48 -08004629</p>
4630
Robert Griesemerf7ac31362009-07-10 16:06:40 -07004631<pre class="ebnf">
Robert Griesemerc1347182011-04-29 12:20:31 -07004632ExpressionStmt = Expression .
Robert Griesemerc2d55862009-02-19 16:49:10 -08004633</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004634
Robert Griesemer8c058b32012-09-18 11:25:53 -07004635<p>
4636The following built-in functions are not permitted in statement context:
4637</p>
4638
4639<pre>
4640append cap complex imag len make new real
4641unsafe.Alignof unsafe.Offsetof unsafe.Sizeof
4642</pre>
4643
Robert Griesemerc2d55862009-02-19 16:49:10 -08004644<pre>
Robert Griesemerb50ed022011-02-01 12:02:49 -08004645h(x+y)
4646f.Close()
Robert Griesemere1e76192009-09-25 14:11:03 -07004647&lt;-ch
Robert Griesemer6af887e2011-05-02 09:16:31 -07004648(&lt;-ch)
Robert Griesemer8c058b32012-09-18 11:25:53 -07004649len("foo") // illegal if len is the built-in function
Robert Griesemerc2d55862009-02-19 16:49:10 -08004650</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004651
4652
Robert Griesemerb50ed022011-02-01 12:02:49 -08004653<h3 id="Send_statements">Send statements</h3>
4654
4655<p>
4656A send statement sends a value on a channel.
Robert Griesemercc3f21c2012-12-03 14:23:41 -08004657The channel expression must be of <a href="#Channel_types">channel type</a>,
4658the channel direction must permit send operations,
4659and the type of the value to be sent must be <a href="#Assignability">assignable</a>
Robert Griesemerb50ed022011-02-01 12:02:49 -08004660to the channel's element type.
4661</p>
4662
4663<pre class="ebnf">
4664SendStmt = Channel "&lt;-" Expression .
4665Channel = Expression .
4666</pre>
4667
4668<p>
4669Both the channel and the value expression are evaluated before communication
Russ Coxe7a138b2012-02-08 15:24:48 -05004670begins. Communication blocks until the send can proceed.
Robert Griesemerb50ed022011-02-01 12:02:49 -08004671A send on an unbuffered channel can proceed if a receiver is ready.
4672A send on a buffered channel can proceed if there is room in the buffer.
Russ Coxe7a138b2012-02-08 15:24:48 -05004673A send on a closed channel proceeds by causing a <a href="#Run_time_panics">run-time panic</a>.
Robert Griesemer54731032011-05-12 09:15:59 -07004674A send on a <code>nil</code> channel blocks forever.
Robert Griesemerb50ed022011-02-01 12:02:49 -08004675</p>
4676
4677<pre>
Robert Griesemer97aa90d2014-05-07 10:40:39 -07004678ch &lt;- 3 // send value 3 to channel ch
Robert Griesemerb50ed022011-02-01 12:02:49 -08004679</pre>
4680
Robert Griesemerb50ed022011-02-01 12:02:49 -08004681
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004682<h3 id="IncDec_statements">IncDec statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004683
Rob Pike96750f12009-02-27 16:47:48 -08004684<p>
Robert Griesemer52a54802008-09-30 13:02:50 -07004685The "++" and "--" statements increment or decrement their operands
Robert Griesemer19b1d352009-09-24 19:36:48 -07004686by the untyped <a href="#Constants">constant</a> <code>1</code>.
Robert Griesemer5474e162010-09-28 14:44:19 -07004687As with an assignment, the operand must be <a href="#Address_operators">addressable</a>
4688or a map index expression.
Rob Pike96750f12009-02-27 16:47:48 -08004689</p>
Robert Griesemer52a54802008-09-30 13:02:50 -07004690
Robert Griesemerf7ac31362009-07-10 16:06:40 -07004691<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07004692IncDecStmt = Expression ( "++" | "--" ) .
Robert Griesemerc2d55862009-02-19 16:49:10 -08004693</pre>
Russ Cox5958dd62009-03-04 17:19:21 -08004694
Rob Pike96750f12009-02-27 16:47:48 -08004695<p>
Robert Griesemer506c0082009-09-08 15:41:14 -07004696The following <a href="#Assignments">assignment statements</a> are semantically
Robert Griesemer52a54802008-09-30 13:02:50 -07004697equivalent:
Rob Pike96750f12009-02-27 16:47:48 -08004698</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004699
Rob Pikeff70f092009-02-20 13:36:14 -08004700<pre class="grammar">
Robert Griesemerc2d55862009-02-19 16:49:10 -08004701IncDec statement Assignment
4702x++ x += 1
4703x-- x -= 1
4704</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004705
Robert Griesemer5474e162010-09-28 14:44:19 -07004706
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004707<h3 id="Assignments">Assignments</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004708
Robert Griesemerf7ac31362009-07-10 16:06:40 -07004709<pre class="ebnf">
Robert Griesemerc2d55862009-02-19 16:49:10 -08004710Assignment = ExpressionList assign_op ExpressionList .
Rob Pikeff70f092009-02-20 13:36:14 -08004711
Robert Griesemerc2d55862009-02-19 16:49:10 -08004712assign_op = [ add_op | mul_op ] "=" .
4713</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004714
Rob Pike96750f12009-02-27 16:47:48 -08004715<p>
Rob Pike678625d2009-09-15 09:54:22 -07004716Each left-hand side operand must be <a href="#Address_operators">addressable</a>,
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05004717a map index expression, or (for <code>=</code> assignments only) the
4718<a href="#Blank_identifier">blank identifier</a>.
Robert Griesemer6af887e2011-05-02 09:16:31 -07004719Operands may be parenthesized.
Rob Pike96750f12009-02-27 16:47:48 -08004720</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004721
Robert Griesemerc2d55862009-02-19 16:49:10 -08004722<pre>
4723x = 1
4724*p = f()
4725a[i] = 23
Robert Griesemer6af887e2011-05-02 09:16:31 -07004726(k) = &lt;-ch // same as: k = &lt;-ch
Robert Griesemerc2d55862009-02-19 16:49:10 -08004727</pre>
Rob Pike96750f12009-02-27 16:47:48 -08004728
4729<p>
4730An <i>assignment operation</i> <code>x</code> <i>op</i><code>=</code>
Robert Griesemer26e726c2017-03-10 17:17:23 -08004731<code>y</code> where <i>op</i> is a binary <a href="#Arithmetic_operators">arithmetic operator</a>
4732is equivalent to <code>x</code> <code>=</code> <code>x</code> <i>op</i>
Robert Griesemer637d5982015-06-11 13:21:46 -07004733<code>(y)</code> but evaluates <code>x</code>
Rob Pike96750f12009-02-27 16:47:48 -08004734only once. The <i>op</i><code>=</code> construct is a single token.
Rob Pike678625d2009-09-15 09:54:22 -07004735In assignment operations, both the left- and right-hand expression lists
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05004736must contain exactly one single-valued expression, and the left-hand
4737expression must not be the blank identifier.
Rob Pike96750f12009-02-27 16:47:48 -08004738</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004739
Robert Griesemerc2d55862009-02-19 16:49:10 -08004740<pre>
Robert Griesemer4ed666e2009-08-27 16:45:42 -07004741a[i] &lt;&lt;= 2
Rob Pike678625d2009-09-15 09:54:22 -07004742i &amp;^= 1&lt;&lt;n
Robert Griesemerc2d55862009-02-19 16:49:10 -08004743</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004744
Rob Pike96750f12009-02-27 16:47:48 -08004745<p>
4746A tuple assignment assigns the individual elements of a multi-valued
4747operation to a list of variables. There are two forms. In the
4748first, the right hand operand is a single multi-valued expression
Robert Griesemer47094dc2014-09-30 11:44:29 -07004749such as a function call, a <a href="#Channel_types">channel</a> or
4750<a href="#Map_types">map</a> operation, or a <a href="#Type_assertions">type assertion</a>.
Russ Cox5958dd62009-03-04 17:19:21 -08004751The number of operands on the left
Robert Griesemer4e56b332009-09-10 10:14:00 -07004752hand side must match the number of values. For instance, if
Rob Pike96750f12009-02-27 16:47:48 -08004753<code>f</code> is a function returning two values,
4754</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004755
Robert Griesemerc2d55862009-02-19 16:49:10 -08004756<pre>
4757x, y = f()
4758</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004759
Rob Pike96750f12009-02-27 16:47:48 -08004760<p>
4761assigns the first value to <code>x</code> and the second to <code>y</code>.
Rob Pike96750f12009-02-27 16:47:48 -08004762In the second form, the number of operands on the left must equal the number
Robert Griesemeref45e642009-08-21 11:25:00 -07004763of expressions on the right, each of which must be single-valued, and the
4764<i>n</i>th expression on the right is assigned to the <i>n</i>th
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05004765operand on the left:
Robert Griesemer2dde4f52012-05-24 10:59:48 -07004766</p>
4767
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05004768<pre>
4769one, two, three = '一', '二', '三'
4770</pre>
4771
4772<p>
4773The <a href="#Blank_identifier">blank identifier</a> provides a way to
4774ignore right-hand side values in an assignment:
4775</p>
4776
4777<pre>
4778_ = x // evaluate x but ignore it
4779x, _ = f() // evaluate f() but ignore second result value
4780</pre>
4781
Robert Griesemer2dde4f52012-05-24 10:59:48 -07004782<p>
4783The assignment proceeds in two phases.
Robert Griesemer9c9e8112012-12-10 11:55:57 -08004784First, the operands of <a href="#Index_expressions">index expressions</a>
Russ Coxfa538112011-10-13 15:44:17 -04004785and <a href="#Address_operators">pointer indirections</a>
4786(including implicit pointer indirections in <a href="#Selectors">selectors</a>)
4787on the left and the expressions on the right are all
4788<a href="#Order_of_evaluation">evaluated in the usual order</a>.
4789Second, the assignments are carried out in left-to-right order.
Rob Pike96750f12009-02-27 16:47:48 -08004790</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004791
Robert Griesemerc2d55862009-02-19 16:49:10 -08004792<pre>
Rob Pike96750f12009-02-27 16:47:48 -08004793a, b = b, a // exchange a and b
Russ Coxfa538112011-10-13 15:44:17 -04004794
4795x := []int{1, 2, 3}
4796i := 0
David Symonds72a29792011-11-29 15:47:36 -08004797i, x[i] = 1, 2 // set i = 1, x[0] = 2
Russ Coxfa538112011-10-13 15:44:17 -04004798
4799i = 0
4800x[i], i = 2, 1 // set x[0] = 2, i = 1
4801
Robert Griesemer2dde4f52012-05-24 10:59:48 -07004802x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end)
Russ Coxfa538112011-10-13 15:44:17 -04004803
David Symonds72a29792011-11-29 15:47:36 -08004804x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5.
Russ Coxfa538112011-10-13 15:44:17 -04004805
4806type Point struct { x, y int }
4807var p *Point
4808x[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7
Robert Griesemer2dde4f52012-05-24 10:59:48 -07004809
4810i = 2
4811x = []int{3, 5, 7}
4812for i, x[i] = range x { // set i, x[2] = 0, x[0]
4813 break
4814}
4815// after this loop, i == 0 and x == []int{3, 5, 3}
Robert Griesemerc2d55862009-02-19 16:49:10 -08004816</pre>
Rob Pike96750f12009-02-27 16:47:48 -08004817
4818<p>
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05004819In assignments, each value must be <a href="#Assignability">assignable</a>
4820to the type of the operand to which it is assigned, with the following special cases:
Rob Pike96750f12009-02-27 16:47:48 -08004821</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004822
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05004823<ol>
Robert Griesemer47094dc2014-09-30 11:44:29 -07004824<li>
4825 Any typed value may be assigned to the blank identifier.
4826</li>
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05004827
Robert Griesemer47094dc2014-09-30 11:44:29 -07004828<li>
4829 If an untyped constant
4830 is assigned to a variable of interface type or the blank identifier,
Robert Griesemer26d22602018-10-02 15:55:38 -07004831 the constant is first implicitly <a href="#Conversions">converted</a> to its
Robert Griesemer47094dc2014-09-30 11:44:29 -07004832 <a href="#Constants">default type</a>.
4833</li>
4834
4835<li>
4836 If an untyped boolean value is assigned to a variable of interface type or
Robert Griesemer26d22602018-10-02 15:55:38 -07004837 the blank identifier, it is first implicitly converted to type <code>bool</code>.
Robert Griesemer47094dc2014-09-30 11:44:29 -07004838</li>
Robert Griesemerf57bf7a2013-11-12 21:06:54 -05004839</ol>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004840
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004841<h3 id="If_statements">If statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004842
Rob Pike96750f12009-02-27 16:47:48 -08004843<p>
4844"If" statements specify the conditional execution of two branches
4845according to the value of a boolean expression. If the expression
4846evaluates to true, the "if" branch is executed, otherwise, if
Robert Griesemera1368a62011-02-22 15:31:57 -08004847present, the "else" branch is executed.
Rob Pike96750f12009-02-27 16:47:48 -08004848</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004849
Robert Griesemerf7ac31362009-07-10 16:06:40 -07004850<pre class="ebnf">
Russ Cox58e19aa2011-07-14 17:15:52 -04004851IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
Robert Griesemerc2d55862009-02-19 16:49:10 -08004852</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004853
Robert Griesemerc2d55862009-02-19 16:49:10 -08004854<pre>
Robert Griesemera1368a62011-02-22 15:31:57 -08004855if x &gt; max {
4856 x = max
Robert Griesemerc2d55862009-02-19 16:49:10 -08004857}
4858</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004859
Russ Cox5958dd62009-03-04 17:19:21 -08004860<p>
Russ Cox16b95ba2009-08-20 10:22:52 -07004861The expression may be preceded by a simple statement, which
4862executes before the expression is evaluated.
Russ Cox5958dd62009-03-04 17:19:21 -08004863</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004864
Robert Griesemerc2d55862009-02-19 16:49:10 -08004865<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08004866if x := f(); x &lt; y {
4867 return x
Robert Griesemera1368a62011-02-22 15:31:57 -08004868} else if x &gt; z {
Robert Griesemer130ac742009-12-10 16:43:01 -08004869 return z
Robert Griesemerc2d55862009-02-19 16:49:10 -08004870} else {
Robert Griesemer130ac742009-12-10 16:43:01 -08004871 return y
Robert Griesemerc2d55862009-02-19 16:49:10 -08004872}
4873</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004874
4875
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004876<h3 id="Switch_statements">Switch statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004877
Rob Pike96750f12009-02-27 16:47:48 -08004878<p>
4879"Switch" statements provide multi-way execution.
Rob Pike5a578492009-03-17 16:48:35 -07004880An expression or type specifier is compared to the "cases"
4881inside the "switch" to determine which branch
4882to execute.
Rob Pikeafee1c52009-03-20 17:41:25 -07004883</p>
Robert Griesemer091cba82009-03-19 08:39:40 -07004884
Robert Griesemerf7ac31362009-07-10 16:06:40 -07004885<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07004886SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
Robert Griesemer091cba82009-03-19 08:39:40 -07004887</pre>
4888
Rob Pikeafee1c52009-03-20 17:41:25 -07004889<p>
Rob Pike5a578492009-03-17 16:48:35 -07004890There are two forms: expression switches and type switches.
Rob Pike5a578492009-03-17 16:48:35 -07004891In an expression switch, the cases contain expressions that are compared
4892against the value of the switch expression.
4893In a type switch, the cases contain types that are compared against the
4894type of a specially annotated switch expression.
Robert Griesemer2d9378c2015-07-27 13:30:16 -07004895The switch expression is evaluated exactly once in a switch statement.
Rob Pike96750f12009-02-27 16:47:48 -08004896</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004897
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004898<h4 id="Expression_switches">Expression switches</h4>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004899
Rob Pike96750f12009-02-27 16:47:48 -08004900<p>
Rob Pike5a578492009-03-17 16:48:35 -07004901In an expression switch,
4902the switch expression is evaluated and
4903the case expressions, which need not be constants,
Robert Griesemer4f185492009-05-01 17:00:16 -07004904are evaluated left-to-right and top-to-bottom; the first one that equals the
Rob Pike5a578492009-03-17 16:48:35 -07004905switch expression
Rob Pike96750f12009-02-27 16:47:48 -08004906triggers execution of the statements of the associated case;
4907the other cases are skipped.
Rob Pike5a578492009-03-17 16:48:35 -07004908If no case matches and there is a "default" case,
4909its statements are executed.
Rob Pike96750f12009-02-27 16:47:48 -08004910There can be at most one default case and it may appear anywhere in the
4911"switch" statement.
Robert Griesemerab266232014-02-25 09:13:37 -08004912A missing switch expression is equivalent to the boolean value
4913<code>true</code>.
Rob Pike96750f12009-02-27 16:47:48 -08004914</p>
Rob Pike70c1a102009-03-18 19:23:59 -07004915
Robert Griesemerf7ac31362009-07-10 16:06:40 -07004916<pre class="ebnf">
Rob Pikef3a33bc2009-09-14 17:39:17 -07004917ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
Robert Griesemer9905cec2013-03-04 13:55:35 -08004918ExprCaseClause = ExprSwitchCase ":" StatementList .
Robert Griesemer091cba82009-03-19 08:39:40 -07004919ExprSwitchCase = "case" ExpressionList | "default" .
Rob Pike70c1a102009-03-18 19:23:59 -07004920</pre>
4921
Rob Pike96750f12009-02-27 16:47:48 -08004922<p>
Robert Griesemer26d22602018-10-02 15:55:38 -07004923If the switch expression evaluates to an untyped constant, it is first implicitly
Robert Griesemer2d9378c2015-07-27 13:30:16 -07004924<a href="#Conversions">converted</a> to its <a href="#Constants">default type</a>;
Robert Griesemer26d22602018-10-02 15:55:38 -07004925if it is an untyped boolean value, it is first implicitly converted to type <code>bool</code>.
Robert Griesemer2d9378c2015-07-27 13:30:16 -07004926The predeclared untyped value <code>nil</code> cannot be used as a switch expression.
4927</p>
4928
4929<p>
Robert Griesemer26d22602018-10-02 15:55:38 -07004930If a case expression is untyped, it is first implicitly <a href="#Conversions">converted</a>
Robert Griesemer2d9378c2015-07-27 13:30:16 -07004931to the type of the switch expression.
4932For each (possibly converted) case expression <code>x</code> and the value <code>t</code>
4933of the switch expression, <code>x == t</code> must be a valid <a href="#Comparison_operators">comparison</a>.
4934</p>
4935
4936<p>
4937In other words, the switch expression is treated as if it were used to declare and
4938initialize a temporary variable <code>t</code> without explicit type; it is that
4939value of <code>t</code> against which each case expression <code>x</code> is tested
4940for equality.
4941</p>
4942
4943<p>
Robert Griesemer67a6b4f2013-03-01 16:45:14 -08004944In a case or default clause, the last non-empty statement
4945may be a (possibly <a href="#Labeled_statements">labeled</a>)
4946<a href="#Fallthrough_statements">"fallthrough" statement</a> to
Rob Pike96750f12009-02-27 16:47:48 -08004947indicate that control should flow from the end of this clause to
Robert Griesemeraed247f2008-10-08 17:05:30 -07004948the first statement of the next clause.
Rob Pike96750f12009-02-27 16:47:48 -08004949Otherwise control flows to the end of the "switch" statement.
Robert Griesemer67a6b4f2013-03-01 16:45:14 -08004950A "fallthrough" statement may appear as the last statement of all
4951but the last clause of an expression switch.
Rob Pike96750f12009-02-27 16:47:48 -08004952</p>
Robert Griesemer0a162a12009-08-19 16:44:04 -07004953
Robert Griesemerc2d55862009-02-19 16:49:10 -08004954<p>
Robert Griesemer2d9378c2015-07-27 13:30:16 -07004955The switch expression may be preceded by a simple statement, which
Russ Cox16b95ba2009-08-20 10:22:52 -07004956executes before the expression is evaluated.
Rob Pike96750f12009-02-27 16:47:48 -08004957</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004958
Robert Griesemerc2d55862009-02-19 16:49:10 -08004959<pre>
4960switch tag {
Rob Pike65ec16b2009-05-29 15:46:03 -07004961default: s3()
4962case 0, 1, 2, 3: s1()
4963case 4, 5, 6, 7: s2()
Robert Griesemerc2d55862009-02-19 16:49:10 -08004964}
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004965
Andrew Gerrand10b77f72010-03-29 13:12:08 +11004966switch x := f(); { // missing switch expression means "true"
Rob Pike65ec16b2009-05-29 15:46:03 -07004967case x &lt; 0: return -x
4968default: return x
Robert Griesemerc2d55862009-02-19 16:49:10 -08004969}
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004970
Robert Griesemere9192752009-12-01 16:15:53 -08004971switch {
Robert Griesemer130ac742009-12-10 16:43:01 -08004972case x &lt; y: f1()
4973case x &lt; z: f2()
4974case x == 4: f3()
Robert Griesemerc2d55862009-02-19 16:49:10 -08004975}
4976</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07004977
Robert Griesemer2d9378c2015-07-27 13:30:16 -07004978<p>
4979Implementation restriction: A compiler may disallow multiple case
4980expressions evaluating to the same constant.
4981For instance, the current compilers disallow duplicate integer,
4982floating point, or string constants in case expressions.
4983</p>
4984
Russ Cox7c4f7cc2009-08-20 11:11:03 -07004985<h4 id="Type_switches">Type switches</h4>
Rob Pike70c1a102009-03-18 19:23:59 -07004986
Rob Pike5a578492009-03-17 16:48:35 -07004987<p>
Rob Pike70c1a102009-03-18 19:23:59 -07004988A type switch compares types rather than values. It is otherwise similar
Robert Griesemer1f95f0d2009-08-27 16:44:17 -07004989to an expression switch. It is marked by a special switch expression that
Robert Griesemer9ecd30a2009-08-27 14:22:51 -07004990has the form of a <a href="#Type_assertions">type assertion</a>
Robert Griesemer48567312012-12-06 09:17:20 -08004991using the reserved word <code>type</code> rather than an actual type:
4992</p>
4993
4994<pre>
4995switch x.(type) {
4996// cases
4997}
4998</pre>
4999
5000<p>
5001Cases then match actual types <code>T</code> against the dynamic type of the
5002expression <code>x</code>. As with type assertions, <code>x</code> must be of
5003<a href="#Interface_types">interface type</a>, and each non-interface type
5004<code>T</code> listed in a case must implement the type of <code>x</code>.
Robert Griesemer3d81d4a2016-05-31 13:32:34 -07005005The types listed in the cases of a type switch must all be
5006<a href="#Type_identity">different</a>.
Rob Pike5a578492009-03-17 16:48:35 -07005007</p>
5008
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005009<pre class="ebnf">
Rob Pikef3a33bc2009-09-14 17:39:17 -07005010TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
Russ Coxc1045db2009-12-23 13:48:44 -08005011TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
Robert Griesemer9905cec2013-03-04 13:55:35 -08005012TypeCaseClause = TypeSwitchCase ":" StatementList .
Rob Pike678625d2009-09-15 09:54:22 -07005013TypeSwitchCase = "case" TypeList | "default" .
5014TypeList = Type { "," Type } .
Rob Pike5a578492009-03-17 16:48:35 -07005015</pre>
5016
5017<p>
Robert Griesemer9ecd30a2009-08-27 14:22:51 -07005018The TypeSwitchGuard may include a
5019<a href="#Short_variable_declarations">short variable declaration</a>.
Robert Griesemerf8555ea2016-08-18 13:14:30 -07005020When that form is used, the variable is declared at the end of the
5021TypeSwitchCase in the <a href="#Blocks">implicit block</a> of each clause.
Robert Griesemer9ecd30a2009-08-27 14:22:51 -07005022In clauses with a case listing exactly one type, the variable
5023has that type; otherwise, the variable has the type of the expression
5024in the TypeSwitchGuard.
Rob Pike94b67eb2009-03-24 17:40:47 -07005025</p>
5026
5027<p>
griesemer84ac90e2017-08-24 15:05:53 +02005028Instead of a type, a case may use the predeclared identifier
5029<a href="#Predeclared_identifiers"><code>nil</code></a>;
5030that case is selected when the expression in the TypeSwitchGuard
Robert Griesemer1f95f0d2009-08-27 16:44:17 -07005031is a <code>nil</code> interface value.
Robert Griesemer3d81d4a2016-05-31 13:32:34 -07005032There may be at most one <code>nil</code> case.
Robert Griesemer9ecd30a2009-08-27 14:22:51 -07005033</p>
5034
5035<p>
Robert Griesemere9192752009-12-01 16:15:53 -08005036Given an expression <code>x</code> of type <code>interface{}</code>,
Rob Pike70c1a102009-03-18 19:23:59 -07005037the following type switch:
Rob Pike5a578492009-03-17 16:48:35 -07005038</p>
5039
5040<pre>
Robert Griesemere9192752009-12-01 16:15:53 -08005041switch i := x.(type) {
Rob Pike94b67eb2009-03-24 17:40:47 -07005042case nil:
Robert Griesemer48567312012-12-06 09:17:20 -08005043 printString("x is nil") // type of i is type of x (interface{})
Rob Pike5a578492009-03-17 16:48:35 -07005044case int:
Robert Griesemer48567312012-12-06 09:17:20 -08005045 printInt(i) // type of i is int
Robert Griesemerb94c0d22011-01-19 23:07:21 -05005046case float64:
Robert Griesemer48567312012-12-06 09:17:20 -08005047 printFloat64(i) // type of i is float64
Robert Griesemerb94c0d22011-01-19 23:07:21 -05005048case func(int) float64:
Robert Griesemer48567312012-12-06 09:17:20 -08005049 printFunction(i) // type of i is func(int) float64
Robert Griesemer9ecd30a2009-08-27 14:22:51 -07005050case bool, string:
Robert Griesemer48567312012-12-06 09:17:20 -08005051 printString("type is bool or string") // type of i is type of x (interface{})
Rob Pike5a578492009-03-17 16:48:35 -07005052default:
Robert Griesemer48567312012-12-06 09:17:20 -08005053 printString("don't know the type") // type of i is type of x (interface{})
Rob Pike5a578492009-03-17 16:48:35 -07005054}
5055</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005056
Rob Pike70c1a102009-03-18 19:23:59 -07005057<p>
5058could be rewritten:
5059</p>
5060
5061<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08005062v := x // x is evaluated exactly once
Rob Pike94b67eb2009-03-24 17:40:47 -07005063if v == nil {
Robert Griesemer48567312012-12-06 09:17:20 -08005064 i := v // type of i is type of x (interface{})
Robert Griesemer130ac742009-12-10 16:43:01 -08005065 printString("x is nil")
Russ Cox9c08d652012-02-21 22:04:30 -05005066} else if i, isInt := v.(int); isInt {
Robert Griesemer48567312012-12-06 09:17:20 -08005067 printInt(i) // type of i is int
Russ Cox9c08d652012-02-21 22:04:30 -05005068} else if i, isFloat64 := v.(float64); isFloat64 {
Robert Griesemer48567312012-12-06 09:17:20 -08005069 printFloat64(i) // type of i is float64
Russ Cox9c08d652012-02-21 22:04:30 -05005070} else if i, isFunc := v.(func(int) float64); isFunc {
Robert Griesemer48567312012-12-06 09:17:20 -08005071 printFunction(i) // type of i is func(int) float64
Rob Pike70c1a102009-03-18 19:23:59 -07005072} else {
Robert Griesemer48567312012-12-06 09:17:20 -08005073 _, isBool := v.(bool)
5074 _, isString := v.(string)
Russ Cox9c08d652012-02-21 22:04:30 -05005075 if isBool || isString {
Robert Griesemer48567312012-12-06 09:17:20 -08005076 i := v // type of i is type of x (interface{})
5077 printString("type is bool or string")
Robert Griesemer9ecd30a2009-08-27 14:22:51 -07005078 } else {
Robert Griesemer48567312012-12-06 09:17:20 -08005079 i := v // type of i is type of x (interface{})
5080 printString("don't know the type")
Robert Griesemer9ecd30a2009-08-27 14:22:51 -07005081 }
Rob Pike70c1a102009-03-18 19:23:59 -07005082}
5083</pre>
5084
Robert Griesemeraeaab592009-08-31 17:30:55 -07005085<p>
Russ Cox16b95ba2009-08-20 10:22:52 -07005086The type switch guard may be preceded by a simple statement, which
5087executes before the guard is evaluated.
Robert Griesemer1f95f0d2009-08-27 16:44:17 -07005088</p>
Robert Griesemer9ecd30a2009-08-27 14:22:51 -07005089
5090<p>
5091The "fallthrough" statement is not permitted in a type switch.
Russ Cox16b95ba2009-08-20 10:22:52 -07005092</p>
5093
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005094<h3 id="For_statements">For statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005095
Rob Pike96750f12009-02-27 16:47:48 -08005096<p>
Robert Griesemerb01f6122016-11-18 10:49:29 -08005097A "for" statement specifies repeated execution of a block. There are three forms:
5098The iteration may be controlled by a single condition, a "for" clause, or a "range" clause.
Rob Pike96750f12009-02-27 16:47:48 -08005099</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005100
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005101<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07005102ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
Robert Griesemerc2d55862009-02-19 16:49:10 -08005103Condition = Expression .
5104</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005105
Robert Griesemerb01f6122016-11-18 10:49:29 -08005106<h4 id="For_condition">For statements with single condition</h4>
5107
Rob Pike96750f12009-02-27 16:47:48 -08005108<p>
5109In its simplest form, a "for" statement specifies the repeated execution of
5110a block as long as a boolean condition evaluates to true.
5111The condition is evaluated before each iteration.
Robert Griesemerab266232014-02-25 09:13:37 -08005112If the condition is absent, it is equivalent to the boolean value
5113<code>true</code>.
Rob Pike96750f12009-02-27 16:47:48 -08005114</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005115
Robert Griesemerc2d55862009-02-19 16:49:10 -08005116<pre>
5117for a &lt; b {
5118 a *= 2
5119}
5120</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005121
Robert Griesemerb01f6122016-11-18 10:49:29 -08005122<h4 id="For_clause">For statements with <code>for</code> clause</h4>
5123
Rob Pike96750f12009-02-27 16:47:48 -08005124<p>
Rob Pike678625d2009-09-15 09:54:22 -07005125A "for" statement with a ForClause is also controlled by its condition, but
Rob Pike96750f12009-02-27 16:47:48 -08005126additionally it may specify an <i>init</i>
5127and a <i>post</i> statement, such as an assignment,
Russ Cox16b95ba2009-08-20 10:22:52 -07005128an increment or decrement statement. The init statement may be a
Robert Griesemer4ed666e2009-08-27 16:45:42 -07005129<a href="#Short_variable_declarations">short variable declaration</a>, but the post statement must not.
Robert Griesemer2fa3e43f2014-09-25 12:52:05 -07005130Variables declared by the init statement are re-used in each iteration.
Rob Pike96750f12009-02-27 16:47:48 -08005131</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005132
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005133<pre class="ebnf">
Robert Griesemer130ac742009-12-10 16:43:01 -08005134ForClause = [ InitStmt ] ";" [ Condition ] ";" [ PostStmt ] .
Rob Pike11417162009-03-24 17:45:53 -07005135InitStmt = SimpleStmt .
5136PostStmt = SimpleStmt .
Robert Griesemerc2d55862009-02-19 16:49:10 -08005137</pre>
Robert Griesemer30a1a8c2008-12-16 11:38:56 -08005138
Robert Griesemerc2d55862009-02-19 16:49:10 -08005139<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08005140for i := 0; i &lt; 10; i++ {
Robert Griesemerc2d55862009-02-19 16:49:10 -08005141 f(i)
5142}
5143</pre>
Russ Cox5958dd62009-03-04 17:19:21 -08005144
Robert Griesemerc2d55862009-02-19 16:49:10 -08005145<p>
Rob Pike96750f12009-02-27 16:47:48 -08005146If non-empty, the init statement is executed once before evaluating the
5147condition for the first iteration;
5148the post statement is executed after each execution of the block (and
5149only if the block was executed).
Robert Griesemer130ac742009-12-10 16:43:01 -08005150Any element of the ForClause may be empty but the
5151<a href="#Semicolons">semicolons</a> are
Rob Pike96750f12009-02-27 16:47:48 -08005152required unless there is only a condition.
Robert Griesemerab266232014-02-25 09:13:37 -08005153If the condition is absent, it is equivalent to the boolean value
5154<code>true</code>.
Rob Pike96750f12009-02-27 16:47:48 -08005155</p>
Robert Griesemer30a1a8c2008-12-16 11:38:56 -08005156
Robert Griesemerc2d55862009-02-19 16:49:10 -08005157<pre>
Rob Pike678625d2009-09-15 09:54:22 -07005158for cond { S() } is the same as for ; cond ; { S() }
5159for { S() } is the same as for true { S() }
Robert Griesemerc2d55862009-02-19 16:49:10 -08005160</pre>
Robert Griesemer30a1a8c2008-12-16 11:38:56 -08005161
Robert Griesemerb01f6122016-11-18 10:49:29 -08005162<h4 id="For_range">For statements with <code>range</code> clause</h4>
5163
Rob Pike96750f12009-02-27 16:47:48 -08005164<p>
5165A "for" statement with a "range" clause
Rob Pike7aee71b2009-04-15 20:28:25 -07005166iterates through all entries of an array, slice, string or map,
Robert Griesemer5474e162010-09-28 14:44:19 -07005167or values received on a channel. For each entry it assigns <i>iteration values</i>
Robert Griesemer20ae6d92014-07-14 15:08:09 -07005168to corresponding <i>iteration variables</i> if present and then executes the block.
Rob Pike96750f12009-02-27 16:47:48 -08005169</p>
Robert Griesemer30a1a8c2008-12-16 11:38:56 -08005170
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005171<pre class="ebnf">
Robert Griesemer20ae6d92014-07-14 15:08:09 -07005172RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .
Robert Griesemerc2d55862009-02-19 16:49:10 -08005173</pre>
Robert Griesemer30a1a8c2008-12-16 11:38:56 -08005174
Robert Griesemerc2d55862009-02-19 16:49:10 -08005175<p>
Robert Griesemer5474e162010-09-28 14:44:19 -07005176The expression on the right in the "range" clause is called the <i>range expression</i>,
Robert Griesemercc3f21c2012-12-03 14:23:41 -08005177which may be an array, pointer to an array, slice, string, map, or channel permitting
5178<a href="#Receive_operator">receive operations</a>.
Robert Griesemer20ae6d92014-07-14 15:08:09 -07005179As with an assignment, if present the operands on the left must be
Robert Griesemer5474e162010-09-28 14:44:19 -07005180<a href="#Address_operators">addressable</a> or map index expressions; they
Robert Griesemer20ae6d92014-07-14 15:08:09 -07005181denote the iteration variables. If the range expression is a channel, at most
5182one iteration variable is permitted, otherwise there may be up to two.
5183If the last iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
5184the range clause is equivalent to the same clause without that identifier.
Robert Griesemer5474e162010-09-28 14:44:19 -07005185</p>
Rob Pike29d0f022011-01-05 11:39:57 -08005186
5187<p>
griesemerada65572017-10-17 15:30:12 -07005188The range expression <code>x</code> is evaluated once before beginning the loop,
5189with one exception: if at most one iteration variable is present and
5190<code>len(x)</code> is <a href="#Length_and_capacity">constant</a>,
5191the range expression is not evaluated.
Russ Cox61e02ee2013-02-15 14:39:28 -05005192</p>
5193
5194<p>
Robert Griesemer5474e162010-09-28 14:44:19 -07005195Function calls on the left are evaluated once per iteration.
Robert Griesemer20ae6d92014-07-14 15:08:09 -07005196For each iteration, iteration values are produced as follows
5197if the respective iteration variables are present:
Robert Griesemer5474e162010-09-28 14:44:19 -07005198</p>
5199
5200<pre class="grammar">
Robert Griesemer20ae6d92014-07-14 15:08:09 -07005201Range expression 1st value 2nd value
Robert Griesemer5474e162010-09-28 14:44:19 -07005202
5203array or slice a [n]E, *[n]E, or []E index i int a[i] E
Robert Griesemerb910a272011-11-01 01:09:22 -04005204string s string type index i int see below rune
Robert Griesemer5474e162010-09-28 14:44:19 -07005205map m map[K]V key k K m[k] V
Shenghou Maced57152013-01-17 23:11:25 +08005206channel c chan E, &lt;-chan E element e E
Robert Griesemer5474e162010-09-28 14:44:19 -07005207</pre>
5208
5209<ol>
5210<li>
Robert Griesemer54731032011-05-12 09:15:59 -07005211For an array, pointer to array, or slice value <code>a</code>, the index iteration
Russ Cox61e02ee2013-02-15 14:39:28 -05005212values are produced in increasing order, starting at element index 0.
Robert Griesemer20ae6d92014-07-14 15:08:09 -07005213If at most one iteration variable is present, the range loop produces
Robert Griesemerbb3a32e2013-05-20 13:27:53 -07005214iteration values from 0 up to <code>len(a)-1</code> and does not index into the array
Robert Griesemer54731032011-05-12 09:15:59 -07005215or slice itself. For a <code>nil</code> slice, the number of iterations is 0.
Robert Griesemer5474e162010-09-28 14:44:19 -07005216</li>
5217
5218<li>
5219For a string value, the "range" clause iterates over the Unicode code points
5220in the string starting at byte index 0. On successive iterations, the index value will be the
5221index of the first byte of successive UTF-8-encoded code points in the string,
Robert Griesemerb910a272011-11-01 01:09:22 -04005222and the second value, of type <code>rune</code>, will be the value of
Rob Pike7aee71b2009-04-15 20:28:25 -07005223the corresponding code point. If the iteration encounters an invalid
Robert Griesemer5474e162010-09-28 14:44:19 -07005224UTF-8 sequence, the second value will be <code>0xFFFD</code>,
Rob Pike7aee71b2009-04-15 20:28:25 -07005225the Unicode replacement character, and the next iteration will advance
5226a single byte in the string.
Robert Griesemer5474e162010-09-28 14:44:19 -07005227</li>
5228
5229<li>
Russ Coxe40d6e02011-10-17 18:49:02 -04005230The iteration order over maps is not specified
5231and is not guaranteed to be the same from one iteration to the next.
Robert Griesemer4e9c86a2017-06-28 10:15:24 -07005232If a map entry that has not yet been reached is removed during iteration,
5233the corresponding iteration value will not be produced. If a map entry is
Shenghou Maced57152013-01-17 23:11:25 +08005234created during iteration, that entry may be produced during the iteration or
5235may be skipped. The choice may vary for each entry created and from one
5236iteration to the next.
5237If the map is <code>nil</code>, the number of iterations is 0.
Robert Griesemer5474e162010-09-28 14:44:19 -07005238</li>
5239
5240<li>
5241For channels, the iteration values produced are the successive values sent on
Robert Griesemer54731032011-05-12 09:15:59 -07005242the channel until the channel is <a href="#Close">closed</a>. If the channel
5243is <code>nil</code>, the range expression blocks forever.
Robert Griesemer5474e162010-09-28 14:44:19 -07005244</li>
Anthony Martin0122a662011-02-08 14:51:15 -08005245</ol>
Robert Griesemer5474e162010-09-28 14:44:19 -07005246
Rob Pike7aee71b2009-04-15 20:28:25 -07005247<p>
Robert Griesemer5474e162010-09-28 14:44:19 -07005248The iteration values are assigned to the respective
5249iteration variables as in an <a href="#Assignments">assignment statement</a>.
Rob Pike94b67eb2009-03-24 17:40:47 -07005250</p>
Robert Griesemer5474e162010-09-28 14:44:19 -07005251
Rob Pike94b67eb2009-03-24 17:40:47 -07005252<p>
Robert Griesemerda633712012-02-29 09:06:05 -08005253The iteration variables may be declared by the "range" clause using a form of
Robert Griesemer2c9e1632012-02-28 17:44:24 -08005254<a href="#Short_variable_declarations">short variable declaration</a>
5255(<code>:=</code>).
Robert Griesemer5474e162010-09-28 14:44:19 -07005256In this case their types are set to the types of the respective iteration values
Robert Griesemer2fa3e43f2014-09-25 12:52:05 -07005257and their <a href="#Declarations_and_scope">scope</a> is the block of the "for"
Robert Griesemer5474e162010-09-28 14:44:19 -07005258statement; they are re-used in each iteration.
Rob Pike96750f12009-02-27 16:47:48 -08005259If the iteration variables are declared outside the "for" statement,
5260after execution their values will be those of the last iteration.
5261</p>
Robert Griesemer30a1a8c2008-12-16 11:38:56 -08005262
Robert Griesemerc2d55862009-02-19 16:49:10 -08005263<pre>
Robert Griesemer54731032011-05-12 09:15:59 -07005264var testdata *struct {
5265 a *[7]int
5266}
5267for i, _ := range testdata.a {
5268 // testdata.a is never evaluated; len(testdata.a) is constant
5269 // i ranges from 0 to 6
5270 f(i)
5271}
5272
Robert Griesemer130ac742009-12-10 16:43:01 -08005273var a [10]string
Robert Griesemerc2d55862009-02-19 16:49:10 -08005274for i, s := range a {
5275 // type of i is int
5276 // type of s is string
5277 // s == a[i]
5278 g(i, s)
5279}
5280
Robert Griesemer130ac742009-12-10 16:43:01 -08005281var key string
Robert Griesemer9ead7722020-01-13 13:01:28 -08005282var val interface{} // element type of m is assignable to val
Robert Griesemer63f54ae2013-07-11 14:41:46 -07005283m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}
Rob Pike678625d2009-09-15 09:54:22 -07005284for key, val = range m {
5285 h(key, val)
Robert Griesemerc2d55862009-02-19 16:49:10 -08005286}
5287// key == last map key encountered in iteration
5288// val == map[key]
Robert Griesemer54731032011-05-12 09:15:59 -07005289
5290var ch chan Work = producer()
5291for w := range ch {
5292 doWork(w)
5293}
Robert Griesemer20ae6d92014-07-14 15:08:09 -07005294
5295// empty a channel
5296for range ch {}
Robert Griesemerc2d55862009-02-19 16:49:10 -08005297</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005298
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005299
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005300<h3 id="Go_statements">Go statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005301
Rob Pike96750f12009-02-27 16:47:48 -08005302<p>
Robert Griesemer25dd0022012-11-29 11:46:25 -08005303A "go" statement starts the execution of a function call
Rob Pike96750f12009-02-27 16:47:48 -08005304as an independent concurrent thread of control, or <i>goroutine</i>,
5305within the same address space.
5306</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005307
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005308<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07005309GoStmt = "go" Expression .
Robert Griesemerc2d55862009-02-19 16:49:10 -08005310</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005311
Rob Pike96750f12009-02-27 16:47:48 -08005312<p>
Robert Griesemer25dd0022012-11-29 11:46:25 -08005313The expression must be a function or method call; it cannot be parenthesized.
5314Calls of built-in functions are restricted as for
5315<a href="#Expression_statements">expression statements</a>.
5316</p>
5317
5318<p>
Rob Pike633a2ce2012-01-23 08:40:13 -08005319The function value and parameters are
5320<a href="#Calls">evaluated as usual</a>
5321in the calling goroutine, but
Rob Pike96750f12009-02-27 16:47:48 -08005322unlike with a regular call, program execution does not wait
Robert Griesemerb9f8b9c2008-09-26 13:38:38 -07005323for the invoked function to complete.
Rob Pike633a2ce2012-01-23 08:40:13 -08005324Instead, the function begins executing independently
5325in a new goroutine.
5326When the function terminates, its goroutine also terminates.
5327If the function has any return values, they are discarded when the
5328function completes.
Rob Pike96750f12009-02-27 16:47:48 -08005329</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005330
Robert Griesemerc2d55862009-02-19 16:49:10 -08005331<pre>
5332go Server()
Brad Fitzpatricke9635102017-05-04 02:39:56 +00005333go func(ch chan&lt;- bool) { for { sleep(10); ch &lt;- true }} (c)
Robert Griesemerc2d55862009-02-19 16:49:10 -08005334</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005335
5336
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005337<h3 id="Select_statements">Select statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005338
Rob Pike96750f12009-02-27 16:47:48 -08005339<p>
Robert Griesemer61d8a332014-05-14 11:47:19 -07005340A "select" statement chooses which of a set of possible
5341<a href="#Send_statements">send</a> or
5342<a href="#Receive_operator">receive</a>
5343operations will proceed.
5344It looks similar to a
5345<a href="#Switch_statements">"switch"</a> statement but with the
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005346cases all referring to communication operations.
Rob Pike96750f12009-02-27 16:47:48 -08005347</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005348
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005349<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07005350SelectStmt = "select" "{" { CommClause } "}" .
Robert Griesemer9905cec2013-03-04 13:55:35 -08005351CommClause = CommCase ":" StatementList .
Robert Griesemerb50ed022011-02-01 12:02:49 -08005352CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
Robert Griesemerd3679722013-01-18 13:59:25 -08005353RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
Robert Griesemerc1347182011-04-29 12:20:31 -07005354RecvExpr = Expression .
Russ Cox61439182011-01-31 17:42:10 -05005355</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005356
Rob Pike96750f12009-02-27 16:47:48 -08005357<p>
Robert Griesemer61d8a332014-05-14 11:47:19 -07005358A case with a RecvStmt may assign the result of a RecvExpr to one or
5359two variables, which may be declared using a
Robert Griesemer4ed666e2009-08-27 16:45:42 -07005360<a href="#Short_variable_declarations">short variable declaration</a>.
Robert Griesemer61d8a332014-05-14 11:47:19 -07005361The RecvExpr must be a (possibly parenthesized) receive operation.
5362There can be at most one default case and it may appear anywhere
5363in the list of cases.
5364</p>
5365
5366<p>
5367Execution of a "select" statement proceeds in several steps:
5368</p>
5369
5370<ol>
5371<li>
5372For all the cases in the statement, the channel operands of receive operations
5373and the channel and right-hand-side expressions of send statements are
5374evaluated exactly once, in source order, upon entering the "select" statement.
5375The result is a set of channels to receive from or send to,
5376and the corresponding values to send.
5377Any side effects in that evaluation will occur irrespective of which (if any)
5378communication operation is selected to proceed.
5379Expressions on the left-hand side of a RecvStmt with a short variable declaration
5380or assignment are not yet evaluated.
5381</li>
5382
5383<li>
5384If one or more of the communications can proceed,
5385a single one that can proceed is chosen via a uniform pseudo-random selection.
5386Otherwise, if there is a default case, that case is chosen.
5387If there is no default case, the "select" statement blocks until
5388at least one of the communications can proceed.
5389</li>
5390
5391<li>
5392Unless the selected case is the default case, the respective communication
5393operation is executed.
5394</li>
5395
5396<li>
5397If the selected case is a RecvStmt with a short variable declaration or
5398an assignment, the left-hand side expressions are evaluated and the
5399received value (or values) are assigned.
5400</li>
5401
5402<li>
5403The statement list of the selected case is executed.
5404</li>
5405</ol>
5406
5407<p>
5408Since communication on <code>nil</code> channels can never proceed,
5409a select with only <code>nil</code> channels and no default case blocks forever.
Rob Pike96750f12009-02-27 16:47:48 -08005410</p>
Robert Griesemer2902a822008-09-17 13:57:11 -07005411
Robert Griesemerc2d55862009-02-19 16:49:10 -08005412<pre>
Robert Griesemer61d8a332014-05-14 11:47:19 -07005413var a []int
5414var c, c1, c2, c3, c4 chan int
Robert Griesemer130ac742009-12-10 16:43:01 -08005415var i1, i2 int
Robert Griesemerc2d55862009-02-19 16:49:10 -08005416select {
5417case i1 = &lt;-c1:
Robert Griesemer130ac742009-12-10 16:43:01 -08005418 print("received ", i1, " from c1\n")
Robert Griesemerc2d55862009-02-19 16:49:10 -08005419case c2 &lt;- i2:
Robert Griesemer130ac742009-12-10 16:43:01 -08005420 print("sent ", i2, " to c2\n")
Robert Griesemer6af887e2011-05-02 09:16:31 -07005421case i3, ok := (&lt;-c3): // same as: i3, ok := &lt;-c3
Russ Cox19d9a402011-01-27 15:34:28 -05005422 if ok {
5423 print("received ", i3, " from c3\n")
5424 } else {
5425 print("c3 is closed\n")
5426 }
Robert Griesemer61d8a332014-05-14 11:47:19 -07005427case a[f()] = &lt;-c4:
5428 // same as:
5429 // case t := &lt;-c4
5430 // a[f()] = t
Robert Griesemerc2d55862009-02-19 16:49:10 -08005431default:
Robert Griesemer130ac742009-12-10 16:43:01 -08005432 print("no communication\n")
Robert Griesemerc2d55862009-02-19 16:49:10 -08005433}
5434
5435for { // send random sequence of bits to c
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005436 select {
Robert Griesemerc2d55862009-02-19 16:49:10 -08005437 case c &lt;- 0: // note: no statement, no fallthrough, no folding of cases
5438 case c &lt;- 1:
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005439 }
Robert Griesemerc2d55862009-02-19 16:49:10 -08005440}
Rob Pike041d1162010-07-13 16:23:54 -07005441
David Symonds72a29792011-11-29 15:47:36 -08005442select {} // block forever
Robert Griesemerc2d55862009-02-19 16:49:10 -08005443</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005444
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005445
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005446<h3 id="Return_statements">Return statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005447
Rob Pike96750f12009-02-27 16:47:48 -08005448<p>
Robert Griesemer1e8e14c2012-11-01 10:13:48 -07005449A "return" statement in a function <code>F</code> terminates the execution
5450of <code>F</code>, and optionally provides one or more result values.
5451Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
5452are executed before <code>F</code> returns to its caller.
Rob Pike96750f12009-02-27 16:47:48 -08005453</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005454
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005455<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07005456ReturnStmt = "return" [ ExpressionList ] .
Robert Griesemerc2d55862009-02-19 16:49:10 -08005457</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005458
Robert Griesemer4b908332009-08-07 17:05:41 -07005459<p>
5460In a function without a result type, a "return" statement must not
5461specify any result values.
5462</p>
Rob Pike96750f12009-02-27 16:47:48 -08005463<pre>
Russ Cox9c08d652012-02-21 22:04:30 -05005464func noResult() {
Rob Pike96750f12009-02-27 16:47:48 -08005465 return
5466}
5467</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005468
Rob Pike96750f12009-02-27 16:47:48 -08005469<p>
Robert Griesemer4b908332009-08-07 17:05:41 -07005470There are three ways to return values from a function with a result
5471type:
Rob Pike96750f12009-02-27 16:47:48 -08005472</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005473
Robert Griesemer4b908332009-08-07 17:05:41 -07005474<ol>
5475 <li>The return value or values may be explicitly listed
5476 in the "return" statement. Each expression must be single-valued
Robert Griesemer440cc952010-06-07 17:40:21 -07005477 and <a href="#Assignability">assignable</a>
5478 to the corresponding element of the function's result type.
Robert Griesemerc2d55862009-02-19 16:49:10 -08005479<pre>
Russ Cox9c08d652012-02-21 22:04:30 -05005480func simpleF() int {
Rob Pike96750f12009-02-27 16:47:48 -08005481 return 2
Robert Griesemerc2d55862009-02-19 16:49:10 -08005482}
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005483
Russ Cox9c08d652012-02-21 22:04:30 -05005484func complexF1() (re float64, im float64) {
Rob Pike96750f12009-02-27 16:47:48 -08005485 return -7.0, -4.0
Robert Griesemerc2d55862009-02-19 16:49:10 -08005486}
5487</pre>
Robert Griesemer4b908332009-08-07 17:05:41 -07005488 </li>
5489 <li>The expression list in the "return" statement may be a single
5490 call to a multi-valued function. The effect is as if each value
5491 returned from that function were assigned to a temporary
5492 variable with the type of the respective value, followed by a
5493 "return" statement listing these variables, at which point the
5494 rules of the previous case apply.
Robert Griesemerc2d55862009-02-19 16:49:10 -08005495<pre>
Russ Cox9c08d652012-02-21 22:04:30 -05005496func complexF2() (re float64, im float64) {
5497 return complexF1()
Rob Pike96750f12009-02-27 16:47:48 -08005498}
5499</pre>
Robert Griesemer4b908332009-08-07 17:05:41 -07005500 </li>
Peter Mundy5928e1d2010-11-09 10:10:57 -08005501 <li>The expression list may be empty if the function's result
Robert Griesemer462a17e2013-03-22 15:36:04 -07005502 type specifies names for its <a href="#Function_types">result parameters</a>.
Rob Pikedb8c2b182010-06-11 21:30:03 -07005503 The result parameters act as ordinary local variables
Robert Griesemer4b908332009-08-07 17:05:41 -07005504 and the function may assign values to them as necessary.
5505 The "return" statement returns the values of these variables.
Rob Pike96750f12009-02-27 16:47:48 -08005506<pre>
Russ Cox9c08d652012-02-21 22:04:30 -05005507func complexF3() (re float64, im float64) {
Robert Griesemer130ac742009-12-10 16:43:01 -08005508 re = 7.0
5509 im = 4.0
5510 return
Robert Griesemerc2d55862009-02-19 16:49:10 -08005511}
Robert Griesemerfb64e0d2011-03-07 16:29:07 -08005512
Russ Coxd9877e22011-11-01 21:45:02 -04005513func (devnull) Write(p []byte) (n int, _ error) {
Robert Griesemerfb64e0d2011-03-07 16:29:07 -08005514 n = len(p)
5515 return
Charles L. Dorian44262d12011-11-01 15:13:33 +09005516}
Robert Griesemerc2d55862009-02-19 16:49:10 -08005517</pre>
Robert Griesemer4b908332009-08-07 17:05:41 -07005518 </li>
5519</ol>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005520
Rob Pikedb8c2b182010-06-11 21:30:03 -07005521<p>
Robert Griesemer462a17e2013-03-22 15:36:04 -07005522Regardless of how they are declared, all the result values are initialized to
5523the <a href="#The_zero_value">zero values</a> for their type upon entry to the
Robert Griesemer1e8e14c2012-11-01 10:13:48 -07005524function. A "return" statement that specifies results sets the result parameters before
5525any deferred functions are executed.
Rob Pikedb8c2b182010-06-11 21:30:03 -07005526</p>
5527
Robert Griesemerc97778f2014-03-05 11:59:53 -08005528<p>
5529Implementation restriction: A compiler may disallow an empty expression list
5530in a "return" statement if a different entity (constant, type, or variable)
5531with the same name as a result parameter is in
5532<a href="#Declarations_and_scope">scope</a> at the place of the return.
5533</p>
5534
5535<pre>
5536func f(n int) (res int, err error) {
5537 if _, err := f(n-1); err != nil {
5538 return // invalid return statement: err is shadowed
5539 }
5540 return
5541}
5542</pre>
Russ Cox5958dd62009-03-04 17:19:21 -08005543
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005544<h3 id="Break_statements">Break statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005545
Rob Pike96750f12009-02-27 16:47:48 -08005546<p>
5547A "break" statement terminates execution of the innermost
Robert Griesemer462a17e2013-03-22 15:36:04 -07005548<a href="#For_statements">"for"</a>,
5549<a href="#Switch_statements">"switch"</a>, or
Robert Griesemer94849d52014-05-28 08:43:47 -07005550<a href="#Select_statements">"select"</a> statement
5551within the same function.
Rob Pike96750f12009-02-27 16:47:48 -08005552</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005553
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005554<pre class="ebnf">
Robert Griesemer130ac742009-12-10 16:43:01 -08005555BreakStmt = "break" [ Label ] .
Robert Griesemerc2d55862009-02-19 16:49:10 -08005556</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005557
Rob Pike96750f12009-02-27 16:47:48 -08005558<p>
5559If there is a label, it must be that of an enclosing
Robert Griesemer462a17e2013-03-22 15:36:04 -07005560"for", "switch", or "select" statement,
5561and that is the one whose execution terminates.
Rob Pike96750f12009-02-27 16:47:48 -08005562</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005563
Robert Griesemerc2d55862009-02-19 16:49:10 -08005564<pre>
Rob Pikecec09542013-09-17 07:41:11 +10005565OuterLoop:
5566 for i = 0; i &lt; n; i++ {
5567 for j = 0; j &lt; m; j++ {
5568 switch a[i][j] {
5569 case nil:
5570 state = Error
5571 break OuterLoop
5572 case item:
5573 state = Found
5574 break OuterLoop
5575 }
Russ Cox108564d2011-03-15 13:51:24 -04005576 }
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005577 }
Robert Griesemerc2d55862009-02-19 16:49:10 -08005578</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005579
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005580<h3 id="Continue_statements">Continue statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005581
Rob Pike96750f12009-02-27 16:47:48 -08005582<p>
5583A "continue" statement begins the next iteration of the
Robert Griesemer462a17e2013-03-22 15:36:04 -07005584innermost <a href="#For_statements">"for" loop</a> at its post statement.
Robert Griesemer94849d52014-05-28 08:43:47 -07005585The "for" loop must be within the same function.
Rob Pike96750f12009-02-27 16:47:48 -08005586</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005587
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005588<pre class="ebnf">
Robert Griesemer130ac742009-12-10 16:43:01 -08005589ContinueStmt = "continue" [ Label ] .
Robert Griesemerc2d55862009-02-19 16:49:10 -08005590</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005591
Rob Pike96750f12009-02-27 16:47:48 -08005592<p>
Rob Pikede9219962010-04-28 13:18:40 -07005593If there is a label, it must be that of an enclosing
5594"for" statement, and that is the one whose execution
Robert Griesemer462a17e2013-03-22 15:36:04 -07005595advances.
Rob Pike96750f12009-02-27 16:47:48 -08005596</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005597
Rob Pikecec09542013-09-17 07:41:11 +10005598<pre>
5599RowLoop:
5600 for y, row := range rows {
5601 for x, data := range row {
5602 if data == endOfRow {
5603 continue RowLoop
5604 }
5605 row[x] = data + bias(x, y)
5606 }
5607 }
5608</pre>
5609
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005610<h3 id="Goto_statements">Goto statements</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005611
Rob Pike96750f12009-02-27 16:47:48 -08005612<p>
Robert Griesemer94849d52014-05-28 08:43:47 -07005613A "goto" statement transfers control to the statement with the corresponding label
5614within the same function.
Rob Pike96750f12009-02-27 16:47:48 -08005615</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005616
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005617<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07005618GotoStmt = "goto" Label .
Robert Griesemerc2d55862009-02-19 16:49:10 -08005619</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005620
Robert Griesemerc2d55862009-02-19 16:49:10 -08005621<pre>
5622goto Error
5623</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005624
Rob Pike96750f12009-02-27 16:47:48 -08005625<p>
5626Executing the "goto" statement must not cause any variables to come into
Russ Coxf4c7db02011-06-17 12:49:04 -04005627<a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto.
5628For instance, this example:
Rob Pike96750f12009-02-27 16:47:48 -08005629</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005630
Robert Griesemerc2d55862009-02-19 16:49:10 -08005631<pre>
Russ Cox108564d2011-03-15 13:51:24 -04005632 goto L // BAD
5633 v := 3
Robert Griesemerc2d55862009-02-19 16:49:10 -08005634L:
5635</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005636
Rob Pike96750f12009-02-27 16:47:48 -08005637<p>
5638is erroneous because the jump to label <code>L</code> skips
5639the creation of <code>v</code>.
Russ Coxf4c7db02011-06-17 12:49:04 -04005640</p>
5641
5642<p>
5643A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block.
5644For instance, this example:
5645</p>
5646
5647<pre>
5648if n%2 == 1 {
5649 goto L1
5650}
5651for n &gt; 0 {
5652 f()
5653 n--
5654L1:
5655 f()
5656 n--
5657}
5658</pre>
5659
5660<p>
Charles L. Dorian44262d12011-11-01 15:13:33 +09005661is erroneous because the label <code>L1</code> is inside
Russ Coxf4c7db02011-06-17 12:49:04 -04005662the "for" statement's block but the <code>goto</code> is not.
Rob Pike96750f12009-02-27 16:47:48 -08005663</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005664
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005665<h3 id="Fallthrough_statements">Fallthrough statements</h3>
Robert Griesemeraed247f2008-10-08 17:05:30 -07005666
Rob Pike96750f12009-02-27 16:47:48 -08005667<p>
5668A "fallthrough" statement transfers control to the first statement of the
Shenghou Maca9876d2015-12-31 11:25:51 -05005669next case clause in an <a href="#Expression_switches">expression "switch" statement</a>.
Robert Griesemer67a6b4f2013-03-01 16:45:14 -08005670It may be used only as the final non-empty statement in such a clause.
Rob Pike96750f12009-02-27 16:47:48 -08005671</p>
Robert Griesemeraed247f2008-10-08 17:05:30 -07005672
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005673<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07005674FallthroughStmt = "fallthrough" .
Robert Griesemerc2d55862009-02-19 16:49:10 -08005675</pre>
Robert Griesemeraed247f2008-10-08 17:05:30 -07005676
5677
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005678<h3 id="Defer_statements">Defer statements</h3>
Robert Griesemer4a903e02009-01-27 09:29:40 -08005679
Rob Pike96750f12009-02-27 16:47:48 -08005680<p>
Robert Griesemer1e8e14c2012-11-01 10:13:48 -07005681A "defer" statement invokes a function whose execution is deferred
5682to the moment the surrounding function returns, either because the
5683surrounding function executed a <a href="#Return_statements">return statement</a>,
5684reached the end of its <a href="#Function_declarations">function body</a>,
5685or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>.
Rob Pike96750f12009-02-27 16:47:48 -08005686</p>
Robert Griesemer4a903e02009-01-27 09:29:40 -08005687
Robert Griesemerf7ac31362009-07-10 16:06:40 -07005688<pre class="ebnf">
Rob Pike11417162009-03-24 17:45:53 -07005689DeferStmt = "defer" Expression .
Robert Griesemerc2d55862009-02-19 16:49:10 -08005690</pre>
Robert Griesemer4a903e02009-01-27 09:29:40 -08005691
Rob Pike96750f12009-02-27 16:47:48 -08005692<p>
Robert Griesemer25dd0022012-11-29 11:46:25 -08005693The expression must be a function or method call; it cannot be parenthesized.
5694Calls of built-in functions are restricted as for
5695<a href="#Expression_statements">expression statements</a>.
5696</p>
5697
5698<p>
Robert Griesemerb4eb22d2014-09-19 13:32:07 -07005699Each time a "defer" statement
Rob Pike633a2ce2012-01-23 08:40:13 -08005700executes, the function value and parameters to the call are
5701<a href="#Calls">evaluated as usual</a>
Robert Griesemerb4eb22d2014-09-19 13:32:07 -07005702and saved anew but the actual function is not invoked.
5703Instead, deferred functions are invoked immediately before
Robert Griesemer1e8e14c2012-11-01 10:13:48 -07005704the surrounding function returns, in the reverse order
Robert Griesemer206fd782018-09-21 21:03:35 -07005705they were deferred. That is, if the surrounding function
5706returns through an explicit <a href="#Return_statements">return statement</a>,
5707deferred functions are executed <i>after</i> any result parameters are set
5708by that return statement but <i>before</i> the function returns to its caller.
Robert Griesemerb4eb22d2014-09-19 13:32:07 -07005709If a deferred function value evaluates
5710to <code>nil</code>, execution <a href="#Handling_panics">panics</a>
Rob Pike651bb8e2014-09-19 14:13:51 -07005711when the function is invoked, not when the "defer" statement is executed.
Robert Griesemer1e8e14c2012-11-01 10:13:48 -07005712</p>
5713
5714<p>
5715For instance, if the deferred function is
Rob Pike5bb29fb2010-03-25 17:59:59 -07005716a <a href="#Function_literals">function literal</a> and the surrounding
Robert Griesemer48f0cd22010-03-23 17:30:14 -07005717function has <a href="#Function_types">named result parameters</a> that
5718are in scope within the literal, the deferred function may access and modify
5719the result parameters before they are returned.
Rob Pike633a2ce2012-01-23 08:40:13 -08005720If the deferred function has any return values, they are discarded when
5721the function completes.
Rob Pike15970c82012-10-16 11:27:20 +11005722(See also the section on <a href="#Handling_panics">handling panics</a>.)
5723</p>
5724
Robert Griesemerc2d55862009-02-19 16:49:10 -08005725<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08005726lock(l)
5727defer unlock(l) // unlocking happens before surrounding function returns
Robert Griesemer4a903e02009-01-27 09:29:40 -08005728
Robert Griesemerc2d55862009-02-19 16:49:10 -08005729// prints 3 2 1 0 before surrounding function returns
5730for i := 0; i &lt;= 3; i++ {
Robert Griesemer130ac742009-12-10 16:43:01 -08005731 defer fmt.Print(i)
Robert Griesemerc2d55862009-02-19 16:49:10 -08005732}
Robert Griesemer48f0cd22010-03-23 17:30:14 -07005733
Robert Griesemer206fd782018-09-21 21:03:35 -07005734// f returns 42
Robert Griesemer48f0cd22010-03-23 17:30:14 -07005735func f() (result int) {
5736 defer func() {
Robert Griesemer206fd782018-09-21 21:03:35 -07005737 // result is accessed after it was set to 6 by the return statement
5738 result *= 7
Robert Griesemer48f0cd22010-03-23 17:30:14 -07005739 }()
Robert Griesemer206fd782018-09-21 21:03:35 -07005740 return 6
Robert Griesemer48f0cd22010-03-23 17:30:14 -07005741}
Robert Griesemerc2d55862009-02-19 16:49:10 -08005742</pre>
Robert Griesemer4a903e02009-01-27 09:29:40 -08005743
Robert Griesemer164a7bc2009-09-30 12:00:25 -07005744<h2 id="Built-in_functions">Built-in functions</h2>
5745
5746<p>
Rob Pike72970872010-03-04 12:35:16 -08005747Built-in functions are
Robert Griesemer164a7bc2009-09-30 12:00:25 -07005748<a href="#Predeclared_identifiers">predeclared</a>.
5749They are called like any other function but some of them
5750accept a type instead of an expression as the first argument.
5751</p>
5752
Russ Cox2a5f0c62009-12-04 10:23:12 -08005753<p>
5754The built-in functions do not have standard Go types,
5755so they can only appear in <a href="#Calls">call expressions</a>;
5756they cannot be used as function values.
5757</p>
5758
Russ Cox9f2cb862011-03-11 14:47:02 -05005759<h3 id="Close">Close</h3>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07005760
5761<p>
Robert Griesemerdc60c5a2010-07-14 16:09:22 -07005762For a channel <code>c</code>, the built-in function <code>close(c)</code>
Russ Coxf58ed4e2011-10-13 16:58:04 -04005763records that no more values will be sent on the channel.
5764It is an error if <code>c</code> is a receive-only channel.
5765Sending to or closing a closed channel causes a <a href="#Run_time_panics">run-time panic</a>.
5766Closing the nil channel also causes a <a href="#Run_time_panics">run-time panic</a>.
Robert Griesemerdc60c5a2010-07-14 16:09:22 -07005767After calling <code>close</code>, and after any previously
Robert Griesemer164a7bc2009-09-30 12:00:25 -07005768sent values have been received, receive operations will return
Robert Griesemerdc60c5a2010-07-14 16:09:22 -07005769the zero value for the channel's type without blocking.
Russ Cox9f2cb862011-03-11 14:47:02 -05005770The multi-valued <a href="#Receive_operator">receive operation</a>
5771returns a received value along with an indication of whether the channel is closed.
Robert Griesemer164a7bc2009-09-30 12:00:25 -07005772</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005773
Robert Griesemerdc60c5a2010-07-14 16:09:22 -07005774
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005775<h3 id="Length_and_capacity">Length and capacity</h3>
Robert Griesemer7a4ed4f2008-09-03 15:15:51 -07005776
Robert Griesemer164a7bc2009-09-30 12:00:25 -07005777<p>
5778The built-in functions <code>len</code> and <code>cap</code> take arguments
5779of various types and return a result of type <code>int</code>.
5780The implementation guarantees that the result always fits into an <code>int</code>.
5781</p>
5782
Rob Pikeff70f092009-02-20 13:36:14 -08005783<pre class="grammar">
Robert Griesemer54731032011-05-12 09:15:59 -07005784Call Argument type Result
Robert Griesemer7a4ed4f2008-09-03 15:15:51 -07005785
Robert Griesemer54731032011-05-12 09:15:59 -07005786len(s) string type string length in bytes
5787 [n]T, *[n]T array length (== n)
5788 []T slice length
5789 map[K]T map length (number of defined keys)
5790 chan T number of elements queued in channel buffer
Robert Griesemer4dc25282008-09-09 10:37:19 -07005791
Robert Griesemer54731032011-05-12 09:15:59 -07005792cap(s) [n]T, *[n]T array length (== n)
5793 []T slice capacity
5794 chan T channel buffer capacity
Robert Griesemerc2d55862009-02-19 16:49:10 -08005795</pre>
Robert Griesemer4dc25282008-09-09 10:37:19 -07005796
Robert Griesemerc2d55862009-02-19 16:49:10 -08005797<p>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07005798The capacity of a slice is the number of elements for which there is
5799space allocated in the underlying array.
5800At any time the following relationship holds:
5801</p>
Robert Griesemer633957b2009-01-06 13:23:20 -08005802
Robert Griesemerc2d55862009-02-19 16:49:10 -08005803<pre>
Anthony Martin0122a662011-02-08 14:51:15 -080058040 &lt;= len(s) &lt;= cap(s)
Robert Griesemerc2d55862009-02-19 16:49:10 -08005805</pre>
Robert Griesemer667ef6c2008-09-10 13:00:32 -07005806
Russ Coxf4429182010-07-01 17:49:47 -07005807<p>
Shenghou Maa0b5b462013-01-22 03:18:20 +08005808The length of a <code>nil</code> slice, map or channel is 0.
Rob Pike82e2db72014-01-04 10:52:59 -08005809The capacity of a <code>nil</code> slice or channel is 0.
Robert Griesemer0c2e6b32010-07-13 11:54:57 -07005810</p>
5811
5812<p>
Robert Griesemer54731032011-05-12 09:15:59 -07005813The expression <code>len(s)</code> is <a href="#Constants">constant</a> if
5814<code>s</code> is a string constant. The expressions <code>len(s)</code> and
5815<code>cap(s)</code> are constants if the type of <code>s</code> is an array
5816or pointer to an array and the expression <code>s</code> does not contain
Robert Griesemer87169812014-03-03 20:07:34 -08005817<a href="#Receive_operator">channel receives</a> or (non-constant)
Robert Griesemer54731032011-05-12 09:15:59 -07005818<a href="#Calls">function calls</a>; in this case <code>s</code> is not evaluated.
5819Otherwise, invocations of <code>len</code> and <code>cap</code> are not
5820constant and <code>s</code> is evaluated.
Russ Coxf4429182010-07-01 17:49:47 -07005821</p>
Robert Griesemer4dc25282008-09-09 10:37:19 -07005822
Robert Griesemer87169812014-03-03 20:07:34 -08005823<pre>
5824const (
5825 c1 = imag(2i) // imag(2i) = 2.0 is a constant
5826 c2 = len([10]float64{2}) // [10]float64{2} contains no function calls
5827 c3 = len([10]float64{c1}) // [10]float64{c1} contains no function calls
5828 c4 = len([10]float64{imag(2i)}) // imag(2i) is a constant and no function call is issued
Shenghou Mac0abdd92014-12-26 02:50:33 -05005829 c5 = len([10]float64{imag(z)}) // invalid: imag(z) is a (non-constant) function call
Robert Griesemer87169812014-03-03 20:07:34 -08005830)
5831var z complex128
5832</pre>
Robert Griesemer54731032011-05-12 09:15:59 -07005833
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005834<h3 id="Allocation">Allocation</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005835
Rob Pike96750f12009-02-27 16:47:48 -08005836<p>
Robert Griesemer6962c152014-10-16 15:08:49 -07005837The built-in function <code>new</code> takes a type <code>T</code>,
5838allocates storage for a <a href="#Variables">variable</a> of that type
5839at run time, and returns a value of type <code>*T</code>
5840<a href="#Pointer_types">pointing</a> to it.
5841The variable is initialized as described in the section on
Robert Griesemer462a17e2013-03-22 15:36:04 -07005842<a href="#The_zero_value">initial values</a>.
Rob Pike96750f12009-02-27 16:47:48 -08005843</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005844
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08005845<pre class="grammar">
Robert Griesemerc2d55862009-02-19 16:49:10 -08005846new(T)
5847</pre>
Robert Griesemer4dc25282008-09-09 10:37:19 -07005848
Rob Pike96750f12009-02-27 16:47:48 -08005849<p>
Robert Griesemer4dc25282008-09-09 10:37:19 -07005850For instance
Rob Pike96750f12009-02-27 16:47:48 -08005851</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005852
Robert Griesemerc2d55862009-02-19 16:49:10 -08005853<pre>
Robert Griesemerb94c0d22011-01-19 23:07:21 -05005854type S struct { a int; b float64 }
Robert Griesemerc2d55862009-02-19 16:49:10 -08005855new(S)
5856</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005857
Rob Pike96750f12009-02-27 16:47:48 -08005858<p>
Robert Griesemer6962c152014-10-16 15:08:49 -07005859allocates storage for a variable of type <code>S</code>,
Rob Pike96750f12009-02-27 16:47:48 -08005860initializes it (<code>a=0</code>, <code>b=0.0</code>),
5861and returns a value of type <code>*S</code> containing the address
Robert Griesemer6962c152014-10-16 15:08:49 -07005862of the location.
Rob Pike96750f12009-02-27 16:47:48 -08005863</p>
5864
Russ Cox7c4f7cc2009-08-20 11:11:03 -07005865<h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07005866
Robert Griesemerc2d55862009-02-19 16:49:10 -08005867<p>
Rob Pike96750f12009-02-27 16:47:48 -08005868The built-in function <code>make</code> takes a type <code>T</code>,
5869which must be a slice, map or channel type,
5870optionally followed by a type-specific list of expressions.
5871It returns a value of type <code>T</code> (not <code>*T</code>).
Robert Griesemer462a17e2013-03-22 15:36:04 -07005872The memory is initialized as described in the section on
5873<a href="#The_zero_value">initial values</a>.
Rob Pike96750f12009-02-27 16:47:48 -08005874</p>
Robert Griesemer633957b2009-01-06 13:23:20 -08005875
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08005876<pre class="grammar">
Robert Griesemerdf674ff2010-05-04 17:31:40 -07005877Call Type T Result
5878
5879make(T, n) slice slice of type T with length n and capacity n
5880make(T, n, m) slice slice of type T with length n and capacity m
5881
5882make(T) map map of type T
Robert Griesemerb0e5a0c2017-04-11 16:10:09 -07005883make(T, n) map map of type T with initial space for approximately n elements
Robert Griesemerdf674ff2010-05-04 17:31:40 -07005884
Robert Griesemer97aa90d2014-05-07 10:40:39 -07005885make(T) channel unbuffered channel of type T
5886make(T, n) channel buffered channel of type T, buffer size n
Robert Griesemerc2d55862009-02-19 16:49:10 -08005887</pre>
Robert Griesemer633957b2009-01-06 13:23:20 -08005888
Robert Griesemer633957b2009-01-06 13:23:20 -08005889
Rob Pike96750f12009-02-27 16:47:48 -08005890<p>
griesemer9690d242017-08-30 15:10:12 +02005891Each of the size arguments <code>n</code> and <code>m</code> must be of integer type
5892or an untyped <a href="#Constants">constant</a>.
5893A constant size argument must be non-negative and <a href="#Representability">representable</a>
5894by a value of type <code>int</code>; if it is an untyped constant it is given type <code>int</code>.
Robert Griesemer39067062012-12-12 11:06:26 -08005895If both <code>n</code> and <code>m</code> are provided and are constant, then
Robert Griesemer3bde0002012-10-19 10:11:06 -07005896<code>n</code> must be no larger than <code>m</code>.
5897If <code>n</code> is negative or larger than <code>m</code> at run time,
5898a <a href="#Run_time_panics">run-time panic</a> occurs.
Rob Pike96750f12009-02-27 16:47:48 -08005899</p>
Robert Griesemer633957b2009-01-06 13:23:20 -08005900
Robert Griesemerc2d55862009-02-19 16:49:10 -08005901<pre>
David Symonds72a29792011-11-29 15:47:36 -08005902s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100
Robert Griesemer3bde0002012-10-19 10:11:06 -07005903s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000
Robert Griesemer39067062012-12-12 11:06:26 -08005904s := make([]int, 1&lt;&lt;63) // illegal: len(s) is not representable by a value of type int
Oling Cat018e89f2013-01-24 20:46:33 +11005905s := make([]int, 10, 0) // illegal: len(s) > cap(s)
David Symonds72a29792011-11-29 15:47:36 -08005906c := make(chan int, 10) // channel with a buffer size of 10
Robert Griesemerb0e5a0c2017-04-11 16:10:09 -07005907m := make(map[string]int, 100) // map with initial space for approximately 100 elements
Robert Griesemerc2d55862009-02-19 16:49:10 -08005908</pre>
Robert Griesemer633957b2009-01-06 13:23:20 -08005909
Robert Griesemerb0e5a0c2017-04-11 16:10:09 -07005910<p>
5911Calling <code>make</code> with a map type and size hint <code>n</code> will
5912create a map with initial space to hold <code>n</code> map elements.
5913The precise behavior is implementation-dependent.
5914</p>
5915
Robert Griesemer164a7bc2009-09-30 12:00:25 -07005916
Robert Griesemer07e983a2010-10-25 16:50:31 -07005917<h3 id="Appending_and_copying_slices">Appending to and copying slices</h3>
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08005918
5919<p>
Robert Griesemer0c494712012-09-28 15:55:38 -07005920The built-in functions <code>append</code> and <code>copy</code> assist in
5921common slice operations.
5922For both functions, the result is independent of whether the memory referenced
5923by the arguments overlaps.
Robert Griesemer07e983a2010-10-25 16:50:31 -07005924</p>
5925
5926<p>
Robert Griesemer95b81372011-06-12 12:09:50 -07005927The <a href="#Function_types">variadic</a> function <code>append</code>
5928appends zero or more values <code>x</code>
Robert Griesemer0f7acf12011-04-19 14:38:49 -07005929to <code>s</code> of type <code>S</code>, which must be a slice type, and
5930returns the resulting slice, also of type <code>S</code>.
Robert Griesemer95b81372011-06-12 12:09:50 -07005931The values <code>x</code> are passed to a parameter of type <code>...T</code>
5932where <code>T</code> is the <a href="#Slice_types">element type</a> of
5933<code>S</code> and the respective
5934<a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply.
Luuk van Dijk77fac212011-10-12 15:59:23 +02005935As a special case, <code>append</code> also accepts a first argument
5936assignable to type <code>[]byte</code> with a second argument of
5937string type followed by <code>...</code>. This form appends the
5938bytes of the string.
Robert Griesemer07e983a2010-10-25 16:50:31 -07005939</p>
5940
5941<pre class="grammar">
Robert Griesemer0f7acf12011-04-19 14:38:49 -07005942append(s S, x ...T) S // T is the element type of S
Robert Griesemer07e983a2010-10-25 16:50:31 -07005943</pre>
5944
5945<p>
5946If the capacity of <code>s</code> is not large enough to fit the additional
Robert Griesemer15da9972013-10-16 16:16:54 -07005947values, <code>append</code> allocates a new, sufficiently large underlying
5948array that fits both the existing slice elements and the additional values.
5949Otherwise, <code>append</code> re-uses the underlying array.
Robert Griesemer07e983a2010-10-25 16:50:31 -07005950</p>
5951
5952<pre>
5953s0 := []int{0, 0}
Robert Griesemer0c494712012-09-28 15:55:38 -07005954s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2}
5955s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7}
5956s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
5957s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
Robert Griesemer0f7acf12011-04-19 14:38:49 -07005958
5959var t []interface{}
David Symonds583b29c2014-12-04 09:29:29 +11005960t = append(t, 42, 3.1415, "foo") // t == []interface{}{42, 3.1415, "foo"}
Luuk van Dijk77fac212011-10-12 15:59:23 +02005961
5962var b []byte
Robert Griesemer0c494712012-09-28 15:55:38 -07005963b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' }
Robert Griesemer07e983a2010-10-25 16:50:31 -07005964</pre>
5965
5966<p>
5967The function <code>copy</code> copies slice elements from
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08005968a source <code>src</code> to a destination <code>dst</code> and returns the
Robert Griesemer0c494712012-09-28 15:55:38 -07005969number of elements copied.
Robert Griesemer7bc03712010-06-07 15:49:39 -07005970Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be
Robert Griesemer425bbad2010-10-25 16:41:06 -07005971<a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>.
Nigel Tao703b0922011-05-15 16:04:37 -07005972The number of elements copied is the minimum of
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08005973<code>len(src)</code> and <code>len(dst)</code>.
Robert Griesemer425bbad2010-10-25 16:41:06 -07005974As a special case, <code>copy</code> also accepts a destination argument assignable
5975to type <code>[]byte</code> with a source argument of a string type.
5976This form copies the bytes from the string into the byte slice.
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08005977</p>
5978
5979<pre class="grammar">
5980copy(dst, src []T) int
Robert Griesemer425bbad2010-10-25 16:41:06 -07005981copy(dst []byte, src string) int
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08005982</pre>
5983
5984<p>
5985Examples:
5986</p>
5987
5988<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08005989var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7}
5990var s = make([]int, 6)
Robert Griesemer425bbad2010-10-25 16:41:06 -07005991var b = make([]byte, 5)
5992n1 := copy(s, a[0:]) // n1 == 6, s == []int{0, 1, 2, 3, 4, 5}
5993n2 := copy(s, s[2:]) // n2 == 4, s == []int{2, 3, 4, 5, 4, 5}
5994n3 := copy(b, "Hello, World!") // n3 == 5, b == []byte("Hello")
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08005995</pre>
5996
Robert Griesemer3e0c0a82011-10-17 12:53:10 -07005997
5998<h3 id="Deletion_of_map_elements">Deletion of map elements</h3>
5999
6000<p>
6001The built-in function <code>delete</code> removes the element with key
6002<code>k</code> from a <a href="#Map_types">map</a> <code>m</code>. The
6003type of <code>k</code> must be <a href="#Assignability">assignable</a>
6004to the key type of <code>m</code>.
6005</p>
6006
6007<pre class="grammar">
6008delete(m, k) // remove element m[k] from map m
6009</pre>
6010
6011<p>
Robert Griesemera9a49fe2012-12-12 13:08:35 -08006012If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code>
6013does not exist, <code>delete</code> is a no-op.
Robert Griesemer3e0c0a82011-10-17 12:53:10 -07006014</p>
6015
6016
Russ Cox0201e372012-02-29 15:20:11 -05006017<h3 id="Complex_numbers">Manipulating complex numbers</h3>
Rob Pike72970872010-03-04 12:35:16 -08006018
6019<p>
6020Three functions assemble and disassemble complex numbers.
Robert Griesemerb94c0d22011-01-19 23:07:21 -05006021The built-in function <code>complex</code> constructs a complex
Rob Pike72970872010-03-04 12:35:16 -08006022value from a floating-point real and imaginary part, while
6023<code>real</code> and <code>imag</code>
6024extract the real and imaginary parts of a complex value.
6025</p>
6026
6027<pre class="grammar">
Robert Griesemerb94c0d22011-01-19 23:07:21 -05006028complex(realPart, imaginaryPart floatT) complexT
Rob Pike72970872010-03-04 12:35:16 -08006029real(complexT) floatT
6030imag(complexT) floatT
6031</pre>
6032
6033<p>
6034The type of the arguments and return value correspond.
Robert Griesemerb94c0d22011-01-19 23:07:21 -05006035For <code>complex</code>, the two arguments must be of the same
Rob Pike72970872010-03-04 12:35:16 -08006036floating-point type and the return type is the complex type
6037with the corresponding floating-point constituents:
Robert Griesemer98aa8222015-07-29 15:42:04 -07006038<code>complex64</code> for <code>float32</code> arguments, and
6039<code>complex128</code> for <code>float64</code> arguments.
Robert Griesemer26d22602018-10-02 15:55:38 -07006040If one of the arguments evaluates to an untyped constant, it is first implicitly
Robert Griesemer98aa8222015-07-29 15:42:04 -07006041<a href="#Conversions">converted</a> to the type of the other argument.
6042If both arguments evaluate to untyped constants, they must be non-complex
6043numbers or their imaginary parts must be zero, and the return value of
6044the function is an untyped complex constant.
6045</p>
6046
6047<p>
6048For <code>real</code> and <code>imag</code>, the argument must be
6049of complex type, and the return type is the corresponding floating-point
6050type: <code>float32</code> for a <code>complex64</code> argument, and
6051<code>float64</code> for a <code>complex128</code> argument.
6052If the argument evaluates to an untyped constant, it must be a number,
6053and the return value of the function is an untyped floating-point constant.
6054</p>
6055
6056<p>
6057The <code>real</code> and <code>imag</code> functions together form the inverse of
6058<code>complex</code>, so for a value <code>z</code> of a complex type <code>Z</code>,
6059<code>z&nbsp;==&nbsp;Z(complex(real(z),&nbsp;imag(z)))</code>.
Rob Pike72970872010-03-04 12:35:16 -08006060</p>
6061
6062<p>
6063If the operands of these functions are all constants, the return
6064value is a constant.
6065</p>
6066
6067<pre>
Robert Griesemerb94c0d22011-01-19 23:07:21 -05006068var a = complex(2, -2) // complex128
Robert Griesemer98aa8222015-07-29 15:42:04 -07006069const b = complex(1.0, -1.4) // untyped complex constant 1 - 1.4i
Robert Griesemerb94c0d22011-01-19 23:07:21 -05006070x := float32(math.Cos(math.Pi/2)) // float32
6071var c64 = complex(5, -x) // complex64
Robert Griesemera10b4cf2019-02-05 14:33:24 -08006072var s int = complex(1, 0) // untyped complex constant 1 + 0i can be converted to int
Robert Griesemer5567b872016-10-14 11:27:11 -07006073_ = complex(1, 2&lt;&lt;s) // illegal: 2 assumes floating-point type, cannot shift
Robert Griesemerb94c0d22011-01-19 23:07:21 -05006074var rl = real(c64) // float32
Robert Griesemer98aa8222015-07-29 15:42:04 -07006075var im = imag(a) // float64
6076const c = imag(b) // untyped constant -1.4
Robert Griesemer5567b872016-10-14 11:27:11 -07006077_ = imag(3 &lt;&lt; s) // illegal: 3 assumes complex type, cannot shift
Rob Pike72970872010-03-04 12:35:16 -08006078</pre>
6079
Rob Pike5bb29fb2010-03-25 17:59:59 -07006080<h3 id="Handling_panics">Handling panics</h3>
6081
6082<p> Two built-in functions, <code>panic</code> and <code>recover</code>,
6083assist in reporting and handling <a href="#Run_time_panics">run-time panics</a>
Charles L. Dorian44262d12011-11-01 15:13:33 +09006084and program-defined error conditions.
Rob Pike5bb29fb2010-03-25 17:59:59 -07006085</p>
6086
6087<pre class="grammar">
6088func panic(interface{})
6089func recover() interface{}
6090</pre>
6091
6092<p>
Rob Pikec34050f2013-03-12 14:28:16 -07006093While executing a function <code>F</code>,
6094an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a>
6095terminates the execution of <code>F</code>.
Robert Griesemer1e8e14c2012-11-01 10:13:48 -07006096Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
Rob Pikec34050f2013-03-12 14:28:16 -07006097are then executed as usual.
6098Next, any deferred functions run by <code>F's</code> caller are run,
6099and so on up to any deferred by the top-level function in the executing goroutine.
6100At that point, the program is terminated and the error
Robert Griesemer1e8e14c2012-11-01 10:13:48 -07006101condition is reported, including the value of the argument to <code>panic</code>.
6102This termination sequence is called <i>panicking</i>.
Rob Pike5bb29fb2010-03-25 17:59:59 -07006103</p>
6104
Robert Griesemer76f32282011-02-04 08:43:21 -08006105<pre>
6106panic(42)
6107panic("unreachable")
6108panic(Error("cannot parse"))
6109</pre>
6110
Rob Pike5bb29fb2010-03-25 17:59:59 -07006111<p>
6112The <code>recover</code> function allows a program to manage behavior
Rob Pikec34050f2013-03-12 14:28:16 -07006113of a panicking goroutine.
6114Suppose a function <code>G</code> defers a function <code>D</code> that calls
6115<code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code>
6116is executing.
6117When the running of deferred functions reaches <code>D</code>,
6118the return value of <code>D</code>'s call to <code>recover</code> will be the value passed to the call of <code>panic</code>.
6119If <code>D</code> returns normally, without starting a new
6120<code>panic</code>, the panicking sequence stops. In that case,
6121the state of functions called between <code>G</code> and the call to <code>panic</code>
6122is discarded, and normal execution resumes.
6123Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s
6124execution terminates by returning to its caller.
Rob Pike5bb29fb2010-03-25 17:59:59 -07006125</p>
6126
6127<p>
Rob Pikec34050f2013-03-12 14:28:16 -07006128The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds:
6129</p>
6130<ul>
6131<li>
6132<code>panic</code>'s argument was <code>nil</code>;
6133</li>
6134<li>
6135the goroutine is not panicking;
6136</li>
6137<li>
6138<code>recover</code> was not called directly by a deferred function.
6139</li>
6140</ul>
6141
6142<p>
Robert Griesemer76f32282011-02-04 08:43:21 -08006143The <code>protect</code> function in the example below invokes
6144the function argument <code>g</code> and protects callers from
6145run-time panics raised by <code>g</code>.
Rob Pike5bb29fb2010-03-25 17:59:59 -07006146</p>
6147
6148<pre>
Robert Griesemer76f32282011-02-04 08:43:21 -08006149func protect(g func()) {
Rob Pike5bb29fb2010-03-25 17:59:59 -07006150 defer func() {
Charles L. Dorian44262d12011-11-01 15:13:33 +09006151 log.Println("done") // Println executes normally even if there is a panic
Rob Pike5bb29fb2010-03-25 17:59:59 -07006152 if x := recover(); x != nil {
Rob Pike966bf712011-03-01 13:54:22 -08006153 log.Printf("run time panic: %v", x)
Rob Pike5bb29fb2010-03-25 17:59:59 -07006154 }
Rob Pikee6b1d422011-04-05 11:01:25 -07006155 }()
Robert Griesemer76f32282011-02-04 08:43:21 -08006156 log.Println("start")
6157 g()
Rob Pike5bb29fb2010-03-25 17:59:59 -07006158}
6159</pre>
6160
Robert Griesemer1a8ebcc2009-11-18 19:15:25 -08006161
Robert Griesemer164a7bc2009-09-30 12:00:25 -07006162<h3 id="Bootstrapping">Bootstrapping</h3>
6163
Robert Griesemer5eb36242009-09-16 11:05:14 -07006164<p>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07006165Current implementations provide several built-in functions useful during
6166bootstrapping. These functions are documented for completeness but are not
6167guaranteed to stay in the language. They do not return a result.
Robert Griesemer5eb36242009-09-16 11:05:14 -07006168</p>
6169
Robert Griesemer164a7bc2009-09-30 12:00:25 -07006170<pre class="grammar">
Robert Griesemerd4d4ff02009-10-19 13:13:59 -07006171Function Behavior
Robert Griesemer164a7bc2009-09-30 12:00:25 -07006172
6173print prints all arguments; formatting of arguments is implementation-specific
6174println like print but prints spaces between arguments and a newline at the end
Robert Griesemer164a7bc2009-09-30 12:00:25 -07006175</pre>
6176
Robert Griesemer50f67ad2017-04-27 17:54:49 -07006177<p>
6178Implementation restriction: <code>print</code> and <code>println</code> need not
6179accept arbitrary argument types, but printing of boolean, numeric, and string
Robert Griesemer86f5f7f2017-04-28 10:32:31 -07006180<a href="#Types">types</a> must be supported.
Robert Griesemer50f67ad2017-04-27 17:54:49 -07006181</p>
Robert Griesemer164a7bc2009-09-30 12:00:25 -07006182
Russ Cox7c4f7cc2009-08-20 11:11:03 -07006183<h2 id="Packages">Packages</h2>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006184
Rob Pike46596852009-03-02 16:17:29 -08006185<p>
6186Go programs are constructed by linking together <i>packages</i>.
Robert Griesemer326ef132009-09-28 19:21:15 -07006187A package in turn is constructed from one or more source files
6188that together declare constants, types, variables and functions
6189belonging to the package and which are accessible in all files
6190of the same package. Those elements may be
6191<a href="#Exported_identifiers">exported</a> and used in another package.
Rob Pike46596852009-03-02 16:17:29 -08006192</p>
6193
Russ Cox7c4f7cc2009-08-20 11:11:03 -07006194<h3 id="Source_file_organization">Source file organization</h3>
Rob Pike46596852009-03-02 16:17:29 -08006195
6196<p>
6197Each source file consists of a package clause defining the package
6198to which it belongs, followed by a possibly empty set of import
6199declarations that declare packages whose contents it wishes to use,
6200followed by a possibly empty set of declarations of functions,
Robert Griesemer0a162a12009-08-19 16:44:04 -07006201types, variables, and constants.
Rob Pike46596852009-03-02 16:17:29 -08006202</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006203
Robert Griesemerf7ac31362009-07-10 16:06:40 -07006204<pre class="ebnf">
Robert Griesemer130ac742009-12-10 16:43:01 -08006205SourceFile = PackageClause ";" { ImportDecl ";" } { TopLevelDecl ";" } .
Robert Griesemerc2d55862009-02-19 16:49:10 -08006206</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006207
Russ Cox7c4f7cc2009-08-20 11:11:03 -07006208<h3 id="Package_clause">Package clause</h3>
Rob Pike46596852009-03-02 16:17:29 -08006209
Robert Griesemerc2d55862009-02-19 16:49:10 -08006210<p>
Rob Pike46596852009-03-02 16:17:29 -08006211A package clause begins each source file and defines the package
6212to which the file belongs.
6213</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006214
Robert Griesemerf7ac31362009-07-10 16:06:40 -07006215<pre class="ebnf">
Robert Griesemer4e56b332009-09-10 10:14:00 -07006216PackageClause = "package" PackageName .
6217PackageName = identifier .
Robert Griesemerc2d55862009-02-19 16:49:10 -08006218</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006219
Robert Griesemer4e56b332009-09-10 10:14:00 -07006220<p>
6221The PackageName must not be the <a href="#Blank_identifier">blank identifier</a>.
6222</p>
6223
Rob Pike46596852009-03-02 16:17:29 -08006224<pre>
6225package math
6226</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006227
Rob Pike46596852009-03-02 16:17:29 -08006228<p>
6229A set of files sharing the same PackageName form the implementation of a package.
6230An implementation may require that all source files for a package inhabit the same directory.
6231</p>
6232
Russ Cox7c4f7cc2009-08-20 11:11:03 -07006233<h3 id="Import_declarations">Import declarations</h3>
Rob Pike46596852009-03-02 16:17:29 -08006234
6235<p>
Robert Griesemer103c9db2012-03-01 13:57:49 -08006236An import declaration states that the source file containing the declaration
6237depends on functionality of the <i>imported</i> package
6238(<a href="#Program_initialization_and_execution">§Program initialization and execution</a>)
Rob Pikeb51ad9c2012-09-23 05:03:43 +10006239and enables access to <a href="#Exported_identifiers">exported</a> identifiers
Robert Griesemer103c9db2012-03-01 13:57:49 -08006240of that package.
6241The import names an identifier (PackageName) to be used for access and an ImportPath
Rob Pike3aec2e42009-09-25 17:00:22 -07006242that specifies the package to be imported.
Rob Pike46596852009-03-02 16:17:29 -08006243</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006244
Robert Griesemerf7ac31362009-07-10 16:06:40 -07006245<pre class="ebnf">
Robert Griesemer130ac742009-12-10 16:43:01 -08006246ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
Robert Griesemer997851e2009-09-25 15:36:25 -07006247ImportSpec = [ "." | PackageName ] ImportPath .
Robert Griesemer130ac742009-12-10 16:43:01 -08006248ImportPath = string_lit .
Robert Griesemerc2d55862009-02-19 16:49:10 -08006249</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006250
Robert Griesemerc2d55862009-02-19 16:49:10 -08006251<p>
Rob Pike3aec2e42009-09-25 17:00:22 -07006252The PackageName is used in <a href="#Qualified_identifiers">qualified identifiers</a>
Robert Griesemer103c9db2012-03-01 13:57:49 -08006253to access exported identifiers of the package within the importing source file.
Rob Pike3aec2e42009-09-25 17:00:22 -07006254It is declared in the <a href="#Blocks">file block</a>.
6255If the PackageName is omitted, it defaults to the identifier specified in the
Robert Griesemer556506e2011-02-22 09:34:13 -08006256<a href="#Package_clause">package clause</a> of the imported package.
Rob Pike3aec2e42009-09-25 17:00:22 -07006257If an explicit period (<code>.</code>) appears instead of a name, all the
Robert Griesemer103c9db2012-03-01 13:57:49 -08006258package's exported identifiers declared in that package's
6259<a href="#Blocks">package block</a> will be declared in the importing source
Rob Pike227fe5f2014-01-14 15:16:01 -08006260file's file block and must be accessed without a qualifier.
Rob Pike46596852009-03-02 16:17:29 -08006261</p>
Russ Cox16b95ba2009-08-20 10:22:52 -07006262
Robert Griesemerc2d55862009-02-19 16:49:10 -08006263<p>
Rob Pike3aec2e42009-09-25 17:00:22 -07006264The interpretation of the ImportPath is implementation-dependent but
6265it is typically a substring of the full file name of the compiled
6266package and may be relative to a repository of installed packages.
6267</p>
6268
6269<p>
Robert Griesemerac4055b2012-02-22 23:51:25 -08006270Implementation restriction: A compiler may restrict ImportPaths to
6271non-empty strings using only characters belonging to
Suriyaa Sundararuban1041ac82018-06-13 07:06:04 +00006272<a href="https://www.unicode.org/versions/Unicode6.3.0/">Unicode's</a>
Robert Griesemerac4055b2012-02-22 23:51:25 -08006273L, M, N, P, and S general categories (the Graphic characters without
Russ Coxfad10f92012-02-23 22:46:04 -05006274spaces) and may also exclude the characters
6275<code>!"#$%&amp;'()*,:;&lt;=&gt;?[\]^`{|}</code>
6276and the Unicode replacement character U+FFFD.
Robert Griesemerac4055b2012-02-22 23:51:25 -08006277</p>
6278
6279<p>
Rob Pike3aec2e42009-09-25 17:00:22 -07006280Assume we have compiled a package containing the package clause
6281<code>package math</code>, which exports function <code>Sin</code>, and
6282installed the compiled package in the file identified by
Rob Pike46596852009-03-02 16:17:29 -08006283<code>"lib/math"</code>.
Rob Pike227fe5f2014-01-14 15:16:01 -08006284This table illustrates how <code>Sin</code> is accessed in files
Rob Pike3aec2e42009-09-25 17:00:22 -07006285that import the package after the
6286various types of import declaration.
Rob Pike46596852009-03-02 16:17:29 -08006287</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006288
Rob Pike46596852009-03-02 16:17:29 -08006289<pre class="grammar">
Robert Griesemer997851e2009-09-25 15:36:25 -07006290Import declaration Local name of Sin
Rob Pike46596852009-03-02 16:17:29 -08006291
Rob Pike46596852009-03-02 16:17:29 -08006292import "lib/math" math.Sin
Rob Pikeb51ad9c2012-09-23 05:03:43 +10006293import m "lib/math" m.Sin
Rob Pike46596852009-03-02 16:17:29 -08006294import . "lib/math" Sin
6295</pre>
6296
Robert Griesemer997851e2009-09-25 15:36:25 -07006297<p>
Rob Pike3aec2e42009-09-25 17:00:22 -07006298An import declaration declares a dependency relation between
6299the importing and imported package.
Robert Griesemer4be38dd2013-03-04 12:59:40 -08006300It is illegal for a package to import itself, directly or indirectly,
6301or to directly import a package without
Robert Griesemer997851e2009-09-25 15:36:25 -07006302referring to any of its exported identifiers. To import a package solely for
6303its side-effects (initialization), use the <a href="#Blank_identifier">blank</a>
6304identifier as explicit package name:
6305</p>
6306
6307<pre>
6308import _ "lib/math"
6309</pre>
6310
6311
Russ Cox7c4f7cc2009-08-20 11:11:03 -07006312<h3 id="An_example_package">An example package</h3>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006313
Robert Griesemerc2d55862009-02-19 16:49:10 -08006314<p>
Rob Pike46596852009-03-02 16:17:29 -08006315Here is a complete Go package that implements a concurrent prime sieve.
6316</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006317
Robert Griesemerc2d55862009-02-19 16:49:10 -08006318<pre>
6319package main
6320
Rob Pike46596852009-03-02 16:17:29 -08006321import "fmt"
6322
Robert Griesemer3c7271f2011-05-24 14:18:44 -07006323// Send the sequence 2, 3, 4, … to channel 'ch'.
Robert Griesemere1e76192009-09-25 14:11:03 -07006324func generate(ch chan&lt;- int) {
Robert Griesemerc2d55862009-02-19 16:49:10 -08006325 for i := 2; ; i++ {
Robert Griesemer130ac742009-12-10 16:43:01 -08006326 ch &lt;- i // Send 'i' to channel 'ch'.
Robert Griesemerc2d55862009-02-19 16:49:10 -08006327 }
6328}
6329
Fazlul Shahriar330139e2009-11-30 21:23:58 -08006330// Copy the values from channel 'src' to channel 'dst',
Robert Griesemerc2d55862009-02-19 16:49:10 -08006331// removing those divisible by 'prime'.
Robert Griesemere1e76192009-09-25 14:11:03 -07006332func filter(src &lt;-chan int, dst chan&lt;- int, prime int) {
David Symonds72a29792011-11-29 15:47:36 -08006333 for i := range src { // Loop over values received from 'src'.
Robert Griesemere1e76192009-09-25 14:11:03 -07006334 if i%prime != 0 {
Robert Griesemer130ac742009-12-10 16:43:01 -08006335 dst &lt;- i // Send 'i' to channel 'dst'.
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006336 }
6337 }
Robert Griesemerc2d55862009-02-19 16:49:10 -08006338}
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006339
Robert Griesemerc2d55862009-02-19 16:49:10 -08006340// The prime sieve: Daisy-chain filter processes together.
6341func sieve() {
Robert Griesemer130ac742009-12-10 16:43:01 -08006342 ch := make(chan int) // Create a new channel.
6343 go generate(ch) // Start generate() as a subprocess.
Robert Griesemerc2d55862009-02-19 16:49:10 -08006344 for {
Robert Griesemer130ac742009-12-10 16:43:01 -08006345 prime := &lt;-ch
6346 fmt.Print(prime, "\n")
6347 ch1 := make(chan int)
6348 go filter(ch, ch1, prime)
6349 ch = ch1
Robert Griesemerc2d55862009-02-19 16:49:10 -08006350 }
6351}
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006352
Robert Griesemerc2d55862009-02-19 16:49:10 -08006353func main() {
Robert Griesemer130ac742009-12-10 16:43:01 -08006354 sieve()
Robert Griesemerc2d55862009-02-19 16:49:10 -08006355}
6356</pre>
Robert Griesemer67153582008-12-16 14:45:09 -08006357
Russ Cox7c4f7cc2009-08-20 11:11:03 -07006358<h2 id="Program_initialization_and_execution">Program initialization and execution</h2>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006359
Russ Cox7c4f7cc2009-08-20 11:11:03 -07006360<h3 id="The_zero_value">The zero value</h3>
Rob Pike8f2330d2009-02-25 16:20:44 -08006361<p>
Robert Griesemer6962c152014-10-16 15:08:49 -07006362When storage is allocated for a <a href="#Variables">variable</a>,
6363either through a declaration or a call of <code>new</code>, or when
6364a new value is created, either through a composite literal or a call
6365of <code>make</code>,
6366and no explicit initialization is provided, the variable or value is
6367given a default value. Each element of such a variable or value is
Robert Griesemeref45e642009-08-21 11:25:00 -07006368set to the <i>zero value</i> for its type: <code>false</code> for booleans,
griesemera9f832a2017-08-24 15:20:18 +02006369<code>0</code> for numeric types, <code>""</code>
Robert Griesemer19b1d352009-09-24 19:36:48 -07006370for strings, and <code>nil</code> for pointers, functions, interfaces, slices, channels, and maps.
Rob Pikeff70f092009-02-20 13:36:14 -08006371This initialization is done recursively, so for instance each element of an
Rob Pike8f2330d2009-02-25 16:20:44 -08006372array of structs will have its fields zeroed if no value is specified.
6373</p>
Robert Griesemerc2d55862009-02-19 16:49:10 -08006374<p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006375These two simple declarations are equivalent:
Rob Pike8f2330d2009-02-25 16:20:44 -08006376</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006377
Robert Griesemerc2d55862009-02-19 16:49:10 -08006378<pre>
Robert Griesemer130ac742009-12-10 16:43:01 -08006379var i int
6380var i int = 0
Robert Griesemerc2d55862009-02-19 16:49:10 -08006381</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006382
Rob Pike8f2330d2009-02-25 16:20:44 -08006383<p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006384After
Rob Pike8f2330d2009-02-25 16:20:44 -08006385</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006386
Robert Griesemerc2d55862009-02-19 16:49:10 -08006387<pre>
Robert Griesemerb94c0d22011-01-19 23:07:21 -05006388type T struct { i int; f float64; next *T }
Robert Griesemer130ac742009-12-10 16:43:01 -08006389t := new(T)
Robert Griesemerc2d55862009-02-19 16:49:10 -08006390</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006391
Rob Pike8f2330d2009-02-25 16:20:44 -08006392<p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006393the following holds:
Rob Pike8f2330d2009-02-25 16:20:44 -08006394</p>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006395
Robert Griesemerc2d55862009-02-19 16:49:10 -08006396<pre>
6397t.i == 0
6398t.f == 0.0
6399t.next == nil
6400</pre>
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006401
Rob Pike96750f12009-02-27 16:47:48 -08006402<p>
6403The same would also be true after
6404</p>
6405
6406<pre>
6407var t T
6408</pre>
6409
Robert Griesemera4366982014-05-20 13:51:39 -07006410<h3 id="Package_initialization">Package initialization</h3>
Robert Griesemer259f0ff2014-09-29 12:44:50 -07006411
Rob Pike8f2330d2009-02-25 16:20:44 -08006412<p>
Robert Griesemer451cf3e2019-05-08 13:21:02 -07006413Within a package, package-level variable initialization proceeds stepwise,
6414with each step selecting the variable earliest in <i>declaration order</i>
6415which has no dependencies on uninitialized variables.
Robert Griesemer259f0ff2014-09-29 12:44:50 -07006416</p>
6417
6418<p>
6419More precisely, a package-level variable is considered <i>ready for
6420initialization</i> if it is not yet initialized and either has
6421no <a href="#Variable_declarations">initialization expression</a> or
Robert Griesemer451cf3e2019-05-08 13:21:02 -07006422its initialization expression has no <i>dependencies</i> on uninitialized variables.
Robert Griesemer259f0ff2014-09-29 12:44:50 -07006423Initialization proceeds by repeatedly initializing the next package-level
6424variable that is earliest in declaration order and ready for initialization,
6425until there are no variables ready for initialization.
6426</p>
6427
6428<p>
6429If any variables are still uninitialized when this
6430process ends, those variables are part of one or more initialization cycles,
6431and the program is not valid.
6432</p>
6433
6434<p>
Robert Griesemer451cf3e2019-05-08 13:21:02 -07006435Multiple variables on the left-hand side of a variable declaration initialized
6436by single (multi-valued) expression on the right-hand side are initialized
6437together: If any of the variables on the left-hand side is initialized, all
6438those variables are initialized in the same step.
6439</p>
6440
6441<pre>
6442var x = a
6443var a, b = f() // a and b are initialized together, before x is initialized
6444</pre>
6445
6446<p>
6447For the purpose of package initialization, <a href="#Blank_identifier">blank</a>
6448variables are treated like any other variables in declarations.
6449</p>
6450
6451<p>
Robert Griesemer259f0ff2014-09-29 12:44:50 -07006452The declaration order of variables declared in multiple files is determined
6453by the order in which the files are presented to the compiler: Variables
6454declared in the first file are declared before any of the variables declared
6455in the second file, and so on.
Rob Pike96750f12009-02-27 16:47:48 -08006456</p>
Robert Griesemera4366982014-05-20 13:51:39 -07006457
6458<p>
6459Dependency analysis does not rely on the actual values of the
6460variables, only on lexical <i>references</i> to them in the source,
Robert Griesemer259f0ff2014-09-29 12:44:50 -07006461analyzed transitively. For instance, if a variable <code>x</code>'s
6462initialization expression refers to a function whose body refers to
6463variable <code>y</code> then <code>x</code> depends on <code>y</code>.
Robert Griesemera4366982014-05-20 13:51:39 -07006464Specifically:
6465</p>
6466
6467<ul>
6468<li>
6469A reference to a variable or function is an identifier denoting that
6470variable or function.
6471</li>
6472
6473<li>
6474A reference to a method <code>m</code> is a
6475<a href="#Method_values">method value</a> or
Robin Eklindcac006a2014-08-30 10:27:01 -07006476<a href="#Method_expressions">method expression</a> of the form
Robert Griesemera4366982014-05-20 13:51:39 -07006477<code>t.m</code>, where the (static) type of <code>t</code> is
6478not an interface type, and the method <code>m</code> is in the
6479<a href="#Method_sets">method set</a> of <code>t</code>.
6480It is immaterial whether the resulting function value
6481<code>t.m</code> is invoked.
6482</li>
6483
6484<li>
Robin Eklindcac006a2014-08-30 10:27:01 -07006485A variable, function, or method <code>x</code> depends on a variable
Robert Griesemera4366982014-05-20 13:51:39 -07006486<code>y</code> if <code>x</code>'s initialization expression or body
6487(for functions and methods) contains a reference to <code>y</code>
6488or to a function or method that depends on <code>y</code>.
6489</li>
6490</ul>
6491
6492<p>
Robert Griesemera4366982014-05-20 13:51:39 -07006493For example, given the declarations
6494</p>
6495
Rob Pike96750f12009-02-27 16:47:48 -08006496<pre>
Robert Griesemera4366982014-05-20 13:51:39 -07006497var (
Robert Griesemer451cf3e2019-05-08 13:21:02 -07006498 a = c + b // == 9
6499 b = f() // == 4
6500 c = f() // == 5
6501 d = 3 // == 5 after initialization has finished
Robert Griesemera4366982014-05-20 13:51:39 -07006502)
6503
6504func f() int {
6505 d++
6506 return d
6507}
Rob Pike96750f12009-02-27 16:47:48 -08006508</pre>
Robert Griesemera4366982014-05-20 13:51:39 -07006509
Rob Pike96750f12009-02-27 16:47:48 -08006510<p>
Robert Griesemera4366982014-05-20 13:51:39 -07006511the initialization order is <code>d</code>, <code>b</code>, <code>c</code>, <code>a</code>.
Robert Griesemer451cf3e2019-05-08 13:21:02 -07006512Note that the order of subexpressions in initialization expressions is irrelevant:
6513<code>a = c + b</code> and <code>a = b + c</code> result in the same initialization
6514order in this example.
6515</p>
6516
6517<p>
6518Dependency analysis is performed per package; only references referring
6519to variables, functions, and (non-interface) methods declared in the current
6520package are considered. If other, hidden, data dependencies exists between
6521variables, the initialization order between those variables is unspecified.
6522</p>
6523
6524<p>
6525For instance, given the declarations
6526</p>
6527
6528<pre>
6529var x = I(T{}).ab() // x has an undetected, hidden dependency on a and b
6530var _ = sideEffect() // unrelated to x, a, or b
6531var a = b
6532var b = 42
6533
6534type I interface { ab() []int }
6535type T struct{}
6536func (T) ab() []int { return []int{a, b} }
6537</pre>
6538
6539<p>
6540the variable <code>a</code> will be initialized after <code>b</code> but
6541whether <code>x</code> is initialized before <code>b</code>, between
6542<code>b</code> and <code>a</code>, or after <code>a</code>, and
6543thus also the moment at which <code>sideEffect()</code> is called (before
6544or after <code>x</code> is initialized) is not specified.
Rob Pike8f2330d2009-02-25 16:20:44 -08006545</p>
Robert Griesemera4366982014-05-20 13:51:39 -07006546
Robert Griesemerc2d55862009-02-19 16:49:10 -08006547<p>
Robert Griesemera4366982014-05-20 13:51:39 -07006548Variables may also be initialized using functions named <code>init</code>
6549declared in the package block, with no arguments and no result parameters.
Rob Pike8cb91842009-09-15 11:56:39 -07006550</p>
Robert Griesemera4366982014-05-20 13:51:39 -07006551
6552<pre>
6553func init() { … }
6554</pre>
6555
Rob Pike8cb91842009-09-15 11:56:39 -07006556<p>
Robert Griesemera6563902016-08-25 21:01:17 -07006557Multiple such functions may be defined per package, even within a single
6558source file. In the package block, the <code>init</code> identifier can
6559be used only to declare <code>init</code> functions, yet the identifier
6560itself is not <a href="#Declarations_and_scope">declared</a>. Thus
Robert Griesemera4366982014-05-20 13:51:39 -07006561<code>init</code> functions cannot be referred to from anywhere
6562in a program.
Rob Pike8f2330d2009-02-25 16:20:44 -08006563</p>
Robert Griesemera4366982014-05-20 13:51:39 -07006564
Robert Griesemerc2d55862009-02-19 16:49:10 -08006565<p>
Robert Griesemera4366982014-05-20 13:51:39 -07006566A package with no imports is initialized by assigning initial values
6567to all its package-level variables followed by calling all <code>init</code>
Robert Griesemerc00043b2014-05-20 17:46:08 -07006568functions in the order they appear in the source, possibly in multiple files,
6569as presented to the compiler.
Robert Griesemerdf49fb32008-08-28 17:47:53 -07006570If a package has imports, the imported packages are initialized
Robert Griesemer566e3b22008-09-26 16:41:50 -07006571before initializing the package itself. If multiple packages import
Robert Griesemera4366982014-05-20 13:51:39 -07006572a package, the imported package will be initialized only once.
6573The importing of packages, by construction, guarantees that there
6574can be no cyclic initialization dependencies.
Rob Pike8f2330d2009-02-25 16:20:44 -08006575</p>
Robert Griesemera4366982014-05-20 13:51:39 -07006576
Robert Griesemerc2d55862009-02-19 16:49:10 -08006577<p>
Robert Griesemera4366982014-05-20 13:51:39 -07006578Package initialization&mdash;variable initialization and the invocation of
6579<code>init</code> functions&mdash;happens in a single goroutine,
6580sequentially, one package at a time.
6581An <code>init</code> function may launch other goroutines, which can run
6582concurrently with the initialization code. However, initialization
6583always sequences
6584the <code>init</code> functions: it will not invoke the next one
6585until the previous one has returned.
Rob Pike8f2330d2009-02-25 16:20:44 -08006586</p>
Robert Griesemera4366982014-05-20 13:51:39 -07006587
Robert Griesemer259f0ff2014-09-29 12:44:50 -07006588<p>
6589To ensure reproducible initialization behavior, build systems are encouraged
6590to present multiple files belonging to the same package in lexical file name
6591order to a compiler.
6592</p>
6593
Robert Griesemera4366982014-05-20 13:51:39 -07006594
6595<h3 id="Program_execution">Program execution</h3>
Robert Griesemerc2d55862009-02-19 16:49:10 -08006596<p>
Russ Coxa6736ca2011-02-03 13:40:51 -05006597A complete program is created by linking a single, unimported package
6598called the <i>main package</i> with all the packages it imports, transitively.
6599The main package must
6600have package name <code>main</code> and
Charles L. Dorian44262d12011-11-01 15:13:33 +09006601declare a function <code>main</code> that takes no
Russ Coxa6736ca2011-02-03 13:40:51 -05006602arguments and returns no value.
Rob Pike8f2330d2009-02-25 16:20:44 -08006603</p>
Robert Griesemer4dc25282008-09-09 10:37:19 -07006604
Robert Griesemerc2d55862009-02-19 16:49:10 -08006605<pre>
Robert Griesemer3c7271f2011-05-24 14:18:44 -07006606func main() { … }
Robert Griesemerc2d55862009-02-19 16:49:10 -08006607</pre>
Robert Griesemer4dc25282008-09-09 10:37:19 -07006608
Rob Pike8f2330d2009-02-25 16:20:44 -08006609<p>
Russ Coxa6736ca2011-02-03 13:40:51 -05006610Program execution begins by initializing the main package and then
6611invoking the function <code>main</code>.
Robert Griesemer7f1d62d2014-05-19 08:54:19 -07006612When that function invocation returns, the program exits.
Russ Coxa6736ca2011-02-03 13:40:51 -05006613It does not wait for other (non-<code>main</code>) goroutines to complete.
Rob Pike811dd252009-03-04 20:39:39 -08006614</p>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006615
Russ Coxd9877e22011-11-01 21:45:02 -04006616<h2 id="Errors">Errors</h2>
6617
6618<p>
6619The predeclared type <code>error</code> is defined as
6620</p>
6621
6622<pre>
6623type error interface {
6624 Error() string
6625}
6626</pre>
6627
6628<p>
6629It is the conventional interface for representing an error condition,
6630with the nil value representing no error.
6631For instance, a function to read data from a file might be defined:
6632</p>
6633
6634<pre>
6635func Read(f *File, b []byte) (n int, err error)
6636</pre>
6637
Evan Shaw21110c72010-04-22 10:14:53 -07006638<h2 id="Run_time_panics">Run-time panics</h2>
Rob Pike5bb29fb2010-03-25 17:59:59 -07006639
6640<p>
6641Execution errors such as attempting to index an array out
6642of bounds trigger a <i>run-time panic</i> equivalent to a call of
6643the built-in function <a href="#Handling_panics"><code>panic</code></a>
6644with a value of the implementation-defined interface type <code>runtime.Error</code>.
Charles L. Dorian9a358df2011-12-08 22:27:14 -05006645That type satisfies the predeclared interface type
Russ Coxd9877e22011-11-01 21:45:02 -04006646<a href="#Errors"><code>error</code></a>.
6647The exact error values that
6648represent distinct run-time error conditions are unspecified.
Rob Pike5bb29fb2010-03-25 17:59:59 -07006649</p>
6650
6651<pre>
6652package runtime
6653
6654type Error interface {
Russ Coxd9877e22011-11-01 21:45:02 -04006655 error
6656 // and perhaps other methods
Rob Pike5bb29fb2010-03-25 17:59:59 -07006657}
6658</pre>
6659
Russ Cox7c4f7cc2009-08-20 11:11:03 -07006660<h2 id="System_considerations">System considerations</h2>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006661
Russ Cox7c4f7cc2009-08-20 11:11:03 -07006662<h3 id="Package_unsafe">Package <code>unsafe</code></h3>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006663
Robert Griesemerc2d55862009-02-19 16:49:10 -08006664<p>
griesemerddc64de2017-10-17 13:38:10 -07006665The built-in package <code>unsafe</code>, known to the compiler
6666and accessible through the <a href="#Import_declarations">import path</a> <code>"unsafe"</code>,
Rob Pike96750f12009-02-27 16:47:48 -08006667provides facilities for low-level programming including operations
6668that violate the type system. A package using <code>unsafe</code>
Robert Griesemer5361b742014-10-23 09:45:11 -07006669must be vetted manually for type safety and may not be portable.
6670The package provides the following interface:
Rob Pikef27e9f02009-02-23 19:22:05 -08006671</p>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006672
Rob Pikeff70f092009-02-20 13:36:14 -08006673<pre class="grammar">
Robert Griesemerc2d55862009-02-19 16:49:10 -08006674package unsafe
Robert Griesemer52c02c22009-02-11 13:46:30 -08006675
Robert Griesemer98b4f6a2009-05-12 21:37:46 -07006676type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type
6677type Pointer *ArbitraryType
Robert Griesemer52c02c22009-02-11 13:46:30 -08006678
Robert Griesemereee70b02011-06-13 16:46:42 -07006679func Alignof(variable ArbitraryType) uintptr
Hong Ruiqi8374e672012-04-05 22:37:07 +10006680func Offsetof(selector ArbitraryType) uintptr
Robert Griesemereee70b02011-06-13 16:46:42 -07006681func Sizeof(variable ArbitraryType) uintptr
Robert Griesemerc2d55862009-02-19 16:49:10 -08006682</pre>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006683
Robert Griesemerc2d55862009-02-19 16:49:10 -08006684<p>
Robert Griesemere121de22013-10-07 10:43:28 -07006685A <code>Pointer</code> is a <a href="#Pointer_types">pointer type</a> but a <code>Pointer</code>
6686value may not be <a href="#Address_operators">dereferenced</a>.
Robert Griesemer5361b742014-10-23 09:45:11 -07006687Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to
Robert Griesemer86f5f7f2017-04-28 10:32:31 -07006688a type of underlying type <code>Pointer</code> and vice versa.
Robert Griesemer5361b742014-10-23 09:45:11 -07006689The effect of converting between <code>Pointer</code> and <code>uintptr</code> is implementation-defined.
Rob Pikef27e9f02009-02-23 19:22:05 -08006690</p>
Russ Cox81eb9302013-02-09 17:36:31 -05006691
6692<pre>
6693var f float64
6694bits = *(*uint64)(unsafe.Pointer(&amp;f))
6695
6696type ptr unsafe.Pointer
6697bits = *(*uint64)(ptr(&amp;f))
Robert Griesemere121de22013-10-07 10:43:28 -07006698
6699var p ptr = nil
Russ Cox81eb9302013-02-09 17:36:31 -05006700</pre>
6701
Robert Griesemerc2d55862009-02-19 16:49:10 -08006702<p>
Robert Griesemerc7631f52012-09-17 12:23:41 -07006703The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code>
6704of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code>
6705as if <code>v</code> was declared via <code>var v = x</code>.
Rob Pikef27e9f02009-02-23 19:22:05 -08006706</p>
Robert Griesemerc2d55862009-02-19 16:49:10 -08006707<p>
Robert Griesemer8c058b32012-09-18 11:25:53 -07006708The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a>
Robert Griesemer51338092013-03-07 20:11:37 -08006709<code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code>
6710or <code>*s</code>, and returns the field offset in bytes relative to the struct's address.
6711If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable
6712without pointer indirections through fields of the struct.
Rob Pike678625d2009-09-15 09:54:22 -07006713For a struct <code>s</code> with field <code>f</code>:
Rob Pikef27e9f02009-02-23 19:22:05 -08006714</p>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006715
Robert Griesemerc2d55862009-02-19 16:49:10 -08006716<pre>
Robert Griesemereee70b02011-06-13 16:46:42 -07006717uintptr(unsafe.Pointer(&amp;s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&amp;s.f))
Robert Griesemerc2d55862009-02-19 16:49:10 -08006718</pre>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006719
Robert Griesemerc2d55862009-02-19 16:49:10 -08006720<p>
Rob Pikef27e9f02009-02-23 19:22:05 -08006721Computer architectures may require memory addresses to be <i>aligned</i>;
6722that is, for addresses of a variable to be a multiple of a factor,
6723the variable's type's <i>alignment</i>. The function <code>Alignof</code>
6724takes an expression denoting a variable of any type and returns the
6725alignment of the (type of the) variable in bytes. For a variable
6726<code>x</code>:
6727</p>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006728
Robert Griesemerc2d55862009-02-19 16:49:10 -08006729<pre>
Robert Griesemereee70b02011-06-13 16:46:42 -07006730uintptr(unsafe.Pointer(&amp;x)) % unsafe.Alignof(x) == 0
Robert Griesemerc2d55862009-02-19 16:49:10 -08006731</pre>
Robert Griesemer533dfd62009-05-13 16:56:00 -07006732
Rob Pikef27e9f02009-02-23 19:22:05 -08006733<p>
6734Calls to <code>Alignof</code>, <code>Offsetof</code>, and
Robert Griesemereee70b02011-06-13 16:46:42 -07006735<code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>.
Rob Pikef27e9f02009-02-23 19:22:05 -08006736</p>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006737
Russ Cox7c4f7cc2009-08-20 11:11:03 -07006738<h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006739
Robert Griesemer997851e2009-09-25 15:36:25 -07006740<p>
Robert Griesemer462a17e2013-03-22 15:36:04 -07006741For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed:
Robert Griesemer997851e2009-09-25 15:36:25 -07006742</p>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006743
Rob Pikeff70f092009-02-20 13:36:14 -08006744<pre class="grammar">
Robert Griesemer777a96a2010-12-02 12:32:14 -08006745type size in bytes
Robert Griesemer52c02c22009-02-11 13:46:30 -08006746
Robert Griesemer777a96a2010-12-02 12:32:14 -08006747byte, uint8, int8 1
6748uint16, int16 2
6749uint32, int32, float32 4
6750uint64, int64, float64, complex64 8
6751complex128 16
Robert Griesemerc2d55862009-02-19 16:49:10 -08006752</pre>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006753
Robert Griesemerc2d55862009-02-19 16:49:10 -08006754<p>
Rob Pikef27e9f02009-02-23 19:22:05 -08006755The following minimal alignment properties are guaranteed:
Rob Pike4501d342009-02-19 17:31:36 -08006756</p>
Robert Griesemerc2d55862009-02-19 16:49:10 -08006757<ol>
Robert Griesemerdd916be2011-01-10 14:25:17 -08006758<li>For a variable <code>x</code> of any type: <code>unsafe.Alignof(x)</code> is at least 1.
Robert Griesemer3af480372010-05-14 13:11:48 -07006759</li>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006760
Rob Pikef27e9f02009-02-23 19:22:05 -08006761<li>For a variable <code>x</code> of struct type: <code>unsafe.Alignof(x)</code> is the largest of
Robert Griesemerdd916be2011-01-10 14:25:17 -08006762 all the values <code>unsafe.Alignof(x.f)</code> for each field <code>f</code> of <code>x</code>, but at least 1.
Robert Griesemer3af480372010-05-14 13:11:48 -07006763</li>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006764
Rob Pikef27e9f02009-02-23 19:22:05 -08006765<li>For a variable <code>x</code> of array type: <code>unsafe.Alignof(x)</code> is the same as
Robert Griesemere62aab12017-02-06 23:33:21 -08006766 the alignment of a variable of the array's element type.
Robert Griesemer3af480372010-05-14 13:11:48 -07006767</li>
Robert Griesemerc2d55862009-02-19 16:49:10 -08006768</ol>
Robert Griesemer52c02c22009-02-11 13:46:30 -08006769
Robert Griesemer1320ce02012-01-09 16:54:24 -08006770<p>
6771A 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.
6772</p>