89
88
canonicalized, so a single accented code point is distinct from the
90
89
same character constructed from combining an accent and a letter;
91
90
those are treated as two code points. For simplicity, this document
92
will use the term <i>character</i> to refer to a Unicode code point.
91
will use the unqualified term <i>character</i> to refer to a Unicode code point
95
95
Each code point is distinct; for instance, upper and lower case letters
99
99
Implementation restriction: For compatibility with other tools, a
100
100
compiler may disallow the NUL character (U+0000) in the source text.
103
Implementation restriction: For compatibility with other tools, a
104
compiler may ignore a UTF-8-encoded byte order mark
105
(U+FEFF) if it is the first Unicode code point in the source text.
106
A byte order mark may be disallowed anywhere else in the source.
103
109
<h3 id="Characters">Characters</h3>
116
In <a href="http://www.unicode.org/versions/Unicode6.0.0/">The Unicode Standard 6.0</a>,
122
In <a href="http://www.unicode.org/versions/Unicode6.2.0/">The Unicode Standard 6.2</a>,
117
123
Section 4.5 "General Category"
118
124
defines a set of character categories. Go treats
119
125
those characters in category Lu, Ll, Lt, Lm, or Lo as Unicode letters,
198
204
<a href="#Integer_literals">integer</a>,
199
205
<a href="#Floating-point_literals">floating-point</a>,
200
206
<a href="#Imaginary_literals">imaginary</a>,
201
<a href="#Character_literals">character</a>, or
207
<a href="#Rune_literals">rune</a>, or
202
208
<a href="#String_literals">string</a> literal
363
<h3 id="Character_literals">Character literals</h3>
369
<h3 id="Rune_literals">Rune literals</h3>
366
A character literal represents a <a href="#Constants">character constant</a>,
367
typically a Unicode code point, as one or more characters enclosed in single
368
quotes. Within the quotes, any character may appear except single
369
quote and newline. A single quoted character represents itself,
372
A rune literal represents a <a href="#Constants">rune constant</a>,
373
an integer value identifying a Unicode code point.
374
A rune literal is expressed as one or more characters enclosed in single quotes.
375
Within the quotes, any character may appear except single
376
quote and newline. A single quoted character represents the Unicode value
377
of the character itself,
370
378
while multi-character sequences beginning with a backslash encode
371
379
values in various formats.
380
388
a literal <code>a</code>-dieresis, U+00E4, value <code>0xe4</code>.
383
Several backslash escapes allow arbitrary values to be represented
384
as ASCII text. There are four ways to represent the integer value
391
Several backslash escapes allow arbitrary values to be encoded as
392
ASCII text. There are four ways to represent the integer value
385
393
as a numeric constant: <code>\x</code> followed by exactly two hexadecimal
386
394
digits; <code>\u</code> followed by exactly four hexadecimal digits;
387
395
<code>\U</code> followed by exactly eight hexadecimal digits, and a
409
417
\t U+0009 horizontal tab
410
418
\v U+000b vertical tab
411
419
\\ U+005c backslash
412
\' U+0027 single quote (valid escape only within character literals)
420
\' U+0027 single quote (valid escape only within rune literals)
413
421
\" U+0022 double quote (valid escape only within string literals)
416
All other sequences starting with a backslash are illegal inside character literals.
424
All other sequences starting with a backslash are illegal inside rune literals.
418
426
<pre class="ebnf">
419
char_lit = "'" ( unicode_value | byte_value ) "'" .
427
rune_lit = "'" ( unicode_value | byte_value ) "'" .
420
428
unicode_value = unicode_char | little_u_value | big_u_value | escaped_char .
421
429
byte_value = octal_byte_value | hex_byte_value .
422
430
octal_byte_value = `\` octal_digit octal_digit octal_digit .
453
466
Raw string literals are character sequences between back quotes
454
467
<code>``</code>. Within the quotes, any character is legal except
455
468
back quote. The value of a raw string literal is the
456
string composed of the uninterpreted characters between the quotes;
469
string composed of the uninterpreted (implicitly UTF-8-encoded) characters
457
471
in particular, backslashes have no special meaning and the string may
458
472
contain newlines.
459
473
Carriage returns inside raw string literals
464
478
quotes <code>""</code>. The text between the quotes,
465
479
which may not contain newlines, forms the
466
480
value of the literal, with backslash escapes interpreted as they
467
are in character literals (except that <code>\'</code> is illegal and
468
<code>\"</code> is legal). The three-digit octal (<code>\</code><i>nnn</i>)
481
are in rune literals (except that <code>\'</code> is illegal and
482
<code>\"</code> is legal), with the same restrictions.
483
The three-digit octal (<code>\</code><i>nnn</i>)
469
484
and two-digit hexadecimal (<code>\x</code><i>nn</i>) escapes represent individual
470
485
<i>bytes</i> of the resulting string; all other escapes represent
471
486
the (possibly multi-byte) UTF-8 encoding of individual <i>characters</i>.
502
519
"日本語" // UTF-8 input text
503
520
`日本語` // UTF-8 input text as a raw literal
504
"\u65e5\u672c\u8a9e" // The explicit Unicode code points
505
"\U000065e5\U0000672c\U00008a9e" // The explicit Unicode code points
506
"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // The explicit UTF-8 bytes
521
"\u65e5\u672c\u8a9e" // the explicit Unicode code points
522
"\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points
523
"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes
510
527
If the source code represents a character as two code points, such as
511
528
a combining form involving an accent and a letter, the result will be
512
an error if placed in a character literal (it is not a single code
529
an error if placed in a rune literal (it is not a single code
513
530
point), and will appear as two code points if placed in a string
518
535
<h2 id="Constants">Constants</h2>
520
537
<p>There are <i>boolean constants</i>,
521
<i>character constants</i>,
538
<i>rune constants</i>,
522
539
<i>integer constants</i>,
523
540
<i>floating-point constants</i>, <i>complex constants</i>,
524
541
and <i>string constants</i>. Character, integer, floating-point,
530
547
A constant value is represented by a
531
<a href="#Character_literals">character</a>,
548
<a href="#Rune_literals">rune</a>,
532
549
<a href="#Integer_literals">integer</a>,
533
550
<a href="#Floating-point_literals">floating-point</a>,
534
551
<a href="#Imaginary_literals">imaginary</a>,
624
641
A type determines the set of values and operations specific to values of that
625
type. A type may be specified by a (possibly qualified) <i>type name</i>
626
(§<a href="#Qualified_identifiers">Qualified identifier</a>, §<a href="#Type_declarations">Type declarations</a>) or a <i>type literal</i>,
642
type. A type may be specified by a
643
(possibly <a href="#Qualified_identifiers">qualified</a>)
644
<a href="#Type_declarations"><i>type name</i></a> or a <i>type literal</i>,
627
645
which composes a new type from previously declared types.
630
648
<pre class="ebnf">
631
649
Type = TypeName | TypeLit | "(" Type ")" .
632
TypeName = QualifiedIdent .
650
TypeName = identifier | QualifiedIdent .
633
651
TypeLit = ArrayType | StructType | PointerType | FunctionType | InterfaceType |
634
652
SliceType | MapType | ChannelType .
646
664
The <i>static type</i> (or just <i>type</i>) of a variable is the
647
665
type defined by its declaration. Variables of interface type
648
666
also have a distinct <i>dynamic type</i>, which
649
is the actual type of the value stored in the variable at run-time.
667
is the actual type of the value stored in the variable at run time.
650
668
The dynamic type may vary during execution but is always
651
669
<a href="#Assignability">assignable</a>
652
670
to the static type of the interface variable. For non-interface
766
784
A <i>string type</i> represents the set of string values.
767
Strings behave like slices of bytes but are immutable: once created,
785
A string value is a (possibly empty) sequence of bytes.
786
Strings are immutable: once created,
768
787
it is impossible to change the contents of a string.
769
788
The predeclared string type is <code>string</code>.
772
The elements of strings have type <code>byte</code> and may be
773
accessed using the usual <a href="#Indexes">indexing operations</a>. It is
774
illegal to take the address of such an element; if
775
<code>s[i]</code> is the <i>i</i>th byte of a
776
string, <code>&s[i]</code> is invalid. The length of string
777
<code>s</code> can be discovered using the built-in function
778
<code>len</code>. The length is a compile-time constant if <code>s</code>
792
The length of a string <code>s</code> (its size in bytes) can be discovered using
793
the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
794
The length is a compile-time constant if the string is a constant.
795
A string's bytes can be accessed by integer <a href="#Index_expressions">indices</a>
796
0 through <code>len(s)-1</code>.
797
It is illegal to take the address of such an element; if
798
<code>s[i]</code> is the <code>i</code>'th byte of a
799
string, <code>&s[i]</code> is invalid.
799
The length is part of the array's type and must be a
800
<a href="#Constant_expressions">constant expression</a> that evaluates to a non-negative
801
integer value. The length of array <code>a</code> can be discovered
802
using the built-in function <a href="#Length_and_capacity"><code>len(a)</code></a>.
803
The elements can be indexed by integer
804
indices 0 through <code>len(a)-1</code> (§<a href="#Indexes">Indexes</a>).
819
The length is part of the array's type; it must evaluate to a non-
820
negative <a href="#Constants">constant</a> representable by a value
821
of type <code>int</code>.
822
The length of array <code>a</code> can be discovered
823
using the built-in function <a href="#Length_and_capacity"><code>len</code></a>.
824
The elements can be addressed by integer <a href="#Index_expressions">indices</a>
825
0 through <code>len(a)-1</code>.
805
826
Array types are always one-dimensional but may be composed to form
806
827
multi-dimensional types.
817
838
<h3 id="Slice_types">Slice types</h3>
820
A slice is a reference to a contiguous segment of an array and
821
contains a numbered sequence of elements from that array. A slice
822
type denotes the set of all slices of arrays of its element type.
841
A slice is a descriptor for a contiguous segment of an array and
842
provides access to a numbered sequence of elements from that array.
843
A slice type denotes the set of all slices of arrays of its element type.
823
844
The value of an uninitialized slice is <code>nil</code>.
831
852
Like arrays, slices are indexable and have a length. The length of a
832
853
slice <code>s</code> can be discovered by the built-in function
833
<a href="#Length_and_capacity"><code>len(s)</code></a>; unlike with arrays it may change during
834
execution. The elements can be addressed by integer indices 0
835
through <code>len(s)-1</code> (§<a href="#Indexes">Indexes</a>). The slice index of a
854
<a href="#Length_and_capacity"><code>len</code></a>; unlike with arrays it may change during
855
execution. The elements can be addressed by integer <a href="#Index_expressions">indices</a>
856
0 through <code>len(s)-1</code>. The slice index of a
836
857
given element may be less than the index of the same element in the
837
858
underlying array.
846
867
The array underlying a slice may extend past the end of the slice.
847
868
The <i>capacity</i> is a measure of that extent: it is the sum of
848
869
the length of the slice and the length of the array beyond the slice;
849
a slice of length up to that capacity can be created by `slicing' a new
850
one from the original slice (§<a href="#Slices">Slices</a>).
870
a slice of length up to that capacity can be created by
871
<a href="#Slices"><i>slicing</i></a> a new one from the original slice.
851
872
The capacity of a slice <code>a</code> can be discovered using the
852
873
built-in function <a href="#Length_and_capacity"><code>cap(a)</code></a>.
994
1015
A field declaration may be followed by an optional string literal <i>tag</i>,
995
1016
which becomes an attribute for all the fields in the corresponding
996
1017
field declaration. The tags are made
997
visible through a <a href="#Package_unsafe">reflection interface</a>
1018
visible through a <a href="/pkg/reflect/#StructTag">reflection interface</a>
998
1019
but are otherwise ignored.
1047
1068
Within a list of parameters or results, the names (IdentifierList)
1048
1069
must either all be present or all be absent. If present, each name
1049
stands for one item (parameter or result) of the specified type; if absent, each
1050
type stands for one item of that type. Parameter and result
1070
stands for one item (parameter or result) of the specified type and
1071
all non-<a href="#Blank_identifier">blank</a> names in the signature
1072
must be <a href="#Uniqueness_of_identifiers">unique</a>.
1073
If absent, each type stands for one item of that type.
1074
Parameter and result
1051
1075
lists are always parenthesized except that if there is exactly
1052
1076
one unnamed result it may be written as an unparenthesized type.
1216
The comparison operators <code>==</code> and <code>!=</code>
1217
(§<a href="#Comparison_operators">Comparison operators</a>) must be fully defined
1240
The <a href="#Comparison_operators">comparison operators</a>
1241
<code>==</code> and <code>!=</code> must be fully defined
1218
1242
for operands of the key type; thus the key type must not be a function, map, or
1220
1244
If the key type is an interface type, these
1233
1257
The number of map elements is called its length.
1234
1258
For a map <code>m</code>, it can be discovered using the
1235
built-in function <a href="#Length_and_capacity"><code>len(m)</code></a>
1259
built-in function <a href="#Length_and_capacity"><code>len</code></a>
1236
1260
and may change during execution. Elements may be added during execution
1237
1261
using <a href="#Assignments">assignments</a> and retrieved with
1238
<a href="#Indexes">index</a> expressions; they may be removed with the
1262
<a href="#Index_expressions">index expressions</a>; they may be removed with the
1239
1263
<a href="#Deletion_of_map_elements"><code>delete</code></a> built-in function.
1446
1470
<h2 id="Blocks">Blocks</h2>
1449
A <i>block</i> is a sequence of declarations and statements within matching
1473
A <i>block</i> is a possibly empty sequence of declarations and statements
1474
within matching brace brackets.
1453
1477
<pre class="ebnf">
1454
Block = "{" { Statement ";" } "}" .
1478
Block = "{" StatementList "}" .
1479
StatementList = { Statement ";" } .
1467
1492
<li>Each file has a <i>file block</i> containing all Go source text
1468
1493
in that file.</li>
1470
<li>Each <code>if</code>, <code>for</code>, and <code>switch</code>
1495
<li>Each <a href="#If_statements">"if"</a>,
1496
<a href="#For_statements">"for"</a>, and
1497
<a href="#Switch_statements">"switch"</a>
1471
1498
statement is considered to be in its own implicit block.</li>
1473
<li>Each clause in a <code>switch</code> or <code>select</code> statement
1500
<li>Each clause in a <a href="#Switch_statements">"switch"</a>
1501
or <a href="#Select_statements">"select"</a> statement
1474
1502
acts as an implicit block.</li>
1510
1538
or function (but not method) declared at top level (outside any
1511
1539
function) is the package block.</li>
1513
<li>The scope of an imported package identifier is the file block
1541
<li>The scope of the package name of an imported package is the file block
1514
1542
of the file containing the import declaration.</li>
1516
<li>The scope of an identifier denoting a function parameter or
1517
result variable is the function body.</li>
1544
<li>The scope of an identifier denoting a method receiver, function parameter,
1545
or result variable is the function body.</li>
1519
1547
<li>The scope of a constant or variable identifier declared
1520
1548
inside a function begins at the end of the ConstSpec or VarSpec
1546
1574
Labels are declared by <a href="#Labeled_statements">labeled statements</a> and are
1547
used in the <code>break</code>, <code>continue</code>, and <code>goto</code>
1548
statements (§<a href="#Break_statements">Break statements</a>, §<a href="#Continue_statements">Continue statements</a>, §<a href="#Goto_statements">Goto statements</a>).
1575
used in the <a href="#Break_statements">"break"</a>,
1576
<a href="#Continue_statements">"continue"</a>, and
1577
<a href="#Goto_statements">"goto"</a> statements.
1549
1578
It is illegal to define a label that is never used.
1550
1579
In contrast to other identifiers, labels are not block scoped and do
1551
1580
not conflict with identifiers that are not labels. The scope of a label
1847
1876
If a list of expressions is given, the variables are initialized
1848
by assigning the expressions to the variables (§<a href="#Assignments">Assignments</a>)
1877
by <a href="#Assignments">assigning</a> the expressions to the variables
1849
1878
in order; all expressions must be consumed and all variables initialized from them.
1850
1879
Otherwise, each variable is initialized to its <a href="#The_zero_value">zero value</a>.
1899
1928
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they
1900
were originally declared in the same block with the same type, and at
1929
were originally declared earlier in the same block with the same type, and at
1901
1930
least one of the non-<a href="#Blank_identifier">blank</a> variables is new. As a consequence, redeclaration
1902
1931
can only appear in a multi-variable short declaration.
1903
1932
Redeclaration does not introduce a new
1908
1937
field1, offset := nextField(str, 0)
1909
1938
field2, offset := nextField(str, offset) // redeclares offset
1939
a, a := 1, 2 // illegal: double declaration of a or no new variable if a was declared elsewhere
1913
1943
Short variable declarations may appear only inside functions.
1914
In some contexts such as the initializers for <code>if</code>,
1915
<code>for</code>, or <code>switch</code> statements,
1916
they can be used to declare local temporary variables (§<a href="#Statements">Statements</a>).
1944
In some contexts such as the initializers for
1945
<a href="#If_statements">"if"</a>,
1946
<a href="#For_statements">"for"</a>, or
1947
<a href="#Switch_statements">"switch"</a> statements,
1948
they can be used to declare local temporary variables.
1919
1951
<h3 id="Function_declarations">Function declarations</h3>
1926
1958
<pre class="ebnf">
1927
FunctionDecl = "func" FunctionName Signature [ Body ] .
1959
FunctionDecl = "func" FunctionName ( Function | Signature ) .
1928
1960
FunctionName = identifier .
1961
Function = Signature FunctionBody .
1962
FunctionBody = Block .
1966
If the function's <a href="#Function_types">signature</a> declares
1967
result parameters, the function body's statement list must end in
1968
a <a href="#Terminating_statements">terminating statement</a>.
1972
func findMarker(c <-chan int) int {
1974
if x := <-c; isMarker(x) {
1978
// invalid: missing return statement.
1948
1998
<h3 id="Method_declarations">Method declarations</h3>
1951
A method is a function with a <i>receiver</i>.
1952
A method declaration binds an identifier, the <i>method name</i>, to a method.
1953
It also associates the method with the receiver's <i>base type</i>.
2001
A method is a <a href="#Function_declarations">function</a> with a <i>receiver</i>.
2002
A method declaration binds an identifier, the <i>method name</i>, to a method,
2003
and associates the method with the receiver's <i>base type</i>.
1956
2006
<pre class="ebnf">
1957
MethodDecl = "func" Receiver MethodName Signature [ Body ] .
2007
MethodDecl = "func" Receiver MethodName ( Function | Signature ) .
1958
2008
Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
1959
2009
BaseTypeName = identifier .
1972
For a base type, the non-<a href="#Blank_identifier">blank</a> names of
1973
methods bound to it must be <a href="#Uniqueness_of_identifiers">unique</a>.
2022
A non-<a href="#Blank_identifier">blank</a> receiver identifier must be
2023
<a href="#Uniqueness_of_identifiers">unique</a> in the method signature.
2024
If the receiver's value is not referenced inside the body of the method,
2025
its identifier may be omitted in the declaration. The same applies in
2026
general to parameters of functions and methods.
2030
For a base type, the non-blank names of methods bound to it must be unique.
1974
2031
If the base type is a <a href="#Struct_types">struct type</a>,
1975
2032
the non-blank method and field names must be distinct.
2000
If the receiver's value is not referenced inside the body of the method,
2001
its identifier may be omitted in the declaration. The same applies in
2002
general to parameters of functions and methods.
2006
2057
The type of a method is the type of a function with the receiver as first
2007
2058
argument. For instance, the method <code>Scale</code> has type
2026
2077
<h3 id="Operands">Operands</h3>
2029
Operands denote the elementary values in an expression.
2080
Operands denote the elementary values in an expression. An operand may be a
2081
literal, a (possibly <a href="#Qualified_identifiers">qualified</a>) identifier
2083
<a href="#Constant_declarations">constant</a>,
2084
<a href="#Variable_declarations">variable</a>, or
2085
<a href="#Function_declarations">function</a>,
2086
a <a href="#Method_expressions">method expression</a> yielding a function,
2087
or a parenthesized expression.
2032
2090
<pre class="ebnf">
2033
Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2091
Operand = Literal | OperandName | MethodExpr | "(" Expression ")" .
2034
2092
Literal = BasicLit | CompositeLit | FunctionLit .
2035
BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2093
BasicLit = int_lit | float_lit | imaginary_lit | rune_lit | string_lit .
2094
OperandName = identifier | QualifiedIdent.
2039
2097
<h3 id="Qualified_identifiers">Qualified identifiers</h3>
2042
A qualified identifier is a non-<a href="#Blank_identifier">blank</a> identifier
2043
qualified by a package name prefix.
2100
A qualified identifier is an identifier qualified with a package name prefix.
2101
Both the package name and the identifier must not be
2102
<a href="#Blank_identifier">blank</a>.
2046
2105
<pre class="ebnf">
2047
QualifiedIdent = [ PackageName "." ] identifier .
2106
QualifiedIdent = PackageName "." identifier .
2089
2148
to the respective field, element, and key types of the LiteralType;
2090
2149
there is no additional conversion.
2091
2150
The key is interpreted as a field name for struct literals,
2092
an index expression for array and slice literals, and a key for map literals.
2151
an index for array and slice literals, and a key for map literals.
2093
2152
For map literals, all elements must have a key. It is an error
2094
2153
to specify multiple elements with the same field name or
2095
2154
constant key value.
2102
2161
<li>A key must be a field name declared in the LiteralType.
2104
<li>A literal that does not contain any keys must
2163
<li>An element list that does not contain any keys must
2105
2164
list an element for each struct field in the
2106
2165
order in which the fields are declared.
2108
2167
<li>If any element has a key, every element must have a key.
2110
<li>A literal that contains keys does not need to
2169
<li>An element list that contains keys does not need to
2111
2170
have an element for each struct field. Omitted fields
2112
2171
get the zero value for that field.
2114
2173
<li>A literal may omit the element list; such a literal evaluates
2115
to the zero value for its type.
2174
to the zero value for its type.
2117
2176
<li>It is an error to specify an element for a non-exported
2118
2177
field of a struct belonging to a different package.
2198
2257
elements that are themselves composite literals may elide the respective
2199
2258
literal type if it is identical to the element type of <code>T</code>.
2200
2259
Similarly, elements that are addresses of composite literals may elide
2201
the <code>&T</code> when the the element type is <code>*T</code>.
2260
the <code>&T</code> when the element type is <code>*T</code>.
2251
2310
<h3 id="Function_literals">Function literals</h3>
2254
A function literal represents an anonymous function.
2255
It consists of a specification of the function type and a function body.
2313
A function literal represents an anonymous <a href="#Function_declarations">function</a>.
2258
2316
<pre class="ebnf">
2259
FunctionLit = FunctionType Body .
2317
FunctionLit = "func" Function .
2334
denotes the field or method <code>f</code> of the value denoted by <code>x</code>
2335
(or sometimes <code>*x</code>; see below). The identifier <code>f</code>
2336
is called the (field or method)
2337
<i>selector</i>; it must not be the <a href="#Blank_identifier">blank identifier</a>.
2338
The type of the expression is the type of <code>f</code>.
2393
denotes the field or method <code>f</code> of the value <code>x</code>
2394
(or sometimes <code>*x</code>; see below).
2395
The identifier <code>f</code> is called the (field or method) <i>selector</i>;
2396
it must not be the <a href="#Blank_identifier">blank identifier</a>.
2397
The type of the selector expression is the type of <code>f</code>.
2398
If <code>x</code> is a package name, see the section on
2399
<a href="#Qualified_identifiers">qualified identifiers</a>.
2341
2403
A selector <code>f</code> may denote a field or method <code>f</code> of
2342
2404
a type <code>T</code>, or it may refer
2343
to a field or method <code>f</code> of a nested anonymous field of
2405
to a field or method <code>f</code> of a nested
2406
<a href="#Struct_types">anonymous field</a> of <code>T</code>.
2345
2407
The number of anonymous fields traversed
2346
2408
to reach <code>f</code> is called its <i>depth</i> in <code>T</code>.
2347
2409
The depth of a field or method <code>f</code>
2364
2428
with shallowest depth, the selector expression is illegal.
2367
For a variable <code>x</code> of type <code>I</code>
2368
where <code>I</code> is an interface type,
2369
<code>x.f</code> denotes the actual method with name <code>f</code> of the value assigned
2370
to <code>x</code> if there is such a method.
2371
If no value or <code>nil</code> was assigned to <code>x</code>, <code>x.f</code> is illegal.
2431
For a variable <code>x</code> of type <code>I</code> where <code>I</code>
2432
is an interface type, <code>x.f</code> denotes the actual method with name
2433
<code>f</code> of the value assigned to <code>x</code>.
2434
If there is no method with name <code>f</code> in the
2435
<a href="#Method_sets">method set</a> of <code>I</code>, the selector
2436
expression is illegal.
2374
2439
In all other cases, <code>x.f</code> is illegal.
2442
If <code>x</code> is of pointer type and has the value
2443
<code>nil</code> and <code>x.f</code> denotes a struct field,
2444
assigning to or evaluating <code>x.f</code>
2445
causes a <a href="#Run_time_panics">run-time panic</a>.
2448
If <code>x</code> is of interface type and has the value
2449
<code>nil</code>, <a href="#Calls">calling</a> or
2450
<a href="#Method_values">evaluating</a> the method <code>x.f</code>
2451
causes a <a href="#Run_time_panics">run-time panic</a>.
2378
Selectors automatically dereference pointers to structs.
2456
Selectors automatically <a href="#Address_operators">dereference</a>
2457
pointers to structs.
2379
2458
If <code>x</code> is a pointer to a struct, <code>x.y</code>
2380
2459
is shorthand for <code>(*x).y</code>; if the field <code>y</code>
2381
2460
is also a pointer to a struct, <code>x.y.z</code> is shorthand
2535
If <code>a</code> is not a map:
2538
<li>the index <code>x</code> must be of integer type or untyped;
2539
it is <i>in range</i> if <code>0 <= x < len(a)</code>,
2540
otherwise it is <i>out of range</i></li>
2541
<li>a <a href="#Constants">constant</a> index must be non-negative
2542
and representable by a value of type <code>int</code>
2455
2546
For <code>a</code> of type <code>A</code> or <code>*A</code>
2456
where <code>A</code> is an <a href="#Array_types">array type</a>,
2457
or for <code>a</code> of type <code>S</code> where <code>S</code> is a <a href="#Slice_types">slice type</a>:
2547
where <code>A</code> is an <a href="#Array_types">array type</a>:
2460
<li><code>x</code> must be an integer value and <code>0 <= x < len(a)</code></li>
2550
<li>a <a href="#Constants">constant</a> index must be in range</li>
2551
<li>if <code>a</code> is <code>nil</code> or if <code>x</code> is out of range at run time,
2552
a <a href="#Run_time_panics">run-time panic</a> occurs</li>
2461
2553
<li><code>a[x]</code> is the array element at index <code>x</code> and the type of
2462
<code>a[x]</code> is the element type of <code>A</code></li>
2463
<li>if <code>a</code> is <code>nil</code> or if the index <code>x</code> is out of range,
2464
a <a href="#Run_time_panics">run-time panic</a> occurs</li>
2554
<code>a[x]</code> is the element type of <code>A</code></li>
2558
For <code>a</code> of type <code>S</code> where <code>S</code> is a <a href="#Slice_types">slice type</a>:
2561
<li>if the slice is <code>nil</code> or if <code>x</code> is out of range at run time,
2562
a <a href="#Run_time_panics">run-time panic</a> occurs</li>
2563
<li><code>a[x]</code> is the slice element at index <code>x</code> and the type of
2564
<code>a[x]</code> is the element type of <code>S</code></li>
2469
2569
where <code>T</code> is a <a href="#String_types">string type</a>:
2472
<li><code>x</code> must be an integer value and <code>0 <= x < len(a)</code></li>
2572
<li>a <a href="#Constants">constant</a> index must be in range
2573
if the string <code>a</code> is also constant</li>
2574
<li>if <code>x</code> is out of range at run time,
2575
a <a href="#Run_time_panics">run-time panic</a> occurs</li>
2473
2576
<li><code>a[x]</code> is the byte at index <code>x</code> and the type of
2474
<code>a[x]</code> is <code>byte</code></li>
2577
<code>a[x]</code> is <code>byte</code></li>
2475
2578
<li><code>a[x]</code> may not be assigned to</li>
2476
<li>if the index <code>x</code> is out of range,
2477
a <a href="#Run_time_panics">run-time panic</a> occurs</li>
2485
2586
<li><code>x</code>'s type must be
2486
<a href="#Assignability">assignable</a>
2487
to the key type of <code>M</code></li>
2587
<a href="#Assignability">assignable</a>
2588
to the key type of <code>M</code></li>
2488
2589
<li>if the map contains an entry with key <code>x</code>,
2489
<code>a[x]</code> is the map value with key <code>x</code>
2490
and the type of <code>a[x]</code> is the value type of <code>M</code></li>
2590
<code>a[x]</code> is the map value with key <code>x</code>
2591
and the type of <code>a[x]</code> is the value type of <code>M</code></li>
2491
2592
<li>if the map is <code>nil</code> or does not contain such an entry,
2492
<code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
2493
for the value type of <code>M</code></li>
2593
<code>a[x]</code> is the <a href="#The_zero_value">zero value</a>
2594
for the value type of <code>M</code></li>
2536
constructs a substring or slice. The index expressions <code>low</code> and
2637
constructs a substring or slice. The indices <code>low</code> and
2537
2638
<code>high</code> select which elements appear in the result. The result has
2538
indexes starting at 0 and length equal to
2639
indices starting at 0 and length equal to
2539
2640
<code>high</code> - <code>low</code>.
2540
2641
After slicing the array <code>a</code>
2571
For arrays or strings, the indexes <code>low</code> and <code>high</code> must
2572
satisfy 0 <= <code>low</code> <= <code>high</code> <= length; for
2573
slices, the upper bound is the capacity rather than the length.
2672
For arrays or strings, the indices <code>low</code> and <code>high</code> are
2673
<i>in range</i> if <code>0</code> <= <code>low</code> <= <code>high</code> <= <code>len(a)</code>,
2674
otherwise they are <i>out of range</i>.
2675
For slices, the upper index bound is the slice capacity <code>cap(a)</code> rather than the length.
2676
A <a href="#Constants">constant</a> index must be non-negative and representable by a value of type
2679
are constant, they must satisfy <code>low <= high</code>. If <code>a</code> is <code>nil</code>
2680
or if the indices are out of range at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
2601
2708
More precisely, if <code>T</code> is not an interface type, <code>x.(T)</code> asserts
2602
2709
that the dynamic type of <code>x</code> is <a href="#Type_identity">identical</a>
2603
2710
to the type <code>T</code>.
2711
In this case, <code>T</code> must <a href="#Method_sets">implement</a> the (interface) type of <code>x</code>;
2712
otherwise the type assertion is invalid since it is not possible for <code>x</code>
2713
to store a value of type <code>T</code>.
2604
2714
If <code>T</code> is an interface type, <code>x.(T)</code> asserts that the dynamic type
2605
of <code>x</code> implements the interface <code>T</code> (§<a href="#Interface_types">Interface types</a>).
2715
of <code>x</code> implements the interface <code>T</code>.
2608
2718
If the type assertion holds, the value of the expression is the value
2609
2719
stored in <code>x</code> and its type is <code>T</code>. If the type assertion is false,
2610
2720
a <a href="#Run_time_panics">run-time panic</a> occurs.
2611
2721
In other words, even though the dynamic type of <code>x</code>
2612
is known only at run-time, the type of <code>x.(T)</code> is
2722
is known only at run time, the type of <code>x.(T)</code> is
2613
2723
known to be <code>T</code> in a correct program.
2727
var x interface{} = 7 // x has dynamic type int and value 7
2728
i := x.(int) // i has type int and value 7
2730
type I interface { m() }
2732
s := y.(string) // illegal: string does not implement I (missing method m)
2733
r := y.(io.Reader) // r has type io.Reader and y must implement both I and io.Reader
2616
If a type assertion is used in an assignment or initialization of the form
2737
If a type assertion is used in an <a href="#Assignments">assignment</a> or initialization of the form
2680
As a special case, if the return parameters of a function or method
2801
As a special case, if the return values of a function or method
2681
2802
<code>g</code> are equal in number and individually
2682
2803
assignable to the parameters of another function or method
2683
2804
<code>f</code>, then the call <code>f(g(<i>parameters_of_g</i>))</code>
2684
2805
will invoke <code>f</code> after binding the return values of
2685
2806
<code>g</code> to the parameters of <code>f</code> in order. The call
2686
of <code>f</code> must contain no parameters other than the call of <code>g</code>.
2807
of <code>f</code> must contain no parameters other than the call of <code>g</code>,
2808
and <code>g</code> must have at least one return value.
2687
2809
If <code>f</code> has a final <code>...</code> parameter, it is
2688
2810
assigned the return values of <code>g</code> that remain after
2689
2811
assignment of regular parameters.
2805
2927
or be an untyped constant that can be converted to unsigned integer type.
2806
2928
If the left operand of a non-constant shift expression is an untyped constant,
2807
2929
the type of the constant is what it would be if the shift expression were
2808
replaced by its left operand alone; the type is <code>int</code> if it cannot
2809
be determined from the context (for instance, if the shift expression is an
2810
operand in a comparison against an untyped constant).
2930
replaced by its left operand alone.
2816
2936
var j int32 = 1<<s // 1 has type int32; j == 0
2817
2937
var k = uint64(1<<s) // 1 has type uint64; k == 1<<33
2818
2938
var m int = 1.0<<s // 1.0 has type int
2819
var n = 1.0<<s != 0 // 1.0 has type int; n == false if ints are 32bits in size
2939
var n = 1.0<<s != i // 1.0 has type int; n == false if ints are 32bits in size
2820
2940
var o = 1<<s == 2<<s // 1 and 2 have type int; o == true if ints are 32bits in size
2821
2941
var p = 1<<s == 1<<33 // illegal if ints are 32bits in size: 1 has type int, but 1<<33 overflows int
2822
2942
var u = 1.0<<s // illegal: 1.0 has type float64, cannot shift
2943
var u1 = 1.0<<s != 0 // illegal: 1.0 has type float64, cannot shift
2944
var u2 = 1<<s != 1.0 // illegal: 1 has type float64, cannot shift
2823
2945
var v float32 = 1<<s // illegal: 1 has type float32, cannot shift
2824
2946
var w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression
2835
2957
There are five precedence levels for binary operators.
2836
2958
Multiplication operators bind strongest, followed by addition
2837
operators, comparison operators, <code>&&</code> (logical and),
2838
and finally <code>||</code> (logical or):
2959
operators, comparison operators, <code>&&</code> (logical AND),
2960
and finally <code>||</code> (logical OR):
2841
2963
<pre class="grammar">
2878
3000
/ quotient integers, floats, complex values
2879
3001
% remainder integers
2881
& bitwise and integers
2882
| bitwise or integers
2883
^ bitwise xor integers
2884
&^ bit clear (and not) integers
3003
& bitwise AND integers
3004
| bitwise OR integers
3005
^ bitwise XOR integers
3006
&^ bit clear (AND NOT) integers
2886
3008
<< left shift integer << unsigned integer
2887
3009
>> right shift integer >> unsigned integer
2941
If the divisor is zero, a <a href="#Run_time_panics">run-time panic</a> occurs.
2942
If the dividend is positive and the divisor is a constant power of 2,
3063
If the divisor is a <a href="#Constants">constant</a>, it must not be zero.
3064
If the divisor is zero at run time, a <a href="#Run_time_panics">run-time panic</a> occurs.
3065
If the dividend is non-negative and the divisor is a constant power of 2,
2943
3066
the division may be replaced by a right shift, and computing the remainder may
2944
be replaced by a bitwise "and" operation:
3067
be replaced by a bitwise AND operation:
2979
For floating-point numbers,
3102
For floating-point and complex numbers,
2980
3103
<code>+x</code> is the same as <code>x</code>,
2981
3104
while <code>-x</code> is the negation of <code>x</code>.
2982
The result of a floating-point division by zero is not specified beyond the
3105
The result of a floating-point or complex division by zero is not specified beyond the
2983
3106
IEEE-754 standard; whether a <a href="#Run_time_panics">run-time panic</a>
2984
3107
occurs is implementation-specific.
2990
3113
For unsigned integer values, the operations <code>+</code>,
2991
3114
<code>-</code>, <code>*</code>, and <code><<</code> are
2992
3115
computed modulo 2<sup><i>n</i></sup>, where <i>n</i> is the bit width of
2993
the unsigned integer's type
2994
(§<a href="#Numeric_types">Numeric types</a>). Loosely speaking, these unsigned integer operations
3116
the <a href="#Numeric_types">unsigned integer</a>'s type.
3117
Loosely speaking, these unsigned integer operations
2995
3118
discard high bits upon overflow, and programs may rely on ``wrap around''.
3070
3193
Channel values are comparable.
3071
Two channel values are equal if they were created by the same call to <code>make</code>
3072
(§<a href="#Making_slices_maps_and_channels">Making slices, maps, and channels</a>)
3194
Two channel values are equal if they were created by the same call to
3195
<a href="#Making_slices_maps_and_channels"><code>make</code></a>
3073
3196
or if both have value <code>nil</code>.
3116
3239
is also allowed and follows from the general rules above.
3120
The result of a comparison can be assigned to any boolean type.
3121
If the context does not demand a specific boolean type,
3122
the result has type <code>bool</code>.
3243
const c = 3 < 4 // c is the untyped bool constant true
3126
3245
type MyBool bool
3130
b1 MyBool = x == y // result of comparison has type MyBool
3131
b2 bool = x == y // result of comparison has type bool
3132
b3 = x == y // result of comparison has type bool
3248
// The result of a comparison is an untyped bool.
3249
// The usual assignment rules apply.
3250
b3 = x == y // b3 has type bool
3251
b4 bool = x == y // b4 has type bool
3252
b5 MyBool = x == y // b5 has type MyBool
3182
3304
For an operand <code>ch</code> of <a href="#Channel_types">channel type</a>,
3183
3305
the value of the receive operation <code><-ch</code> is the value received
3184
from the channel <code>ch</code>. The type of the value is the element type of
3185
the channel. The expression blocks until a value is available.
3306
from the channel <code>ch</code>. The channel direction must permit receive operations,
3307
and the type of the receive operation is the element type of the channel.
3308
The expression blocks until a value is available.
3186
3309
Receiving from a <code>nil</code> channel blocks forever.
3310
Receiving from a <a href="#Close">closed</a> channel always succeeds,
3311
immediately returning the element type's <a href="#The_zero_value">zero
3207
yields an additional result.
3208
The boolean variable <code>ok</code> indicates whether
3209
the received value was sent on the channel (<code>true</code>)
3210
or is a <a href="#The_zero_value">zero value</a> returned
3211
because the channel is closed and empty (<code>false</code>).
3333
yields an additional result of type <code>bool</code> reporting whether the
3334
communication succeeded. The value of <code>ok</code> is <code>true</code>
3335
if the value received was delivered by a successful send operation to the
3336
channel, or <code>false</code> if it is a zero value generated because the
3337
channel is closed and empty.
3328
3457
That is, given <code>f := T.Mv</code>, <code>f</code> is invoked
3329
3458
as <code>f(t, 7)</code> not <code>t.f(7)</code>.
3330
3459
To construct a function that binds the receiver, use a
3331
<a href="#Function_literals">closure</a>.
3460
<a href="#Function_literals">function literal</a> or
3461
<a href="#Method_values">method value</a>.
3336
3466
The resulting function takes an explicit receiver of that interface type.
3469
<h3 id="Method_values">Method values</h3>
3472
If the expression <code>x</code> has static type <code>T</code> and
3473
<code>M</code> is in the <a href="#Method_sets">method set</a> of type <code>T</code>,
3474
<code>x.M</code> is called a <i>method value</i>.
3475
The method value <code>x.M</code> is a function value that is callable
3476
with the same arguments as a method call of <code>x.M</code>.
3477
The expression <code>x</code> is evaluated and saved during the evaluation of the
3478
method value; the saved copy is then used as the receiver in any calls,
3479
which may be executed later.
3483
The type <code>T</code> may be an interface or non-interface type.
3487
As in the discussion of <a href="#Method_expressions">method expressions</a> above,
3488
consider a struct type <code>T</code> with two methods,
3489
<code>Mv</code>, whose receiver is of type <code>T</code>, and
3490
<code>Mp</code>, whose receiver is of type <code>*T</code>.
3497
func (tv T) Mv(a int) int { return 0 } // value receiver
3498
func (tp *T) Mp(f float32) float32 { return 1 } // pointer receiver
3514
yields a function value of type
3522
These two invocations are equivalent:
3531
Similarly, the expression
3539
yields a function value of type
3543
func(float32) float32
3547
As with <a href="#Selectors">selectors</a>, a reference to a non-interface method with a value receiver
3548
using a pointer will automatically dereference that pointer: <code>pt.Mv</code> is equivalent to <code>(*pt).Mv</code>.
3552
As with <a href="#Calls">method calls</a>, a reference to a non-interface method with a pointer receiver
3553
using an addressable value will automatically take the address of that value: <code>t.Mv</code> is equivalent to <code>(&t).Mv</code>.
3557
f := t.Mv; f(7) // like t.Mv(7)
3558
f := pt.Mp; f(7) // like pt.Mp(7)
3559
f := pt.Mv; f(7) // like (*pt).Mv(7)
3560
f := t.Mp; f(7) // like (&t).Mp(7)
3561
f := makeT().Mp // invalid: result of makeT() is not addressable
3565
Although the examples above use non-interface types, it is also legal to create a method value
3566
from a value of interface type.
3570
var i interface { M(int) } = myVal
3571
f := i.M; f(7) // like i.M(7)
3339
3574
<h3 id="Conversions">Conversions</h3>
3347
3582
<pre class="ebnf">
3348
Conversion = Type "(" Expression ")" .
3583
Conversion = Type "(" Expression [ "," ] ")" .
3352
If the type starts with an operator it must be parenthesized:
3587
If the type starts with the operator <code>*</code> or <code><-</code>,
3588
or if the type starts with the keyword <code>func</code>
3589
and has no result list, it must be parenthesized when
3590
necessary to avoid ambiguity:
3356
3594
*Point(p) // same as *(Point(p))
3357
(*Point)(p) // p is converted to (*Point)
3595
(*Point)(p) // p is converted to *Point
3358
3596
<-chan int(c) // same as <-(chan int(c))
3359
(<-chan int)(c) // c is converted to (<-chan int)
3597
(<-chan int)(c) // c is converted to <-chan int
3598
func()(x) // function signature func() x
3599
(func())(x) // x is converted to func()
3600
(func() int)(x) // x is converted to func() int
3601
func() int(x) // x is converted to func() int (unambiguous)
3369
3611
<code>x</code> is representable by a value of type <code>T</code>.
3614
<code>x</code> is a floating-point constant,
3615
<code>T</code> is a floating-point type,
3616
and <code>x</code> is representable by a value
3617
of type <code>T</code> after rounding using
3618
IEEE 754 round-to-even rules.
3619
The constant <code>T(x)</code> is the rounded value.
3372
3622
<code>x</code> is an integer constant and <code>T</code> is a
3373
3623
<a href="#String_types">string type</a>.
3374
The same rule as for non-constant <code>x</code> applies in this case
3375
(§<a href="#Conversions_to_and_from_a_string_type">Conversions to and from a string type</a>).
3624
The <a href="#Conversions_to_and_from_a_string_type">same rule</a>
3625
as for non-constant <code>x</code> applies in this case.
3384
3634
uint(iota) // iota value of type uint
3385
3635
float32(2.718281828) // 2.718281828 of type float32
3386
3636
complex128(1) // 1.0 + 0.0i of type complex128
3637
float32(0.49999999) // 0.5 of type float32
3387
3638
string('x') // "x" of type string
3388
3639
string(0x266c) // "♬" of type string
3389
3640
MyString("foo" + "bar") // "foobar" of type MyString
3419
3670
<code>x</code>'s type and <code>T</code> are both complex types.
3422
<code>x</code> is an integer or has type <code>[]byte</code> or
3423
<code>[]rune</code> and <code>T</code> is a string type.
3673
<code>x</code> is an integer or a slice of bytes or runes
3674
and <code>T</code> is a string type.
3426
<code>x</code> is a string and <code>T</code> is <code>[]byte</code> or
3427
<code>[]rune</code>.
3677
<code>x</code> is a string and <code>T</code> is a slice of bytes or runes.
3561
3811
Except for shift operations, if the operands of a binary operation are
3562
3812
different kinds of untyped constants, the operation and, for non-boolean operations, the result use
3563
the kind that appears later in this list: integer, character, floating-point, complex.
3813
the kind that appears later in this list: integer, rune, floating-point, complex.
3564
3814
For example, an untyped integer constant divided by an
3565
3815
untyped complex constant yields an untyped complex constant.
3570
3820
an untyped boolean constant. If the left operand of a constant
3571
3821
<a href="#Operators">shift expression</a> is an untyped constant, the
3572
3822
result is an integer constant; otherwise it is a constant of the same
3573
type as the left operand, which must be of integer type
3574
(§<a href="#Arithmetic_operators">Arithmetic operators</a>).
3823
type as the left operand, which must be of
3824
<a href="#Numeric_types">integer type</a>.
3575
3825
Applying all other operators to untyped constants results in an untyped
3576
3826
constant of the same kind (that is, a boolean, integer, floating-point,
3577
3827
complex, or string constant).
3581
3831
const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant)
3582
3832
const b = 15 / 4 // b == 3 (untyped integer constant)
3583
3833
const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant)
3584
const Θ float64 = 3/2 // Θ == 1.5 (type float64)
3834
const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division)
3835
const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division)
3585
3836
const d = 1 << 3.0 // d == 8 (untyped integer constant)
3586
3837
const e = 1.0 << 3 // e == 8 (untyped integer constant)
3587
const f = int32(1) << 33 // f == 0 (type int32)
3838
const f = int32(1) << 33 // illegal (constant 8589934592 overflows int32)
3588
3839
const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant)
3589
3840
const h = "foo" > "bar" // h == true (untyped boolean constant)
3590
3841
const j = true // j == true (untyped boolean constant)
3591
const k = 'w' + 1 // k == 'x' (untyped character constant)
3842
const k = 'w' + 1 // k == 'x' (untyped rune constant)
3592
3843
const l = "hi" // l == "hi" (untyped string constant)
3593
3844
const m = string(k) // m == "x" (type string)
3594
3845
const Σ = 1 - 0.707i // (untyped complex constant)
3600
3851
Applying the built-in function <code>complex</code> to untyped
3601
integer, character, or floating-point constants yields
3852
integer, rune, or floating-point constants yields
3602
3853
an untyped complex constant.
3606
const ic = complex(0, c) // ic == 3.75i (untyped complex constant)
3607
const iΘ = complex(0, Θ) // iΘ == 1.5i (type complex128)
3857
const ic = complex(0, c) // ic == 3.75i (untyped complex constant)
3858
const iΘ = complex(0, Θ) // iΘ == 1.5i (type complex128)
3617
const Huge = 1 << 100
3618
const Four int8 = Huge >> 98
3868
const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (untyped integer constant)
3869
const Four int8 = Huge >> 98 // Four == 4 (type int8)
3873
The divisor of a constant division or remainder operation must not be zero:
3877
3.14 / 0.0 // illegal: division by zero
3627
3886
uint(-1) // -1 cannot be represented as a uint
3628
3887
int(3.14) // 3.14 cannot be represented as an int
3629
int64(Huge) // 1<<100 cannot be represented as an int64
3630
Four * 300 // 300 cannot be represented as an int8
3631
Four * 100 // 400 cannot be represented as an int8
3888
int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64
3889
Four * 300 // operand 300 cannot be represented as an int8 (type of Four)
3890
Four * 100 // product 400 cannot be represented as an int8 (type of Four)
3641
3900
^1 // untyped integer constant, equal to -2
3642
uint8(^1) // error, same as uint8(-2), out of range
3901
uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8
3643
3902
^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)
3644
3903
int8(^1) // same as int8(-2)
3645
3904
^int8(1) // same as -1 ^ int8(1) = -2
3668
3927
<h3 id="Order_of_evaluation">Order of evaluation</h3>
3671
When evaluating the elements of an assignment or expression,
3672
all function calls, method calls and
3930
When evaluating the <a href="#Operands">operands</a> of an expression,
3931
<a href="#Assignments">assignment</a>, or
3932
<a href="#Return_statements">return statement</a>,
3933
all function calls, method calls, and
3673
3934
communication operations are evaluated in lexical left-to-right
3689
3950
of <code>y</code> is not specified.
3955
f := func() int { a = 2; return 3 }
3956
x := []int{a, f()} // x may be [1, 3] or [2, 3]: evaluation order between a and f() is not specified
3693
3960
Floating-point operations within a single expression are evaluated according to
3694
3961
the associativity of the operators. Explicit parentheses affect the evaluation
3713
3980
SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt | Assignment | ShortVarDecl .
3983
<h3 id="Terminating_statements">Terminating statements</h3>
3986
A terminating statement is one of the following:
3991
A <a href="#Return_statements">"return"</a> or
3992
<a href="#Goto_statements">"goto"</a> statement.
3993
<!-- ul below only for regular layout -->
3998
A call to the built-in function
3999
<a href="#Handling_panics"><code>panic</code></a>.
4000
<!-- ul below only for regular layout -->
4005
A <a href="#Blocks">block</a> in which the statement list ends in a terminating statement.
4006
<!-- ul below only for regular layout -->
4011
An <a href="#If_statements">"if" statement</a> in which:
4013
<li>the "else" branch is present, and</li>
4014
<li>both branches are terminating statements.</li>
4019
A <a href="#For_statements">"for" statement</a> in which:
4021
<li>there are no "break" statements referring to the "for" statement, and</li>
4022
<li>the loop condition is absent.</li>
4027
A <a href="#Switch_statements">"switch" statement</a> in which:
4029
<li>there are no "break" statements referring to the "switch" statement,</li>
4030
<li>there is a default case, and</li>
4031
<li>the statement lists in each case, including the default, end in a terminating
4032
statement, or a possibly labeled <a href="#Fallthrough_statements">"fallthrough"
4038
A <a href="#Select_statements">"select" statement</a> in which:
4040
<li>there are no "break" statements referring to the "select" statement, and</li>
4041
<li>the statement lists in each case, including the default if present,
4042
end in a terminating statement.</li>
4047
A <a href="#Labeled_statements">labeled statement</a> labeling
4048
a terminating statement.
4053
All other statements are not terminating.
4057
A <a href="#Blocks">statement list</a> ends in a terminating statement if the list
4058
is not empty and its final statement is terminating.
3717
4062
<h3 id="Empty_statements">Empty statements</h3>
3745
4090
<h3 id="Expression_statements">Expression statements</h3>
3748
Function calls, method calls, and receive operations
4093
With the exception of specific built-in functions,
4094
function and method <a href="#Calls">calls</a> and
4095
<a href="#Receive_operator">receive operations</a>
3749
4096
can appear in statement context. Such statements may be parenthesized.
3767
4124
A send statement sends a value on a channel.
3768
The channel expression must be of <a href="#Channel_types">channel type</a>
3769
and the type of the value must be <a href="#Assignability">assignable</a>
4125
The channel expression must be of <a href="#Channel_types">channel type</a>,
4126
the channel direction must permit send operations,
4127
and the type of the value to be sent must be <a href="#Assignability">assignable</a>
3770
4128
to the channel's element type.
3886
4244
The assignment proceeds in two phases.
3887
First, the operands of <a href="#Indexes">index expressions</a>
4245
First, the operands of <a href="#Index_expressions">index expressions</a>
3888
4246
and <a href="#Address_operators">pointer indirections</a>
3889
4247
(including implicit pointer indirections in <a href="#Selectors">selectors</a>)
3890
4248
on the left and the expressions on the right are all
3926
4284
to type <code>bool</code>, <code>rune</code>, <code>int</code>, <code>float64</code>,
3927
4285
<code>complex128</code> or <code>string</code>
3928
4286
respectively, depending on whether the value is a
3929
boolean, character, integer, floating-point, complex, or string constant.
4287
boolean, rune, integer, floating-point, complex, or string constant.
4007
4365
<pre class="ebnf">
4008
4366
ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
4009
ExprCaseClause = ExprSwitchCase ":" { Statement ";" } .
4367
ExprCaseClause = ExprSwitchCase ":" StatementList .
4010
4368
ExprSwitchCase = "case" ExpressionList | "default" .
4014
In a case or default clause,
4015
the last statement only may be a "fallthrough" statement
4016
(§<a href="#Fallthrough_statements">Fallthrough statement</a>) to
4372
In a case or default clause, the last non-empty statement
4373
may be a (possibly <a href="#Labeled_statements">labeled</a>)
4374
<a href="#Fallthrough_statements">"fallthrough" statement</a> to
4017
4375
indicate that control should flow from the end of this clause to
4018
4376
the first statement of the next clause.
4019
4377
Otherwise control flows to the end of the "switch" statement.
4378
A "fallthrough" statement may appear as the last statement of all
4379
but the last clause of an expression switch.
4049
4409
A type switch compares types rather than values. It is otherwise similar
4050
4410
to an expression switch. It is marked by a special switch expression that
4051
4411
has the form of a <a href="#Type_assertions">type assertion</a>
4052
using the reserved word <code>type</code> rather than an actual type.
4053
Cases then match literal types against the dynamic type of the expression
4054
in the type assertion.
4412
using the reserved word <code>type</code> rather than an actual type:
4422
Cases then match actual types <code>T</code> against the dynamic type of the
4423
expression <code>x</code>. As with type assertions, <code>x</code> must be of
4424
<a href="#Interface_types">interface type</a>, and each non-interface type
4425
<code>T</code> listed in a case must implement the type of <code>x</code>.
4057
4428
<pre class="ebnf">
4058
4429
TypeSwitchStmt = "switch" [ SimpleStmt ";" ] TypeSwitchGuard "{" { TypeCaseClause } "}" .
4059
4430
TypeSwitchGuard = [ identifier ":=" ] PrimaryExpr "." "(" "type" ")" .
4060
TypeCaseClause = TypeSwitchCase ":" { Statement ";" } .
4431
TypeCaseClause = TypeSwitchCase ":" StatementList .
4061
4432
TypeSwitchCase = "case" TypeList | "default" .
4062
4433
TypeList = Type { "," Type } .
4088
4458
switch i := x.(type) {
4090
printString("x is nil")
4460
printString("x is nil") // type of i is type of x (interface{})
4092
printInt(i) // i is an int
4462
printInt(i) // type of i is int
4094
printFloat64(i) // i is a float64
4464
printFloat64(i) // type of i is float64
4095
4465
case func(int) float64:
4096
printFunction(i) // i is a function
4466
printFunction(i) // type of i is func(int) float64
4097
4467
case bool, string:
4098
printString("type is bool or string") // i is an interface{}
4468
printString("type is bool or string") // type of i is type of x (interface{})
4100
printString("don't know the type")
4470
printString("don't know the type") // type of i is type of x (interface{})
4109
4479
v := x // x is evaluated exactly once
4481
i := v // type of i is type of x (interface{})
4111
4482
printString("x is nil")
4112
4483
} else if i, isInt := v.(int); isInt {
4113
printInt(i) // i is an int
4484
printInt(i) // type of i is int
4114
4485
} else if i, isFloat64 := v.(float64); isFloat64 {
4115
printFloat64(i) // i is a float64
4486
printFloat64(i) // type of i is float64
4116
4487
} else if i, isFunc := v.(func(int) float64); isFunc {
4117
printFunction(i) // i is a function
4488
printFunction(i) // type of i is func(int) float64
4119
i1, isBool := v.(bool)
4120
i2, isString := v.(string)
4490
_, isBool := v.(bool)
4491
_, isString := v.(string)
4121
4492
if isBool || isString {
4123
printString("type is bool or string") // i is an interface{}
4493
i := v // type of i is type of x (interface{})
4494
printString("type is bool or string")
4126
printString("don't know the type") // i is an interface{}
4496
i := v // type of i is type of x (interface{})
4497
printString("don't know the type")
4208
4579
<pre class="ebnf">
4209
RangeClause = Expression [ "," Expression ] ( "=" | ":=" ) "range" Expression .
4580
RangeClause = ( ExpressionList "=" | IdentifierList ":=" ) "range" Expression .
4213
4584
The expression on the right in the "range" clause is called the <i>range expression</i>,
4214
which may be an array, pointer to an array, slice, string, map, or channel.
4585
which may be an array, pointer to an array, slice, string, map, or channel permitting
4586
<a href="#Receive_operator">receive operations</a>.
4215
4587
As with an assignment, the operands on the left must be
4216
4588
<a href="#Address_operators">addressable</a> or map index expressions; they
4217
4589
denote the iteration variables. If the range expression is a channel, only
4218
one iteration variable is permitted, otherwise there may be one or two.
4219
If the second iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
4590
one iteration variable is permitted, otherwise there may be one or two. In the latter case,
4591
if the second iteration variable is the <a href="#Blank_identifier">blank identifier</a>,
4220
4592
the range clause is equivalent to the same clause with only the first variable present.
4224
The range expression is evaluated once before beginning the loop
4225
except if the expression is an array, in which case, depending on
4226
the expression, it might not be evaluated (see below).
4596
The range expression is evaluated once before beginning the loop,
4597
with one exception. If the range expression is an array or a pointer to an array
4598
and only the first iteration value is present, only the range expression's
4599
length is evaluated; if that length is constant
4600
<a href="#Length_and_capacity">by definition</a>,
4601
the range expression itself will not be evaluated.
4227
4605
Function calls on the left are evaluated once per iteration.
4228
4606
For each iteration, iteration values are produced as follows:
4234
4612
array or slice a [n]E, *[n]E, or []E index i int a[i] E
4235
4613
string s string type index i int see below rune
4236
4614
map m map[K]V key k K m[k] V
4237
channel c chan E element e E
4615
channel c chan E, <-chan E element e E
4242
4620
For an array, pointer to array, or slice value <code>a</code>, the index iteration
4243
values are produced in increasing order, starting at element index 0. As a special
4244
case, if only the first iteration variable is present, the range loop produces
4621
values are produced in increasing order, starting at element index 0.
4622
If only the first iteration variable is present, the range loop produces
4245
4623
iteration values from 0 up to <code>len(a)</code> and does not index into the array
4246
4624
or slice itself. For a <code>nil</code> slice, the number of iterations is 0.
4261
4639
The iteration order over maps is not specified
4262
4640
and is not guaranteed to be the same from one iteration to the next.
4263
If map entries that have not yet been reached are deleted during iteration,
4641
If map entries that have not yet been reached are removed during iteration,
4264
4642
the corresponding iteration values will not be produced. If map entries are
4265
inserted during iteration, the behavior is implementation-dependent, but the
4266
iteration values for each entry will be produced at most once. If the map
4267
is <code>nil</code>, the number of iterations is 0.
4643
created during iteration, that entry may be produced during the iteration or
4644
may be skipped. The choice may vary for each entry created and from one
4645
iteration to the next.
4646
If the map is <code>nil</code>, the number of iterations is 0.
4327
4706
<h3 id="Go_statements">Go statements</h3>
4330
A "go" statement starts the execution of a function or method call
4709
A "go" statement starts the execution of a function call
4331
4710
as an independent concurrent thread of control, or <i>goroutine</i>,
4332
4711
within the same address space.
4340
The expression must be a call.
4719
The expression must be a function or method call; it cannot be parenthesized.
4720
Calls of built-in functions are restricted as for
4721
<a href="#Expression_statements">expression statements</a>.
4341
4725
The function value and parameters are
4342
4726
<a href="#Calls">evaluated as usual</a>
4343
4727
in the calling goroutine, but
4367
4751
<pre class="ebnf">
4368
4752
SelectStmt = "select" "{" { CommClause } "}" .
4369
CommClause = CommCase ":" { Statement ";" } .
4753
CommClause = CommCase ":" StatementList .
4370
4754
CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
4371
RecvStmt = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
4755
RecvStmt = [ ExpressionList "=" | IdentifierList ":=" ] RecvExpr .
4372
4756
RecvExpr = Expression .
4385
4769
chosen and the corresponding communication and statements are
4386
4770
evaluated. Otherwise, if there is a default case, that executes;
4387
4771
if there is no default case, the statement blocks until one of the communications can
4772
complete. There can be at most one default case and it may appear anywhere in the
4389
4774
If there are no cases with non-<code>nil</code> channels,
4390
4775
the statement blocks forever.
4391
4776
Even if the statement blocks,
4437
4822
<h3 id="Return_statements">Return statements</h3>
4440
A "return" statement terminates execution of the containing function
4441
and optionally provides a result value or values to the caller.
4825
A "return" statement in a function <code>F</code> terminates the execution
4826
of <code>F</code>, and optionally provides one or more result values.
4827
Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
4828
are executed before <code>F</code> returns to its caller.
4444
4831
<pre class="ebnf">
4490
4877
<li>The expression list may be empty if the function's result
4491
type specifies names for its result parameters (§<a href="#Function_types">Function Types</a>).
4878
type specifies names for its <a href="#Function_types">result parameters</a>.
4492
4879
The result parameters act as ordinary local variables
4493
4880
and the function may assign values to them as necessary.
4494
4881
The "return" statement returns the values of these variables.
4511
Regardless of how they are declared, all the result values are initialized to the zero values for their type (§<a href="#The_zero_value">The zero value</a>) upon entry to the function.
4898
Regardless of how they are declared, all the result values are initialized to
4899
the <a href="#The_zero_value">zero values</a> for their type upon entry to the
4900
function. A "return" statement that specifies results sets the result parameters before
4901
any deferred functions are executed.
4525
4915
A "break" statement terminates execution of the innermost
4526
"for", "switch" or "select" statement.
4916
<a href="#For_statements">"for"</a>,
4917
<a href="#Switch_statements">"switch"</a>, or
4918
<a href="#Select_statements">"select"</a> statement.
4529
4921
<pre class="ebnf">
4534
4926
If there is a label, it must be that of an enclosing
4535
"for", "switch" or "select" statement, and that is the one whose execution
4537
(§<a href="#For_statements">For statements</a>, §<a href="#Switch_statements">Switch statements</a>, §<a href="#Select_statements">Select statements</a>).
4927
"for", "switch", or "select" statement,
4928
and that is the one whose execution terminates.
4625
5015
A "fallthrough" statement transfers control to the first statement of the
4626
next case clause in a expression "switch" statement (§<a href="#Expression_switches">Expression switches</a>). It may
4627
be used only as the final non-empty statement in a case or default clause in an
4628
expression "switch" statement.
5016
next case clause in a <a href="#Expression_switches">expression "switch" statement</a>.
5017
It may be used only as the final non-empty statement in such a clause.
4631
5020
<pre class="ebnf">
4636
5025
<h3 id="Defer_statements">Defer statements</h3>
4639
A "defer" statement invokes a function whose execution is deferred to the moment
4640
the surrounding function returns.
5028
A "defer" statement invokes a function whose execution is deferred
5029
to the moment the surrounding function returns, either because the
5030
surrounding function executed a <a href="#Return_statements">return statement</a>,
5031
reached the end of its <a href="#Function_declarations">function body</a>,
5032
or because the corresponding goroutine is <a href="#Handling_panics">panicking</a>.
4643
5035
<pre class="ebnf">
4648
The expression must be a function or method call.
5040
The expression must be a function or method call; it cannot be parenthesized.
5041
Calls of built-in functions are restricted as for
5042
<a href="#Expression_statements">expression statements</a>.
4649
5046
Each time the "defer" statement
4650
5047
executes, the function value and parameters to the call are
4651
5048
<a href="#Calls">evaluated as usual</a>
4652
and saved anew but the
4653
actual function is not invoked.
4654
Instead, deferred calls are executed in LIFO order
4655
immediately before the surrounding function returns,
4656
after the return values, if any, have been evaluated, but before they
4657
are returned to the caller. For instance, if the deferred function is
5049
and saved anew but the actual function body is not executed.
5050
Instead, deferred functions are executed immediately before
5051
the surrounding function returns, in the reverse order
5056
For instance, if the deferred function is
4658
5057
a <a href="#Function_literals">function literal</a> and the surrounding
4659
5058
function has <a href="#Function_types">named result parameters</a> that
4660
5059
are in scope within the literal, the deferred function may access and modify
4661
5060
the result parameters before they are returned.
4662
5061
If the deferred function has any return values, they are discarded when
4663
5062
the function completes.
5063
(See also the section on <a href="#Handling_panics">handling panics</a>.)
4771
5172
The built-in function <code>new</code> takes a type <code>T</code> and
4772
5173
returns a value of type <code>*T</code>.
4773
The memory is initialized as described in the section on initial values
4774
(§<a href="#The_zero_value">The zero value</a>).
5174
The memory is initialized as described in the section on
5175
<a href="#The_zero_value">initial values</a>.
4777
5178
<pre class="grammar">
4797
5198
<h3 id="Making_slices_maps_and_channels">Making slices, maps and channels</h3>
4800
Slices, maps and channels are reference types that do not require the
4801
extra indirection of an allocation with <code>new</code>.
4802
5201
The built-in function <code>make</code> takes a type <code>T</code>,
4803
5202
which must be a slice, map or channel type,
4804
5203
optionally followed by a type-specific list of expressions.
4805
5204
It returns a value of type <code>T</code> (not <code>*T</code>).
4806
The memory is initialized as described in the section on initial values
4807
(§<a href="#The_zero_value">The zero value</a>).
5205
The memory is initialized as described in the section on
5206
<a href="#The_zero_value">initial values</a>.
4810
5209
<pre class="grammar">
4825
The arguments <code>n</code> and <code>m</code> must be of integer type.
4826
A <a href="#Run_time_panics">run-time panic</a> occurs if <code>n</code>
4827
is negative or larger than <code>m</code>, or if <code>n</code> or
4828
<code>m</code> cannot be represented by an <code>int</code>.
5224
The size arguments <code>n</code> and <code>m</code> must be of integer type or untyped.
5225
A <a href="#Constants">constant</a> size argument must be non-negative and
5226
representable by a value of type <code>int</code>.
5227
If both <code>n</code> and <code>m</code> are provided and are constant, then
5228
<code>n</code> must be no larger than <code>m</code>.
5229
If <code>n</code> is negative or larger than <code>m</code> at run time,
5230
a <a href="#Run_time_panics">run-time panic</a> occurs.
4832
5234
s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100
4833
s := make([]int, 10) // slice with len(s) == cap(s) == 10
5235
s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000
5236
s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type int
5237
s := make([]int, 10, 0) // illegal: len(s) > cap(s)
4834
5238
c := make(chan int, 10) // channel with a buffer size of 10
4835
5239
m := make(map[string]int, 100) // map with initial space for 100 elements
4872
5279
s0 := []int{0, 0}
4873
s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2}
4874
s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7}
4875
s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
5280
s1 := append(s0, 2) // append a single element s1 == []int{0, 0, 2}
5281
s2 := append(s1, 3, 5, 7) // append multiple elements s2 == []int{0, 0, 2, 3, 5, 7}
5282
s3 := append(s2, s0...) // append a slice s3 == []int{0, 0, 2, 3, 5, 7, 0, 0}
5283
s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 == []int{3, 5, 7, 2, 3, 5, 7, 0, 0}
4877
5285
var t []interface{}
4878
t = append(t, 42, 3.1415, "foo") t == []interface{}{42, 3.1415, "foo"}
5286
t = append(t, 42, 3.1415, "foo") t == []interface{}{42, 3.1415, "foo"}
4881
b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' }
5289
b = append(b, "bar"...) // append string contents b == []byte{'b', 'a', 'r' }
4885
5293
The function <code>copy</code> copies slice elements from
4886
5294
a source <code>src</code> to a destination <code>dst</code> and returns the
4887
number of elements copied. Source and destination may overlap.
5295
number of elements copied.
4888
5296
Both arguments must have <a href="#Type_identity">identical</a> element type <code>T</code> and must be
4889
5297
<a href="#Assignability">assignable</a> to a slice of type <code>[]T</code>.
4890
5298
The number of elements copied is the minimum of
4930
If the element <code>m[k]</code> does not exist, <code>delete</code> is
4931
a no-op. Calling <code>delete</code> with a nil map causes a
4932
<a href="#Run_time_panics">run-time panic</a>.
5338
If the map <code>m</code> is <code>nil</code> or the element <code>m[k]</code>
5339
does not exist, <code>delete</code> is a no-op.
4991
When a function <code>F</code> calls <code>panic</code>, normal
4992
execution of <code>F</code> stops immediately. Any functions whose
4993
execution was <a href="#Defer_statements">deferred</a> by the
4994
invocation of <code>F</code> are run in the usual way, and then
4995
<code>F</code> returns to its caller. To the caller, <code>F</code>
4996
then behaves like a call to <code>panic</code>, terminating its own
4997
execution and running deferred functions. This continues until all
4998
functions in the goroutine have ceased execution, in reverse order.
4999
At that point, the program is
5000
terminated and the error condition is reported, including the value of
5001
the argument to <code>panic</code>. This termination sequence is
5002
called <i>panicking</i>.
5398
While executing a function <code>F</code>,
5399
an explicit call to <code>panic</code> or a <a href="#Run_time_panics">run-time panic</a>
5400
terminates the execution of <code>F</code>.
5401
Any functions <a href="#Defer_statements">deferred</a> by <code>F</code>
5402
are then executed as usual.
5403
Next, any deferred functions run by <code>F's</code> caller are run,
5404
and so on up to any deferred by the top-level function in the executing goroutine.
5405
At that point, the program is terminated and the error
5406
condition is reported, including the value of the argument to <code>panic</code>.
5407
This termination sequence is called <i>panicking</i>.
5012
5417
The <code>recover</code> function allows a program to manage behavior
5013
of a panicking goroutine. Executing a <code>recover</code> call
5014
<i>inside</i> a deferred function (but not any function called by it) stops
5015
the panicking sequence by restoring normal execution, and retrieves
5016
the error value passed to the call of <code>panic</code>. If
5017
<code>recover</code> is called outside the deferred function it will
5018
not stop a panicking sequence. In this case, or when the goroutine
5019
is not panicking, or if the argument supplied to <code>panic</code>
5020
was <code>nil</code>, <code>recover</code> returns <code>nil</code>.
5418
of a panicking goroutine.
5419
Suppose a function <code>G</code> defers a function <code>D</code> that calls
5420
<code>recover</code> and a panic occurs in a function on the same goroutine in which <code>G</code>
5422
When the running of deferred functions reaches <code>D</code>,
5423
the return value of <code>D</code>'s call to <code>recover</code> will be the value passed to the call of <code>panic</code>.
5424
If <code>D</code> returns normally, without starting a new
5425
<code>panic</code>, the panicking sequence stops. In that case,
5426
the state of functions called between <code>G</code> and the call to <code>panic</code>
5427
is discarded, and normal execution resumes.
5428
Any functions deferred by <code>G</code> before <code>D</code> are then run and <code>G</code>'s
5429
execution terminates by returning to its caller.
5433
The return value of <code>recover</code> is <code>nil</code> if any of the following conditions holds:
5437
<code>panic</code>'s argument was <code>nil</code>;
5440
the goroutine is not panicking;
5443
<code>recover</code> was not called directly by a deferred function.
5024
5448
The <code>protect</code> function in the example below invokes
5112
5536
An import declaration states that the source file containing the declaration
5113
5537
depends on functionality of the <i>imported</i> package
5114
5538
(<a href="#Program_initialization_and_execution">§Program initialization and execution</a>)
5115
and it enables access to <a href="#Exported_identifiers">exported</a> identifiers
5539
and enables access to <a href="#Exported_identifiers">exported</a> identifiers
5116
5540
of that package.
5117
5541
The import names an identifier (PackageName) to be used for access and an ImportPath
5118
5542
that specifies the package to be imported.
5146
5570
Implementation restriction: A compiler may restrict ImportPaths to
5147
5571
non-empty strings using only characters belonging to
5148
<a href="http://www.unicode.org/versions/Unicode6.0.0/">Unicode's</a>
5572
<a href="http://www.unicode.org/versions/Unicode6.2.0/">Unicode's</a>
5149
5573
L, M, N, P, and S general categories (the Graphic characters without
5150
5574
spaces) and may also exclude the characters
5151
5575
<code>!"#$%&'()*,:;<=>?[\]^`{|}</code>
5166
5590
Import declaration Local name of Sin
5168
5592
import "lib/math" math.Sin
5169
import M "lib/math" M.Sin
5593
import m "lib/math" m.Sin
5170
5594
import . "lib/math" Sin
5174
5598
An import declaration declares a dependency relation between
5175
5599
the importing and imported package.
5176
It is illegal for a package to import itself or to import a package without
5600
It is illegal for a package to import itself, directly or indirectly,
5601
or to directly import a package without
5177
5602
referring to any of its exported identifiers. To import a package solely for
5178
5603
its side-effects (initialization), use the <a href="#Blank_identifier">blank</a>
5179
5604
identifier as explicit package name:
5294
5719
defined in its source.
5295
A package may contain multiple
5296
<code>init</code> functions, even
5720
A package-scope or file-scope identifier
5721
with name <code>init</code> may only be
5722
declared to be a function with this signature.
5723
Multiple such functions may be defined, even
5297
5724
within a single source file; they execute
5298
5725
in unspecified order.
5301
5728
Within a package, package-level variables are initialized,
5302
and constant values are determined, in
5303
data-dependent order: if the initializer of <code>A</code>
5304
depends on the value of <code>B</code>, <code>A</code>
5729
and constant values are determined, according to
5730
order of reference: if the initializer of <code>A</code>
5731
depends on <code>B</code>, <code>A</code>
5305
5732
will be set after <code>B</code>.
5306
It is an error if such dependencies form a cycle.
5307
Dependency analysis is done lexically: <code>A</code>
5733
Dependency analysis does not depend on the actual values
5734
of the items being initialized, only on their appearance
5308
5737
depends on <code>B</code> if the value of <code>A</code>
5309
5738
contains a mention of <code>B</code>, contains a value
5310
5739
whose initializer
5311
5740
mentions <code>B</code>, or mentions a function that
5312
5741
mentions <code>B</code>, recursively.
5742
It is an error if such dependencies form a cycle.
5313
5743
If two items are not interdependent, they will be initialized
5314
in the order they appear in the source.
5744
in the order they appear in the source, possibly in multiple files,
5745
as presented to the compiler.
5315
5746
Since the dependency analysis is done per package, it can produce
5316
5747
unspecified results if <code>A</code>'s initializer calls a function defined
5317
5748
in another package that refers to <code>B</code>.
5433
Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted into
5434
a <code>Pointer</code> and vice versa.
5437
The function <code>Sizeof</code> takes an expression denoting a
5438
variable of any type and returns the size of the variable in bytes.
5441
The function <code>Offsetof</code> takes a selector (§<a href="#Selectors">Selectors</a>) denoting a struct
5442
field of any type and returns the field offset in bytes relative to the
5864
Any pointer or value of <a href="#Types">underlying type</a> <code>uintptr</code> can be converted to
5865
a <code>Pointer</code> type and vice versa.
5870
bits = *(*uint64)(unsafe.Pointer(&f))
5872
type ptr unsafe.Pointer
5873
bits = *(*uint64)(ptr(&f))
5877
The functions <code>Alignof</code> and <code>Sizeof</code> take an expression <code>x</code>
5878
of any type and return the alignment or size, respectively, of a hypothetical variable <code>v</code>
5879
as if <code>v</code> was declared via <code>var v = x</code>.
5882
The function <code>Offsetof</code> takes a (possibly parenthesized) <a href="#Selectors">selector</a>
5883
<code>s.f</code>, denoting a field <code>f</code> of the struct denoted by <code>s</code>
5884
or <code>*s</code>, and returns the field offset in bytes relative to the struct's address.
5885
If <code>f</code> is an <a href="#Struct_types">embedded field</a>, it must be reachable
5886
without pointer indirections through fields of the struct.
5444
5887
For a struct <code>s</code> with field <code>f</code>:
5465
5908
Calls to <code>Alignof</code>, <code>Offsetof</code>, and
5466
5909
<code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>.
5470
5912
<h3 id="Size_and_alignment_guarantees">Size and alignment guarantees</h3>
5473
For the numeric types (§<a href="#Numeric_types">Numeric types</a>), the following sizes are guaranteed:
5915
For the <a href="#Numeric_types">numeric types</a>, the following sizes are guaranteed:
5476
5918
<pre class="grammar">