The Go Programming Language Specification
Language version go1.24 (Dec 30, 2024)
Introduction
This is the reference manual for the Go programming language.The pre-Go1.18 version, without generics, can be foundhere.For more information and other documents, seego.dev.
Go is a general-purpose language designed with systems programmingin mind. It is strongly typed and garbage-collected and has explicitsupport for concurrent programming. Programs are constructed frompackages, whose properties allow efficient management ofdependencies.
The syntax is compact and simple to parse, allowing for easy analysisby automatic tools such as integrated development environments.
Notation
The syntax is specified using avariantof Extended Backus-Naur Form (EBNF):
Syntax = { Production } .Production = production_name "=" [ Expression ] "." .Expression = Term { "|" Term } .Term = Factor { Factor } .Factor = production_name | token [ "…" token ] | Group | Option | Repetition .Group = "(" Expression ")" .Option = "[" Expression "]" .Repetition = "{" Expression "}" .
Productions are expressions constructed from terms and the followingoperators, in increasing precedence:
| alternation() grouping[] option (0 or 1 times){} repetition (0 to n times)
Lowercase production names are used to identify lexical (terminal) tokens.Non-terminals are in CamelCase. Lexical tokens are enclosed indouble quotes""
or back quotes``
.
The forma … b
represents the set of characters froma
throughb
as alternatives. The horizontalellipsis…
is also used elsewhere in the spec to informally denote variousenumerations or code snippets that are not further specified. The character…
(as opposed to the three characters...
) is not a token of the Golanguage.
A link of the form [Go 1.xx] indicates that a describedlanguage feature (or some aspect of it) was changed or added with language version 1.xx andthus requires at minimum that language version to build.For details, see thelinked sectionin theappendix.
Source code representation
Source code is Unicode text encoded inUTF-8. The text is notcanonicalized, so a single accented code point is distinct from thesame character constructed from combining an accent and a letter;those are treated as two code points. For simplicity, this documentwill use the unqualified termcharacter to refer to a Unicode code pointin the source text.
Each code point is distinct; for instance, uppercase and lowercase lettersare different characters.
Implementation restriction: For compatibility with other tools, acompiler may disallow the NUL character (U+0000) in the source text.
Implementation restriction: For compatibility with other tools, acompiler may ignore a UTF-8-encoded byte order mark(U+FEFF) if it is the first Unicode code point in the source text.A byte order mark may be disallowed anywhere else in the source.
Characters
The following terms are used to denote specific Unicode character categories:
newline = /* the Unicode code point U+000A */ .unicode_char = /* an arbitrary Unicode code point except newline */ .unicode_letter = /* a Unicode code point categorized as "Letter" */ .unicode_digit = /* a Unicode code point categorized as "Number, decimal digit" */ .
InThe Unicode Standard 8.0,Section 4.5 "General Category" defines a set of character categories.Go treats all characters in any of the Letter categories Lu, Ll, Lt, Lm, or Loas Unicode letters, and those in the Number category Nd as Unicode digits.
Letters and digits
The underscore character_
(U+005F) is considered a lowercase letter.
letter =unicode_letter | "_" .decimal_digit = "0" … "9" .binary_digit = "0" | "1" .octal_digit = "0" … "7" .hex_digit = "0" … "9" | "A" … "F" | "a" … "f" .
Lexical elements
Comments
Comments serve as program documentation. There are two forms:
- Line comments start with the character sequence
//
and stop at the end of the line. - General comments start with the character sequence
/*
and stop with the first subsequent character sequence*/
.
A comment cannot start inside arune orstring literal, or inside a comment.A general comment containing no newlines acts like a space.Any other comment acts like a newline.
Tokens
Tokens form the vocabulary of the Go language.There are four classes:identifiers,keywords,operatorsand punctuation, andliterals.White space, formed fromspaces (U+0020), horizontal tabs (U+0009),carriage returns (U+000D), and newlines (U+000A),is ignored except as it separates tokensthat would otherwise combine into a single token. Also, a newline or end of filemay trigger the insertion of asemicolon.While breaking the input into tokens,the next token is the longest sequence of characters that form avalid token.
Semicolons
The formal syntax uses semicolons";"
as terminators ina number of productions. Go programs may omit most of these semicolonsusing the following two rules:
- When the input is broken into tokens, a semicolon is automatically insertedinto the token stream immediately after a line's final token if that token is
- anidentifier
- aninteger,floating-point,imaginary,rune, orstring literal
- one of thekeywords
break
,continue
,fallthrough
, orreturn
- one of theoperators and punctuation
++
,--
,)
,]
, or}
- To allow complex statements to occupy a single line, a semicolonmay be omitted before a closing
")"
or"}"
.
To reflect idiomatic use, code examples in this document elide semicolonsusing these rules.
Identifiers
Identifiers name program entities such as variables and types.An identifier is a sequence of one or more letters and digits.The first character in an identifier must be a letter.
identifier =letter {letter |unicode_digit } .
a_x9ThisVariableIsExportedαβ
Some identifiers arepredeclared.
Keywords
The following keywords are reserved and may not be used as identifiers.
break default func interface selectcase defer go map structchan else goto package switchconst fallthrough if range typecontinue for import return var
Operators and punctuation
The following character sequences representoperators(includingassignment operators) and punctuation[Go 1.18]:
+ & += &= && == != ( )- | -= |= || < <= [ ]* ^ *= ^= <- > >= { }/ << /= <<= ++ = := , ;% >> %= >>= -- ! ... . : &^ &^= ~
Integer literals
An integer literal is a sequence of digits representing aninteger constant.An optional prefix sets a non-decimal base:0b
or0B
for binary,0
,0o
, or0O
for octal,and0x
or0X
for hexadecimal[Go 1.13].A single0
is considered a decimal zero.In hexadecimal literals, lettersa
throughf
andA
throughF
represent values 10 through 15.
For readability, an underscore character_
may appear aftera base prefix or between successive digits; such underscores do not changethe literal's value.
int_lit =decimal_lit |binary_lit |octal_lit |hex_lit .decimal_lit = "0" | ( "1" … "9" ) [ [ "_" ]decimal_digits ] .binary_lit = "0" ( "b" | "B" ) [ "_" ]binary_digits .octal_lit = "0" [ "o" | "O" ] [ "_" ]octal_digits .hex_lit = "0" ( "x" | "X" ) [ "_" ]hex_digits .decimal_digits =decimal_digit { [ "_" ]decimal_digit } .binary_digits =binary_digit { [ "_" ]binary_digit } .octal_digits =octal_digit { [ "_" ]octal_digit } .hex_digits =hex_digit { [ "_" ]hex_digit } .
424_206000_6000o6000O600 // second character is capital letter 'O'0xBadFace0xBad_Face0x_67_7a_2f_cc_40_c6170141183460469231731687303715884105727170_141183_460469_231731_687303_715884_105727_42 // an identifier, not an integer literal42_ // invalid: _ must separate successive digits4__2 // invalid: only one _ at a time0_xBadFace // invalid: _ must separate successive digits
Floating-point literals
A floating-point literal is a decimal or hexadecimal representation of afloating-point constant.
A decimal floating-point literal consists of an integer part (decimal digits),a decimal point, a fractional part (decimal digits), and an exponent part(e
orE
followed by an optional sign and decimal digits).One of the integer part or the fractional part may be elided; one of the decimal pointor the exponent part may be elided.An exponent value exp scales the mantissa (integer and fractional part) by 10exp.
A hexadecimal floating-point literal consists of a0x
or0X
prefix, an integer part (hexadecimal digits), a radix point, a fractional part (hexadecimal digits),and an exponent part (p
orP
followed by an optional sign and decimal digits).One of the integer part or the fractional part may be elided; the radix point may be elided as well,but the exponent part is required. (This syntax matches the one given in IEEE 754-2008 §5.12.3.)An exponent value exp scales the mantissa (integer and fractional part) by 2exp[Go 1.13].
For readability, an underscore character_
may appear aftera base prefix or between successive digits; such underscores do not changethe literal value.
float_lit =decimal_float_lit |hex_float_lit .decimal_float_lit =decimal_digits "." [decimal_digits ] [decimal_exponent ] |decimal_digitsdecimal_exponent | "."decimal_digits [decimal_exponent ] .decimal_exponent = ( "e" | "E" ) [ "+" | "-" ]decimal_digits .hex_float_lit = "0" ( "x" | "X" )hex_mantissahex_exponent .hex_mantissa = [ "_" ]hex_digits "." [hex_digits ] | [ "_" ]hex_digits | "."hex_digits .hex_exponent = ( "p" | "P" ) [ "+" | "-" ]decimal_digits .
0.72.40072.40 // == 72.402.718281.e+06.67428e-111E6.25.12345E+51_5. // == 15.00.15e+0_2 // == 15.00x1p-2 // == 0.250x2.p10 // == 2048.00x1.Fp+0 // == 1.93750X.8p-0 // == 0.50X_1FFFP-16 // == 0.12498474121093750x15e-2 // == 0x15e - 2 (integer subtraction)0x.p1 // invalid: mantissa has no digits1p-2 // invalid: p exponent requires hexadecimal mantissa0x1.5e-2 // invalid: hexadecimal mantissa requires p exponent1_.5 // invalid: _ must separate successive digits1._5 // invalid: _ must separate successive digits1.5_e1 // invalid: _ must separate successive digits1.5e_1 // invalid: _ must separate successive digits1.5e1_ // invalid: _ must separate successive digits
Imaginary literals
An imaginary literal represents the imaginary part of acomplex constant.It consists of aninteger orfloating-point literalfollowed by the lowercase letteri
.The value of an imaginary literal is the value of the respectiveinteger or floating-point literal multiplied by the imaginary uniti[Go 1.13]
imaginary_lit = (decimal_digits |int_lit |float_lit) "i" .
For backward compatibility, an imaginary literal's integer part consistingentirely of decimal digits (and possibly underscores) is considered a decimalinteger, even if it starts with a leading0
.
0i0123i // == 123i for backward-compatibility0o123i // == 0o123 * 1i == 83i0xabci // == 0xabc * 1i == 2748i0.i2.71828i1.e+0i6.67428e-11i1E6i.25i.12345E+5i0x1p-2i // == 0x1p-2 * 1i == 0.25i
Rune literals
A rune literal represents arune constant,an integer value identifying a Unicode code point.A rune literal is expressed as one or more characters enclosed in single quotes,as in'x'
or'\n'
.Within the quotes, any character may appear except newline and unescaped singlequote. A single quoted character represents the Unicode valueof the character itself,while multi-character sequences beginning with a backslash encodevalues in various formats.
The simplest form represents the single character within the quotes;since Go source text is Unicode characters encoded in UTF-8, multipleUTF-8-encoded bytes may represent a single integer value. Forinstance, the literal'a'
holds a single byte representinga literala
, Unicode U+0061, value0x61
, while'ä'
holds two bytes (0xc3
0xa4
) representinga literala
-dieresis, U+00E4, value0xe4
.
Several backslash escapes allow arbitrary values to be encoded asASCII text. There are four ways to represent the integer valueas a numeric constant:\x
followed by exactly two hexadecimaldigits;\u
followed by exactly four hexadecimal digits;\U
followed by exactly eight hexadecimal digits, and aplain backslash\
followed by exactly three octal digits.In each case the value of the literal is the value represented bythe digits in the corresponding base.
Although these representations all result in an integer, they havedifferent valid ranges. Octal escapes must represent a value between0 and 255 inclusive. Hexadecimal escapes satisfy this conditionby construction. The escapes\u
and\U
represent Unicode code points so within them some values are illegal,in particular those above0x10FFFF
and surrogate halves.
After a backslash, certain single-character escapes represent special values:
\a U+0007 alert or bell\b U+0008 backspace\f U+000C form feed\n U+000A line feed or newline\r U+000D carriage return\t U+0009 horizontal tab\v U+000B vertical tab\\ U+005C backslash\' U+0027 single quote (valid escape only within rune literals)\" U+0022 double quote (valid escape only within string literals)
An unrecognized character following a backslash in a rune literal is illegal.
rune_lit = "'" (unicode_value |byte_value ) "'" .unicode_value =unicode_char |little_u_value |big_u_value |escaped_char .byte_value =octal_byte_value |hex_byte_value .octal_byte_value = `\`octal_digitoctal_digitoctal_digit .hex_byte_value = `\` "x"hex_digithex_digit .little_u_value = `\` "u"hex_digithex_digithex_digithex_digit .big_u_value = `\` "U"hex_digithex_digithex_digithex_digithex_digithex_digithex_digithex_digit .escaped_char = `\` ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | `\` | "'" | `"` ) .
'a''ä''本''\t''\000''\007''\377''\x07''\xff''\u12e4''\U00101234''\'' // rune literal containing single quote character'aa' // illegal: too many characters'\k' // illegal: k is not recognized after a backslash'\xa' // illegal: too few hexadecimal digits'\0' // illegal: too few octal digits'\400' // illegal: octal value over 255'\uDFFF' // illegal: surrogate half'\U00110000' // illegal: invalid Unicode code point
String literals
A string literal represents astring constantobtained from concatenating a sequence of characters. There are two forms:raw string literals and interpreted string literals.
Raw string literals are character sequences between back quotes, as in`foo`
. Within the quotes, any character may appear exceptback quote. The value of a raw string literal is thestring composed of the uninterpreted (implicitly UTF-8-encoded) charactersbetween the quotes;in particular, backslashes have no special meaning and the string maycontain newlines.Carriage return characters ('\r') inside raw string literalsare discarded from the raw string value.
Interpreted string literals are character sequences between doublequotes, as in"bar"
.Within the quotes, any character may appear except newline and unescaped double quote.The text between the quotes forms thevalue of the literal, with backslash escapes interpreted as theyare inrune literals (except that\'
is illegal and\"
is legal), with the same restrictions.The three-digit octal (\
nnn)and two-digit hexadecimal (\x
nn) escapes represent individualbytes of the resulting string; all other escapes representthe (possibly multi-byte) UTF-8 encoding of individualcharacters.Thus inside a string literal\377
and\xFF
representa single byte of value0xFF
=255, whileÿ
,\u00FF
,\U000000FF
and\xc3\xbf
representthe two bytes0xc3
0xbf
of the UTF-8 encoding of characterU+00FF.
string_lit =raw_string_lit |interpreted_string_lit .raw_string_lit = "`" {unicode_char |newline } "`" .interpreted_string_lit = `"` {unicode_value |byte_value } `"` .
`abc` // same as "abc"`\n\n` // same as "\\n\n\\n""\n""\"" // same as `"`"Hello, world!\n""日本語""\u65e5本\U00008a9e""\xff\u00FF""\uD800" // illegal: surrogate half"\U00110000" // illegal: invalid Unicode code point
These examples all represent the same string:
"日本語" // UTF-8 input text`日本語` // UTF-8 input text as a raw literal"\u65e5\u672c\u8a9e" // the explicit Unicode code points"\U000065e5\U0000672c\U00008a9e" // the explicit Unicode code points"\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e" // the explicit UTF-8 bytes
If the source code represents a character as two code points, such asa combining form involving an accent and a letter, the result will bean error if placed in a rune literal (it is not a single codepoint), and will appear as two code points if placed in a stringliteral.
Constants
There areboolean constants,rune constants,integer constants,floating-point constants,complex constants,andstring constants. Rune, integer, floating-point,and complex constants arecollectively callednumeric constants.
A constant value is represented by arune,integer,floating-point,imaginary,orstring literal,an identifier denoting a constant,aconstant expression,aconversion with a result that is a constant, orthe result value of some built-in functions such asmin
ormax
applied to constant arguments,unsafe.Sizeof
applied tocertain values,cap
orlen
applied tosome expressions,real
andimag
applied to a complex constantandcomplex
applied to numeric constants.The boolean truth values are represented by the predeclared constantstrue
andfalse
. The predeclared identifieriota denotes an integer constant.
In general, complex constants are a form ofconstant expressionand are discussed in that section.
Numeric constants represent exact values of arbitrary precision and do not overflow.Consequently, there are no constants denoting the IEEE 754 negative zero, infinity,and not-a-number values.
Constants may betyped oruntyped.Literal constants,true
,false
,iota
,and certainconstant expressionscontaining only untyped constant operands are untyped.
A constant may be given a type explicitly by aconstant declarationorconversion, or implicitly when used in avariable declaration or anassignment statement or as anoperand in anexpression.It is an error if the constant valuecannot berepresented as a value of the respective type.If the type is a type parameter, the constant is converted into a non-constantvalue of the type parameter.
An untyped constant has adefault type which is the type to which theconstant is implicitly converted in contexts where a typed value is required,for instance, in ashort variable declarationsuch asi := 0
where there is no explicit type.The default type of an untyped constant isbool
,rune
,int
,float64
,complex128
, orstring
respectively, depending on whether it is a boolean, rune, integer, floating-point,complex, or string constant.
Implementation restriction: Although numeric constants have arbitraryprecision in the language, a compiler may implement them using aninternal representation with limited precision. That said, everyimplementation must:
- Represent integer constants with at least 256 bits.
- Represent floating-point constants, including the parts of a complex constant, with a mantissa of at least 256 bits and a signed binary exponent of at least 16 bits.
- Give an error if unable to represent an integer constant precisely.
- Give an error if unable to represent a floating-point or complex constant due to overflow.
- Round to the nearest representable constant if unable to represent a floating-point or complex constant due to limits on precision.
These requirements apply both to literal constants and to the resultof evaluatingconstantexpressions.
Variables
A variable is a storage location for holding avalue.The set of permissible values is determined by thevariable'stype.
Avariable declarationor, for function parameters and results, the signatureof afunction declarationorfunction literal reservesstorage for a named variable.Calling the built-in functionnew
or taking the address of acomposite literalallocates storage for a variable at run time.Such an anonymous variable is referred to via a (possibly implicit)pointer indirection.
Structured variables ofarray,slice,andstruct types have elements and fields that maybeaddressed individually. Each such elementacts like a variable.
Thestatic type (or justtype) of a variable is thetype given in its declaration, the type provided in thenew
call or composite literal, or the type ofan element of a structured variable.Variables of interface type also have a distinctdynamic type,which is the (non-interface) type of the value assigned to the variable at run time(unless the value is the predeclared identifiernil
,which has no type).The dynamic type may vary during execution but values stored in interfacevariables are alwaysassignableto the static type of the variable.
var x interface{} // x is nil and has static type interface{}var v *T // v has value nil, static type *Tx = 42 // x has value 42 and dynamic type intx = v // x has value (*T)(nil) and dynamic type *T
A variable's value is retrieved by referring to the variable in anexpression; it is the most recent valueassigned to the variable.If a variable has not yet been assigned a value, its value is thezero value for its type.
Types
A type determines a set of values together with operations and methods specificto those values. A type may be denoted by atype name, if it has one, which must befollowed bytype arguments if the type is generic.A type may also be specified using atype literal, which composes a typefrom existing types.
Type =TypeName [TypeArgs ] |TypeLit | "("Type ")" .TypeName =identifier |QualifiedIdent .TypeArgs = "["TypeList [ "," ] "]" .TypeList =Type { ","Type } .TypeLit =ArrayType |StructType |PointerType |FunctionType |InterfaceType |SliceType |MapType |ChannelType .
The languagepredeclares certain type names.Others are introduced withtype declarationsortype parameter lists.Composite types—array, struct, pointer, function,interface, slice, map, and channel types—may be constructed usingtype literals.
Predeclared types, defined types, and type parameters are callednamed types.An alias denotes a named type if the type given in the alias declaration is a named type.
Boolean types
Aboolean type represents the set of Boolean truth valuesdenoted by the predeclared constantstrue
andfalse
. The predeclared boolean type isbool
;it is adefined type.
Numeric types
Aninteger,floating-point, orcomplex typerepresents the set of integer, floating-point, or complex values, respectively.They are collectively callednumeric types.The predeclared architecture-independent numeric types are:
uint8 the set of all unsigned 8-bit integers (0 to 255)uint16 the set of all unsigned 16-bit integers (0 to 65535)uint32 the set of all unsigned 32-bit integers (0 to 4294967295)uint64 the set of all unsigned 64-bit integers (0 to 18446744073709551615)int8 the set of all signed 8-bit integers (-128 to 127)int16 the set of all signed 16-bit integers (-32768 to 32767)int32 the set of all signed 32-bit integers (-2147483648 to 2147483647)int64 the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)float32 the set of all IEEE 754 32-bit floating-point numbersfloat64 the set of all IEEE 754 64-bit floating-point numberscomplex64 the set of all complex numbers with float32 real and imaginary partscomplex128 the set of all complex numbers with float64 real and imaginary partsbyte alias for uint8rune alias for int32
The value of ann-bit integer isn bits wide and represented usingtwo's complement arithmetic.
There is also a set of predeclared integer types with implementation-specific sizes:
uint either 32 or 64 bitsint same size as uintuintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value
To avoid portability issues all numeric types aredefinedtypes and thus distinct exceptbyte
, which is analias foruint8
, andrune
, which is an alias forint32
.Explicit conversionsare required when different numeric types are mixed in an expressionor assignment. For instance,int32
andint
are not the same type even though they may have the same size on aparticular architecture.
String types
Astring type represents the set of string values.A string value is a (possibly empty) sequence of bytes.The number of bytes is called the length of the string and is never negative.Strings are immutable: once created,it is impossible to change the contents of a string.The predeclared string type isstring
;it is adefined type.
The length of a strings
can be discovered usingthe built-in functionlen
.The length is a compile-time constant if the string is a constant.A string's bytes can be accessed by integerindices0 throughlen(s)-1
.It is illegal to take the address of such an element; ifs[i]
is thei
'th byte of astring,&s[i]
is invalid.
Array types
An array is a numbered sequence of elements of a singletype, called the element type.The number of elements is called the length of the array and is never negative.
ArrayType = "["ArrayLength "]"ElementType .ArrayLength =Expression .ElementType =Type .
The length is part of the array's type; it must evaluate to anon-negativeconstantrepresentable by a valueof typeint
.The length of arraya
can be discoveredusing the built-in functionlen
.The elements can be addressed by integerindices0 throughlen(a)-1
.Array types are always one-dimensional but may be composed to formmulti-dimensional types.
[32]byte[2*N] struct { x, y int32 }[1000]*float64[3][5]int[2][2][2]float64 // same as [2]([2]([2]float64))
An array typeT
may not have an element of typeT
,or of a type containingT
as a component, directly or indirectly,if those containing types are only array or struct types.
// invalid array typestype (T1 [10]T1 // element type of T1 is T1T2 [10]struct{ f T2 } // T2 contains T2 as component of a structT3 [10]T4 // T3 contains T3 as component of a struct in T4T4 struct{ f T3 } // T4 contains T4 as component of array T3 in a struct)// valid array typestype (T5 [10]*T5 // T5 contains T5 as component of a pointerT6 [10]func() T6 // T6 contains T6 as component of a function typeT7 [10]struct{ f []T7 } // T7 contains T7 as component of a slice in a struct)
Slice types
A slice is a descriptor for a contiguous segment of anunderlying array andprovides access to a numbered sequence of elements from that array.A slice type denotes the set of all slices of arrays of its element type.The number of elements is called the length of the slice and is never negative.The value of an uninitialized slice isnil
.
SliceType = "[" "]"ElementType .
The length of a slices
can be discovered by the built-in functionlen
; unlike with arrays it may change duringexecution. The elements can be addressed by integerindices0 throughlen(s)-1
. The slice index of agiven element may be less than the index of the same element in theunderlying array.
A slice, once initialized, is always associated with an underlyingarray that holds its elements. A slice therefore shares storagewith its array and with other slices of the same array; by contrast,distinct arrays always represent distinct storage.
The array underlying a slice may extend past the end of the slice.Thecapacity is a measure of that extent: it is the sum ofthe length of the slice and the length of the array beyond the slice;a slice of length up to that capacity can be created byslicing a new one from the original slice.The capacity of a slicea
can be discovered using thebuilt-in functioncap(a)
.
A new, initialized slice value for a given element typeT
may bemade using the built-in functionmake
,which takes a slice typeand parameters specifying the length and optionally the capacity.A slice created withmake
always allocates a new, hidden arrayto which the returned slice value refers. That is, executing
make([]T, length, capacity)
produces the same slice as allocating an array andslicingit, so these two expressions are equivalent:
make([]int, 50, 100)new([100]int)[0:50]
Like arrays, slices are always one-dimensional but may be composed to constructhigher-dimensional objects.With arrays of arrays, the inner arrays are, by construction, always the same length;however with slices of slices (or arrays of slices), the inner lengths may vary dynamically.Moreover, the inner slices must be initialized individually.
Struct types
A struct is a sequence of named elements, called fields, each of which has aname and a type. Field names may be specified explicitly (IdentifierList) orimplicitly (EmbeddedField).Within a struct, non-blank field names mustbeunique.
StructType = "struct" "{" {FieldDecl ";" } "}" .FieldDecl = (IdentifierListType |EmbeddedField) [Tag ] .EmbeddedField = [ "*" ]TypeName [TypeArgs ] .Tag =string_lit .
// An empty struct.struct {}// A struct with 6 fields.struct {x, y intu float32_ float32 // paddingA *[]intF func()}
A field declared with a type but no explicit field name is called anembedded field.An embedded field must be specified asa type nameT
or as a pointer to a non-interface type name*T
,andT
itself may not bea pointer type or type parameter. The unqualified type name acts as the field name.
// A struct with four embedded fields of types T1, *T2, P.T3 and *P.T4struct {T1 // field name is T1*T2 // field name is T2P.T3 // field name is T3*P.T4 // field name is T4x, y int // field names are x and y}
The following declaration is illegal because field names must be uniquein a struct type:
struct {T // conflicts with embedded field *T and *P.T*T // conflicts with embedded field T and *P.T*P.T // conflicts with embedded field T and *T}
A field ormethodf
of anembedded field in a structx
is calledpromoted ifx.f
is a legalselector that denotesthat field or methodf
.
Promoted fields act like ordinary fieldsof a struct except that they cannot be used as field names incomposite literals of the struct.
Given a struct typeS
and a type nameT
, promoted methods are included in the method set of the struct as follows:
- If
S
contains an embedded fieldT
,themethod sets ofS
and*S
both include promoted methods with receiverT
. The method set of*S
alsoincludes promoted methods with receiver*T
. - If
S
contains an embedded field*T
,the method sets ofS
and*S
bothinclude promoted methods with receiverT
or*T
.
A field declaration may be followed by an optional string literaltag,which becomes an attribute for all the fields in the correspondingfield declaration. An empty tag string is equivalent to an absent tag.The tags are made visible through areflection interfaceand take part intype identity for structsbut are otherwise ignored.
struct {x, y float64 "" // an empty tag string is like an absent tagname string "any string is permitted as a tag"_ [4]byte "ceci n'est pas un champ de structure"}// A struct corresponding to a TimeStamp protocol buffer.// The tag strings define the protocol buffer field numbers;// they follow the convention outlined by the reflect package.struct {microsec uint64 `protobuf:"1"`serverIP6 uint64 `protobuf:"2"`}
A struct typeT
may not contain a field of typeT
,or of a type containingT
as a component, directly or indirectly,if those containing types are only array or struct types.
// invalid struct typestype (T1 struct{ T1 } // T1 contains a field of T1T2 struct{ f [10]T2 } // T2 contains T2 as component of an arrayT3 struct{ T4 } // T3 contains T3 as component of an array in struct T4T4 struct{ f [10]T3 } // T4 contains T4 as component of struct T3 in an array)// valid struct typestype (T5 struct{ f *T5 } // T5 contains T5 as component of a pointerT6 struct{ f func() T6 } // T6 contains T6 as component of a function typeT7 struct{ f [10][]T7 } // T7 contains T7 as component of a slice in an array)
Pointer types
A pointer type denotes the set of all pointers tovariables of a giventype, called thebase type of the pointer.Thevalue of an uninitialized pointer isnil
.
PointerType = "*"BaseType .BaseType =Type .
*Point*[4]int
Function types
A function type denotes the set of all functions with the same parameter and result types.Thevalue of an uninitialized variable of functiontype isnil
.
FunctionType = "func"Signature .Signature =Parameters [Result ] .Result =Parameters |Type .Parameters = "(" [ParameterList [ "," ] ] ")" .ParameterList =ParameterDecl { ","ParameterDecl } .ParameterDecl = [IdentifierList ] [ "..." ]Type .
Within a list of parameters or results, the names (IdentifierList)must either all be present or all be absent. If present, each namestands for one item (parameter or result) of the specified type andall non-blank names in the signaturemust beunique.If absent, each type stands for one item of that type.Parameter and resultlists are always parenthesized except that if there is exactlyone unnamed result it may be written as an unparenthesized type.
The final incoming parameter in a function signature may havea type prefixed with...
.A function with such a parameter is calledvariadic andmay be invoked with zero or more arguments for that parameter.
func()func(x int) intfunc(a, _ int, z float32) boolfunc(a, b int, z float32) (bool)func(prefix string, values ...int)func(a, b int, z float64, opt ...interface{}) (success bool)func(int, int, float64) (float64, *[]int)func(n int) func(p *T)
Interface types
An interface type defines atype set.A variable of interface type can store a value of any type that is in the typeset of the interface. Such a type is said toimplement the interface.Thevalue of an uninitialized variable ofinterface type isnil
.
InterfaceType = "interface" "{" {InterfaceElem ";" } "}" .InterfaceElem =MethodElem |TypeElem .MethodElem =MethodNameSignature .MethodName =identifier .TypeElem =TypeTerm { "|"TypeTerm } .TypeTerm =Type |UnderlyingType .UnderlyingType = "~"Type .
An interface type is specified by a list ofinterface elements.An interface element is either amethod or atype element,where a type element is a union of one or moretype terms.A type term is either a single type or a single underlying type.
Basic interfaces
In its most basic form an interface specifies a (possibly empty) list of methods.The type set defined by such an interface is the set of types which implement all ofthose methods, and the correspondingmethod set consistsexactly of the methods specified by the interface.Interfaces whose type sets can be defined entirely by a list of methods are calledbasic interfaces.
// A simple File interface.interface {Read([]byte) (int, error)Write([]byte) (int, error)Close() error}
The name of each explicitly specified method must beuniqueand notblank.
interface {String() stringString() string // illegal: String not unique_(x int) // illegal: method must have non-blank name}
More than one type may implement an interface.For instance, if two typesS1
andS2
have the method set
func (p T) Read(p []byte) (n int, err error)func (p T) Write(p []byte) (n int, err error)func (p T) Close() error
(whereT
stands for eitherS1
orS2
)then theFile
interface is implemented by bothS1
andS2
, regardless of what other methodsS1
andS2
may have or share.
Every type that is a member of the type set of an interface implements that interface.Any given type may implement several distinct interfaces.For instance, all types implement theempty interface which stands for the setof all (non-interface) types:
interface{}
For convenience, the predeclared typeany
is an alias for the empty interface.[Go 1.18]
Similarly, consider this interface specification,which appears within atype declarationto define an interface calledLocker
:
type Locker interface {Lock()Unlock()}
IfS1
andS2
also implement
func (p T) Lock() { … }func (p T) Unlock() { … }
they implement theLocker
interface as wellas theFile
interface.
Embedded interfaces
In a slightly more general forman interfaceT
may use a (possibly qualified) interface typenameE
as an interface element. This is calledembedding interfaceE
inT
[Go 1.14].The type set ofT
is theintersection of the type setsdefined byT
's explicitly declared methods and the type setsofT
’s embedded interfaces.In other words, the type set ofT
is the set of all types that implement all theexplicitly declared methods ofT
and also all the methods ofE
[Go 1.18].
type Reader interface {Read(p []byte) (n int, err error)Close() error}type Writer interface {Write(p []byte) (n int, err error)Close() error}// ReadWriter's methods are Read, Write, and Close.type ReadWriter interface {Reader // includes methods of Reader in ReadWriter's method setWriter // includes methods of Writer in ReadWriter's method set}
When embedding interfaces, methods with thesame names musthaveidentical signatures.
type ReadCloser interface {Reader // includes methods of Reader in ReadCloser's method setClose() // illegal: signatures of Reader.Close and Close are different}
General interfaces
In their most general form, an interface element may also be an arbitrary type termT
, or a term of the form~T
specifying the underlying typeT
,or a union of termst1|t2|…|tn
[Go 1.18].Together with method specifications, these elements enable the precisedefinition of an interface's type set as follows:
- The type set of the empty interface is the set of all non-interface types.
- The type set of a non-empty interface is the intersection of the type setsof its interface elements.
- The type set of a method specification is the set of all non-interface typeswhose method sets include that method.
- The type set of a non-interface type term is the set consistingof just that type.
- The type set of a term of the form
~T
is the set of all types whose underlying type isT
. - The type set of aunion of terms
t1|t2|…|tn
is the union of the type sets of the terms.
The quantification "the set of all non-interface types" refers not just to all (non-interface)types declared in the program at hand, but all possible types in all possible programs, andhence is infinite.Similarly, given the set of all non-interface types that implement a particular method, theintersection of the method sets of those types will contain exactly that method, even if alltypes in the program at hand always pair that method with another method.
By construction, an interface's type set never contains an interface type.
// An interface representing only the type int.interface {int}// An interface representing all types with underlying type int.interface {~int}// An interface representing all types with underlying type int that implement the String method.interface {~intString() string}// An interface representing an empty type set: there is no type that is both an int and a string.interface {intstring}
In a term of the form~T
, the underlying type ofT
must be itself, andT
cannot be an interface.
type MyInt intinterface {~[]byte // the underlying type of []byte is itself~MyInt // illegal: the underlying type of MyInt is not MyInt~error // illegal: error is an interface}
Union elements denote unions of type sets:
// The Float interface represents all floating-point types// (including any named types whose underlying types are// either float32 or float64).type Float interface {~float32 | ~float64}
The typeT
in a term of the formT
or~T
cannotbe atype parameter, and the type sets of allnon-interface terms must be pairwise disjoint (the pairwise intersection of the type sets must be empty).Given a type parameterP
:
interface {P // illegal: P is a type parameterint | ~P // illegal: P is a type parameter~int | MyInt // illegal: the type sets for ~int and MyInt are not disjoint (~int includes MyInt)float32 | Float // overlapping type sets but Float is an interface}
Implementation restriction:A union (with more than one term) cannot contain thepredeclared identifiercomparable
or interfaces that specify methods, or embedcomparable
or interfacesthat specify methods.
Interfaces that are notbasic may only be used as typeconstraints, or as elements of other interfaces used as constraints.They cannot be the types of values or variables, or components of other,non-interface types.
var x Float // illegal: Float is not a basic interfacevar x interface{} = Float(nil) // illegaltype Floatish struct {f Float // illegal}
An interface typeT
may not embed a type elementthat is, contains, or embedsT
, directly or indirectly.
// illegal: Bad may not embed itselftype Bad interface {Bad}// illegal: Bad1 may not embed itself using Bad2type Bad1 interface {Bad2}type Bad2 interface {Bad1}// illegal: Bad3 may not embed a union containing Bad3type Bad3 interface {~int | ~string | Bad3}// illegal: Bad4 may not embed an array containing Bad4 as element typetype Bad4 interface {[10]Bad4}
Implementing an interface
A typeT
implements an interfaceI
if
T
is not an interface and is an element of the type set ofI
; orT
is an interface and the type set ofT
is a subset of thetype set ofI
.
A value of typeT
implements an interface ifT
implements the interface.
Map types
A map is an unordered group of elements of one type, called theelement type, indexed by a set of uniquekeys of another type,called the key type.Thevalue of an uninitialized map isnil
.
MapType = "map" "["KeyType "]"ElementType .KeyType =Type .
Thecomparison operators==
and!=
must be fully definedfor operands of the key type; thus the key type must not be a function, map, orslice.If the key type is an interface type, thesecomparison operators must be defined for the dynamic key values;failure will cause arun-time panic.
map[string]intmap[*T]struct{ x, y float64 }map[string]interface{}
The number of map elements is called its length.For a mapm
, it can be discovered using thebuilt-in functionlen
and may change during execution. Elements may be added during executionusingassignments and retrieved withindex expressions; they may be removed with thedelete
andclear
built-in function.
A new, empty map value is made using the built-infunctionmake
,which takes the map type and an optional capacity hint as arguments:
make(map[string]int)make(map[string]int, 100)
The initial capacity does not bound its size:maps grow to accommodate the number of itemsstored in them, with the exception ofnil
maps.Anil
map is equivalent to an empty map except that no elementsmay be added.
Channel types
A channel provides a mechanism forconcurrently executing functionsto communicate bysending andreceivingvalues of a specified element type.Thevalue of an uninitialized channel isnil
.
ChannelType = ( "chan" | "chan" "<-" | "<-" "chan" )ElementType .
The optional<-
operator specifies the channeldirection,send orreceive. If a direction is given, the channel isdirectional,otherwise it isbidirectional.A channel may be constrained only to send or only to receive byassignment orexplicitconversion.
chan T // can be used to send and receive values of type Tchan<- float64 // can only be used to send float64s<-chan int // can only be used to receive ints
The<-
operator associates with the leftmostchan
possible:
chan<- chan int // same as chan<- (chan int)chan<- <-chan int // same as chan<- (<-chan int)<-chan <-chan int // same as <-chan (<-chan int)chan (<-chan int)
A new, initialized channelvalue can be made using the built-in functionmake
,which takes the channel type and an optionalcapacity as arguments:
make(chan int, 100)
The capacity, in number of elements, sets the size of the buffer in the channel.If the capacity is zero or absent, the channel is unbuffered and communicationsucceeds only when both a sender and receiver are ready. Otherwise, the channelis buffered and communication succeeds without blocking if the bufferis not full (sends) or not empty (receives).Anil
channel is never ready for communication.
A channel may be closed with the built-in functionclose
.The multi-valued assignment form of thereceive operatorreports whether a received value was sent beforethe channel was closed.
A single channel may be used insend statements,receive operations,and calls to the built-in functionscap
andlen
by any number of goroutines without further synchronization.Channels act as first-in-first-out queues.For example, if one goroutine sends values on a channeland a second goroutine receives them, the values arereceived in the order sent.
Properties of types and values
Representation of values
Values of predeclared types (see below for the interfacesany
anderror
), arrays, and structs are self-contained:Each such value contains a complete copy of all its data,andvariables of such types store the entire value.For instance, an array variable provides the storage (the variables)for all elements of the array.The respectivezero values are specific to thevalue's types; they are nevernil
.
Non-nil pointer, function, slice, map, and channel values contain referencesto underlying data which may be shared by multiple values:
- A pointer value is a reference to the variable holdingthe pointer base type value.
- A function value contains references to the (possiblyanonymous) functionand enclosed variables.
- A slice value contains the slice length, capacity, anda reference to itsunderlying array.
- A map or channel value is a reference to the implementation-specificdata structure of the map or channel.
An interface value may be self-contained or contain references to underlying datadepending on the interface'sdynamic type.The predeclared identifiernil
is the zero value for types whose valuescan contain references.
When multiple values share underlying data, changing one value may change another.For instance, changing an element of aslice will changethat element in the underlying array for all slices that share the array.
Underlying types
Each typeT
has anunderlying type: IfT
is one of the predeclared boolean, numeric, or string types, or a type literal,the corresponding underlying type isT
itself.Otherwise,T
's underlying type is the underlying type of thetype to whichT
refers in its declaration.For a type parameter that is the underlying type of itstype constraint, which is always an interface.
type (A1 = stringA2 = A1)type (B1 stringB2 B1B3 []B1B4 B3)func f[P any](x P) { … }
The underlying type ofstring
,A1
,A2
,B1
,andB2
isstring
.The underlying type of[]B1
,B3
, andB4
is[]B1
.The underlying type ofP
isinterface{}
.
Core types
Each non-interface typeT
has acore type, which is the same as theunderlying type ofT
.
An interfaceT
has a core type if one of the followingconditions is satisfied:
- There is a single type
U
which is theunderlying typeof all types in thetype set ofT
; or - the type set of
T
contains onlychannel typeswith identical element typeE
, and all directional channels have the samedirection.
No other interfaces have a core type.
The core type of an interface is, depending on the condition that is satisfied, either:
- the type
U
; or - the type
chan E
ifT
contains only bidirectionalchannels, or the typechan<- E
or<-chan E
depending on the direction of the directional channels present.
By definition, a core type is never adefined type,type parameter, orinterface type.
Examples of interfaces with core types:
type Celsius float32type Kelvin float32interface{ int } // intinterface{ Celsius|Kelvin } // float32interface{ ~chan int } // chan intinterface{ ~chan int|~chan<- int } // chan<- intinterface{ ~[]*data; String() string } // []*data
Examples of interfaces without core types:
interface{} // no single underlying typeinterface{ Celsius|float64 } // no single underlying typeinterface{ chan int | chan<- string } // channels have different element typesinterface{ <-chan int | chan<- int } // directional channels have different directions
Some operations (slice expressions,append
andcopy
)rely on a slightly more loose form of core types which accept byte slices and strings.Specifically, if there are exactly two types,[]byte
andstring
,which are the underlying types of all types in the type set of interfaceT
,the core type ofT
is calledbytestring
.
Examples of interfaces withbytestring
core types:
interface{ int } // int (same as ordinary core type)interface{ []byte | string } // bytestringinterface{ ~[]byte | myString } // bytestring
Note thatbytestring
is not a real type; it cannot be used to declarevariables or compose other types. It exists solely to describe the behavior of someoperations that read from a sequence of bytes, which may be a byte slice or a string.
Type identity
Two types are eitheridentical ordifferent.
Anamed type is always different from any other type.Otherwise, two types are identical if theirunderlying type literals arestructurally equivalent; that is, they have the same literal structure and correspondingcomponents have identical types. In detail:
- Two array types are identical if they have identical element types and the same array length.
- Two slice types are identical if they have identical element types.
- Two struct types are identical if they have the same sequence of fields, and if corresponding pairs of fields have the same names, identical types, and identical tags, and are either both embedded or both not embedded.Non-exported field names from different packages are always different.
- Two pointer types are identical if they have identical base types.
- Two function types are identical if they have the same number of parameters and result values, corresponding parameter and result types are identical, and either both functions are variadic or neither is. Parameter and result names are not required to match.
- Two interface types are identical if they define the same type set.
- Two map types are identical if they have identical key and element types.
- Two channel types are identical if they have identical element types and the same direction.
- Twoinstantiated types are identical if their defined types and all type arguments are identical.
Given the declarations
type (A0 = []stringA1 = A0A2 = struct{ a, b int }A3 = intA4 = func(A3, float64) *A0A5 = func(x int, _ float64) *[]stringB0 A0B1 []stringB2 struct{ a, b int }B3 struct{ a, c int }B4 func(int, float64) *B0B5 func(x int, y float64) *A1C0 = B0D0[P1, P2 any] struct{ x P1; y P2 }E0 = D0[int, string])
these types are identical:
A0, A1, and []stringA2 and struct{ a, b int }A3 and intA4, func(int, float64) *[]string, and A5B0 and C0D0[int, string] and E0[]int and []intstruct{ a, b *B5 } and struct{ a, b *B5 }func(x int, y float64) *[]string, func(int, float64) (result *[]string), and A5
B0
andB1
are different because they are new typescreated by distincttype definitions;func(int, float64) *B0
andfunc(x int, y float64) *[]string
are different becauseB0
is different from[]string
;andP1
andP2
are different because they are differenttype parameters.D0[int, string]
andstruct{ x int; y string }
aredifferent because the former is aninstantiateddefined type while the latter is a type literal(but they are stillassignable).
Assignability
A valuex
of typeV
isassignable to avariable of typeT
("x
is assignable toT
") if one of the following conditions applies:
V
andT
are identical.V
andT
have identicalunderlying typesbut are not type parameters and at least one ofV
orT
is not anamed type.V
andT
are channel types withidentical element types,V
is a bidirectional channel,and at least one ofV
orT
is not anamed type.T
is an interface type, but not a type parameter, andx
implementsT
.x
is the predeclared identifiernil
andT
is a pointer, function, slice, map, channel, or interface type,but not a type parameter.x
is an untypedconstantrepresentableby a value of typeT
.
Additionally, ifx
's typeV
orT
are type parameters,x
is assignable to a variable of typeT
if one of the following conditions applies:
x
is the predeclared identifiernil
,T
isa type parameter, andx
is assignable to each type inT
's type set.V
is not anamed type,T
isa type parameter, andx
is assignable to each type inT
's type set.V
is a type parameter andT
is not a named type,and values of each type inV
's type set are assignabletoT
.
Representability
Aconstantx
isrepresentableby a value of typeT
,whereT
is not atype parameter,if one of the following conditions applies:
x
is in the set of valuesdetermined byT
.T
is afloating-point type andx
can be rounded toT
'sprecision without overflow. Rounding uses IEEE 754 round-to-even rules but with an IEEEnegative zero further simplified to an unsigned zero. Note that constant values never resultin an IEEE negative zero, NaN, or infinity.T
is a complex type, andx
'scomponentsreal(x)
andimag(x)
are representable by values ofT
's component type (float32
orfloat64
).
IfT
is a type parameter,x
is representable by a value of typeT
ifx
is representableby a value of each type inT
's type set.
x T x is representable by a value of T because'a' byte 97 is in the set of byte values97 rune rune is an alias for int32, and 97 is in the set of 32-bit integers"foo" string "foo" is in the set of string values1024 int16 1024 is in the set of 16-bit integers42.0 byte 42 is in the set of unsigned 8-bit integers1e10 uint64 10000000000 is in the set of unsigned 64-bit integers2.718281828459045 float32 2.718281828459045 rounds to 2.7182817 which is in the set of float32 values-1e-1000 float64 -1e-1000 rounds to IEEE -0.0 which is further simplified to 0.00i int 0 is an integer value(42 + 0i) float32 42.0 (with zero imaginary part) is in the set of float32 values
x T x is not representable by a value of T because0 bool 0 is not in the set of boolean values'a' string 'a' is a rune, it is not in the set of string values1024 byte 1024 is not in the set of unsigned 8-bit integers-1 uint16 -1 is not in the set of unsigned 16-bit integers1.1 int 1.1 is not an integer value42i float32 (0 + 42i) is not in the set of float32 values1e1000 float64 1e1000 overflows to IEEE +Inf after rounding
Method sets
Themethod set of a type determines the methods that can becalled on anoperand of that type.Every type has a (possibly empty) method set associated with it:
- The method set of adefined type
T
consists of allmethods declared with receiver typeT
. - The method set of a pointer to a defined type
T
(whereT
is neither a pointer nor an interface)is the set of all methods declared with receiver*T
orT
. - The method set of aninterface type is the intersectionof the method sets of each type in the interface'stype set(the resulting method set is usually just the set of declared methods in the interface).
Further rules apply to structs (and pointer to structs) containing embedded fields,as described in the section onstruct types.Any other type has an empty method set.
In a method set, each method must have auniquenon-blankmethod name.
Blocks
Ablock is a possibly empty sequence of declarations and statementswithin matching brace brackets.
Block = "{"StatementList "}" .StatementList = {Statement ";" } .
In addition to explicit blocks in the source code, there are implicit blocks:
- Theuniverse block encompasses all Go source text.
- Eachpackage has apackage block containing all Go source text for that package.
- Each file has afile block containing all Go source text in that file.
- Each"if","for", and"switch" statement is considered to be in its own implicit block.
- Each clause in a"switch" or"select" statement acts as an implicit block.
Blocks nest and influencescoping.
Declarations and scope
Adeclaration binds a non-blank identifier to aconstant,type,type parameter,variable,function,label, orpackage.Every identifier in a program must be declared.No identifier may be declared twice in the same block, andno identifier may be declared in both the file and package block.
Theblank identifier may be used like any other identifierin a declaration, but it does not introduce a binding and thus is not declared.In the package block, the identifierinit
may only be used forinit
function declarations,and like the blank identifier it does not introduce a new binding.
Declaration =ConstDecl |TypeDecl |VarDecl .TopLevelDecl =Declaration |FunctionDecl |MethodDecl .
Thescope of a declared identifier is the extent of source text in whichthe identifier denotes the specified constant, type, variable, function, label, or package.
Go is lexically scoped usingblocks:
- The scope of apredeclared identifier is the universe block.
- The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block.
- The scope of the package name of an imported package is the file block of the file containing the import declaration.
- The scope of an identifier denoting a method receiver, function parameter, or result variable is the function body.
- The scope of an identifier denoting a type parameter of a function or declared by a method receiver begins after the name of the function and ends at the end of the function body.
- The scope of an identifier denoting a type parameter of a type begins after the name of the type and ends at the end of the TypeSpec.
- The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.
- The scope of a type identifier declared inside a function begins at the identifier in the TypeSpec and ends at the end of the innermost containing block.
An identifier declared in a block may be redeclared in an inner block.While the identifier of the inner declaration is in scope, it denotesthe entity declared by the inner declaration.
Thepackage clause is not a declaration; the package namedoes not appear in any scope. Its purpose is to identify the files belongingto the samepackage and to specify the default package name for importdeclarations.
Label scopes
Labels are declared bylabeled statements and areused in the"break","continue", and"goto" statements.It is illegal to define a label that is never used.In contrast to other identifiers, labels are not block scoped and donot conflict with identifiers that are not labels. The scope of a labelis the body of the function in which it is declared and excludesthe body of any nested function.
Blank identifier
Theblank identifier is represented by the underscore character_
.It serves as an anonymous placeholder instead of a regular (non-blank)identifier and has special meaning indeclarations,as anoperand, and inassignment statements.
Predeclared identifiers
The following identifiers are implicitly declared in theuniverse block[Go 1.18][Go 1.21]:
Types:any bool byte comparablecomplex64 complex128 error float32 float64int int8 int16 int32 int64 rune stringuint uint8 uint16 uint32 uint64 uintptrConstants:true false iotaZero value:nilFunctions:append cap clear close complex copy delete imag lenmake max min new panic print println real recover
Exported identifiers
An identifier may beexported to permit access to it from another package.An identifier is exported if both:
- the first character of the identifier's name is a Unicode uppercaseletter (Unicode character category Lu); and
- the identifier is declared in thepackage blockor it is afield name ormethod name.
All other identifiers are not exported.
Uniqueness of identifiers
Given a set of identifiers, an identifier is calledunique if it isdifferent from every other in the set.Two identifiers are different if they are spelled differently, or if theyappear in differentpackages and are notexported. Otherwise, they are the same.
Constant declarations
A constant declaration binds a list of identifiers (the names ofthe constants) to the values of a list ofconstant expressions.The number of identifiers must be equalto the number of expressions, and thenth identifier onthe left is bound to the value of thenth expression on theright.
ConstDecl = "const" (ConstSpec | "(" {ConstSpec ";" } ")" ) .ConstSpec =IdentifierList [ [Type ] "="ExpressionList ] .IdentifierList =identifier { ","identifier } .ExpressionList =Expression { ","Expression } .
If the type is present, all constants take the type specified, andthe expressions must beassignable to that type,which must not be a type parameter.If the type is omitted, the constants take theindividual types of the corresponding expressions.If the expression values are untypedconstants,the declared constants remain untyped and the constant identifiersdenote the constant values. For instance, if the expression is afloating-point literal, the constant identifier denotes a floating-pointconstant, even if the literal's fractional part is zero.
const Pi float64 = 3.14159265358979323846const zero = 0.0 // untyped floating-point constantconst (size int64 = 1024eof = -1 // untyped integer constant)const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", untyped integer and string constantsconst u, v float32 = 0, 3 // u = 0.0, v = 3.0
Within a parenthesizedconst
declaration list theexpression list may be omitted from any but the first ConstSpec.Such an empty list is equivalent to the textual substitution of thefirst preceding non-empty expression list and its type if any.Omitting the list of expressions is therefore equivalent torepeating the previous list. The number of identifiers must be equalto the number of expressions in the previous list.Together with theiota
constant generatorthis mechanism permits light-weight declaration of sequential values:
const (Sunday = iotaMondayTuesdayWednesdayThursdayFridayPartydaynumberOfDays // this constant is not exported)
Iota
Within aconstant declaration, the predeclared identifieriota
represents successive untyped integerconstants. Its value is the index of the respectiveConstSpecin that constant declaration, starting at zero.It can be used to construct a set of related constants:
const (c0 = iota // c0 == 0c1 = iota // c1 == 1c2 = iota // c2 == 2)const (a = 1 << iota // a == 1 (iota == 0)b = 1 << iota // b == 2 (iota == 1)c = 3 // c == 3 (iota == 2, unused)d = 1 << iota // d == 8 (iota == 3))const (u = iota * 42 // u == 0 (untyped integer constant)v float64 = iota * 42 // v == 42.0 (float64 constant)w = iota * 42 // w == 84 (untyped integer constant))const x = iota // x == 0const y = iota // y == 0
By definition, multiple uses ofiota
in the same ConstSpec all have the same value:
const (bit0, mask0 = 1 << iota, 1<<iota - 1 // bit0 == 1, mask0 == 0 (iota == 0)bit1, mask1 // bit1 == 2, mask1 == 1 (iota == 1)_, _ // (iota == 2, unused)bit3, mask3 // bit3 == 8, mask3 == 7 (iota == 3))
This last example exploits theimplicit repetitionof the last non-empty expression list.
Type declarations
A type declaration binds an identifier, thetype name, to atype.Type declarations come in two forms: alias declarations and type definitions.
TypeDecl = "type" (TypeSpec | "(" {TypeSpec ";" } ")" ) .TypeSpec =AliasDecl |TypeDef .
Alias declarations
An alias declaration binds an identifier to the given type[Go 1.9].
AliasDecl =identifier [TypeParameters ] "="Type .
Within thescope ofthe identifier, it serves as analias for the given type.
type (nodeList = []*Node // nodeList and []*Node are identical typesPolar = polar // Polar and polar denote identical types)
If the alias declaration specifiestype parameters[Go 1.24], the type name denotes ageneric alias.Generic aliases must beinstantiated when theyare used.
type set[P comparable] = map[P]bool
In an alias declaration the given type cannot be a type parameter.
type A[P any] = P // illegal: P is a type parameter
Type definitions
A type definition creates a new, distinct type with the sameunderlying type and operations as the given typeand binds an identifier, thetype name, to it.
TypeDef =identifier [TypeParameters ]Type .
The new type is called adefined type.It isdifferent from any other type,including the type it is created from.
type (Point struct{ x, y float64 } // Point and struct{ x, y float64 } are different typespolar Point // polar and Point denote different types)type TreeNode struct {left, right *TreeNodevalue any}type Block interface {BlockSize() intEncrypt(src, dst []byte)Decrypt(src, dst []byte)}
A defined type may havemethods associated with it.It does not inherit any methods bound to the given type,but themethod setof an interface type or of elements of a composite type remains unchanged:
// A Mutex is a data type with two methods, Lock and Unlock.type Mutex struct { /* Mutex fields */ }func (m *Mutex) Lock() { /* Lock implementation */ }func (m *Mutex) Unlock() { /* Unlock implementation */ }// NewMutex has the same composition as Mutex but its method set is empty.type NewMutex Mutex// The method set of PtrMutex's underlying type *Mutex remains unchanged,// but the method set of PtrMutex is empty.type PtrMutex *Mutex// The method set of *PrintableMutex contains the methods// Lock and Unlock bound to its embedded field Mutex.type PrintableMutex struct {Mutex}// MyBlock is an interface type that has the same method set as Block.type MyBlock Block
Type definitions may be used to define different boolean, numeric,or string types and associate methods with them:
type TimeZone intconst (EST TimeZone = -(5 + iota)CSTMSTPST)func (tz TimeZone) String() string {return fmt.Sprintf("GMT%+dh", tz)}
If the type definition specifiestype parameters,the type name denotes ageneric type.Generic types must beinstantiated when theyare used.
type List[T any] struct {next *List[T]value T}
In a type definition the given type cannot be a type parameter.
type T[P any] P // illegal: P is a type parameterfunc f[T any]() {type L T // illegal: T is a type parameter declared by the enclosing function}
A generic type may also havemethods associated with it.In this case, the method receivers must declare the same number of type parameters aspresent in the generic type definition.
// The method Len returns the number of elements in the linked list l.func (l *List[T]) Len() int { … }
Type parameter declarations
A type parameter list declares thetype parameters of a generic function or type declaration.The type parameter list looks like an ordinaryfunction parameter listexcept that the type parameter names must all be present and the list is enclosedin square brackets rather than parentheses[Go 1.18].
TypeParameters = "["TypeParamList [ "," ] "]" .TypeParamList =TypeParamDecl { ","TypeParamDecl } .TypeParamDecl =IdentifierListTypeConstraint .
All non-blank names in the list must be unique.Each name declares a type parameter, which is a new and differentnamed typethat acts as a placeholder for an (as of yet) unknown type in the declaration.The type parameter is replaced with atype argument uponinstantiation of the generic function or type.
[P any][S interface{ ~[]byte|string }][S ~[]E, E any][P Constraint[int]][_ any]
Just as each ordinary function parameter has a parameter type, each type parameterhas a corresponding (meta-)type which is called itstype constraint.
A parsing ambiguity arises when the type parameter list for a generic typedeclares a single type parameterP
with a constraintC
such that the textP C
forms a valid expression:
type T[P *C] …type T[P (C)] …type T[P *C|Q] ……
In these rare cases, the type parameter list is indistinguishable from anexpression and the type declaration is parsed as an array type declaration.To resolve the ambiguity, embed the constraint in aninterface or use a trailing comma:
type T[P interface{*C}] …type T[P *C,] …
Type parameters may also be declared by the receiver specificationof amethod declaration associatedwith a generic type.
Within a type parameter list of a generic typeT
, a type constraintmay not (directly, or indirectly through the type parameter list of anothergeneric type) refer toT
.
type T1[P T1[P]] … // illegal: T1 refers to itselftype T2[P interface{ T2[int] }] … // illegal: T2 refers to itselftype T3[P interface{ m(T3[int])}] … // illegal: T3 refers to itselftype T4[P T5[P]] … // illegal: T4 refers to T5 andtype T5[P T4[P]] … // T5 refers to T4type T6[P int] struct{ f *T6[P] } // ok: reference to T6 is not in type parameter list
Type constraints
Atype constraint is aninterface that defines theset of permissible type arguments for the respective type parameter and controls theoperations supported by values of that type parameter[Go 1.18].
TypeConstraint =TypeElem .
If the constraint is an interface literal of the forminterface{E}
whereE
is an embeddedtype element (not a method), in a type parameter listthe enclosinginterface{ … }
may be omitted for convenience:
[T []P] // = [T interface{[]P}][T ~int] // = [T interface{~int}][T int|string] // = [T interface{int|string}]type Constraint ~int // illegal: ~int is not in a type parameter list
Thepredeclaredinterface typecomparable
denotes the set of all non-interface types that arestrictly comparable[Go 1.18].
Even though interfaces that are not type parameters arecomparable,they are not strictly comparable and therefore they do not implementcomparable
.However, theysatisfycomparable
.
int // implements comparable (int is strictly comparable)[]byte // does not implement comparable (slices cannot be compared)interface{} // does not implement comparable (see above)interface{ ~int | ~string } // type parameter only: implements comparable (int, string types are strictly comparable)interface{ comparable } // type parameter only: implements comparable (comparable implements itself)interface{ ~int | ~[]byte } // type parameter only: does not implement comparable (slices are not comparable)interface{ ~struct{ any } } // type parameter only: does not implement comparable (field any is not strictly comparable)
Thecomparable
interface and interfaces that (directly or indirectly) embedcomparable
may only be used as type constraints. They cannot be the types ofvalues or variables, or components of other, non-interface types.
Satisfying a type constraint
A type argumentT
satisfies a type constraintC
ifT
is an element of the type set defined byC
; in other words,ifT
implementsC
.As an exception, astrictly comparabletype constraint may also be satisfied by acomparable(not necessarily strictly comparable) type argument[Go 1.20].More precisely:
A type Tsatisfies a constraintC
if
T
implementsC
; orC
can be written in the forminterface{ comparable; E }
,whereE
is abasic interface andT
iscomparable and implementsE
.
type argument type constraint // constraint satisfactionint interface{ ~int } // satisfied: int implements interface{ ~int }string comparable // satisfied: string implements comparable (string is strictly comparable)[]byte comparable // not satisfied: slices are not comparableany interface{ comparable; int } // not satisfied: any does not implement interface{ int }any comparable // satisfied: any is comparable and implements the basic interface anystruct{f any} comparable // satisfied: struct{f any} is comparable and implements the basic interface anyany interface{ comparable; m() } // not satisfied: any does not implement the basic interface interface{ m() }interface{ m() } interface{ comparable; m() } // satisfied: interface{ m() } is comparable and implements the basic interface interface{ m() }
Because of the exception in the constraint satisfaction rule, comparing operands of type parameter typemay panic at run-time (even though comparable type parameters are always strictly comparable).
Variable declarations
A variable declaration creates one or morevariables,binds corresponding identifiers to them, and gives each a type and an initial value.
VarDecl = "var" (VarSpec | "(" {VarSpec ";" } ")" ) .VarSpec =IdentifierList (Type [ "="ExpressionList ] | "="ExpressionList ) .
var i intvar U, V, W float64var k = 0var x, y float32 = -1, -2var (i intu, v, s = 2.0, 3.0, "bar")var re, im = complexSqrt(-1)var _, found = entries[name] // map lookup; only interested in "found"
If a list of expressions is given, the variables are initializedwith the expressions following the rules forassignment statements.Otherwise, each variable is initialized to itszero value.
If a type is present, each variable is given that type.Otherwise, each variable is given the type of the correspondinginitialization value in the assignment.If that value is an untyped constant, it is first implicitlyconverted to itsdefault type;if it is an untyped boolean value, it is first implicitly converted to typebool
.The predeclared identifiernil
cannot be used to initialize a variablewith no explicit type.
var d = math.Sin(0.5) // d is float64var i = 42 // i is intvar t, ok = x.(T) // t is T, ok is boolvar n = nil // illegal
Implementation restriction: A compiler may make it illegal to declare a variableinside afunction body if the variable isnever used.
Short variable declarations
Ashort variable declaration uses the syntax:
ShortVarDecl =IdentifierList ":="ExpressionList .
It is shorthand for a regularvariable declarationwith initializer expressions but no types:
"var" IdentifierList "=" ExpressionList .
i, j := 0, 10f := func() int { return 7 }ch := make(chan int)r, w, _ := os.Pipe() // os.Pipe() returns a connected pair of Files and an error, if any_, y, _ := coord(p) // coord() returns three values; only interested in y coordinate
Unlike regular variable declarations, a short variable declaration mayredeclarevariables provided they were originally declared earlier in the same block(or the parameter lists if the block is the function body) with the same type,and at least one of the non-blank variables is new.As a consequence, redeclaration can only appear in a multi-variable short declaration.Redeclaration does not introduce a new variable; it just assigns a new value to the original.The non-blank variable names on the left side of:=
must beunique.
field1, offset := nextField(str, 0)field2, offset := nextField(str, offset) // redeclares offsetx, y, x := 1, 2, 3 // illegal: x repeated on left side of :=
Short variable declarations may appear only inside functions.In some contexts such as the initializers for"if","for", or"switch" statements,they can be used to declare local temporary variables.
Function declarations
A function declaration binds an identifier, thefunction name,to a function.
FunctionDecl = "func"FunctionName [TypeParameters ]Signature [FunctionBody ] .FunctionName =identifier .FunctionBody =Block .
If the function'ssignature declaresresult parameters, the function body's statement list must end inaterminating statement.
func IndexRune(s string, r rune) int {for i, c := range s {if c == r {return i}}// invalid: missing return statement}
If the function declaration specifiestype parameters,the function name denotes ageneric function.A generic function must beinstantiated before it can becalled or used as a value.
func min[T ~int|~float64](x, y T) T {if x < y {return x}return y}
A function declaration without type parameters may omit the body.Such a declaration provides the signature for a function implemented outside Go,such as an assembly routine.
func flushICache(begin, end uintptr) // implemented externally
Method declarations
A method is afunction with areceiver.A method declaration binds an identifier, themethod name, to a method,and associates the method with the receiver'sbase type.
MethodDecl = "func"ReceiverMethodNameSignature [FunctionBody ] .Receiver =Parameters .
The receiver is specified via an extra parameter section preceding the methodname. That parameter section must declare a single non-variadic parameter, the receiver.Its type must be adefined typeT
or apointer to a defined typeT
, possibly followed by a list of type parameternames[P1, P2, …]
enclosed in square brackets.T
is called the receiverbase type. A receiver base type cannot bea pointer or interface type and it must be defined in the same package as the method.The method is said to bebound to its receiver base type and the method nameis visible only withinselectors for typeT
or*T
.
A non-blank receiver identifier must beunique in the method signature.If the receiver's value is not referenced inside the body of the method,its identifier may be omitted in the declaration. The same applies ingeneral to parameters of functions and methods.
For a base type, the non-blank names of methods bound to it must be unique.If the base type is astruct type,the non-blank method and field names must be distinct.
Given defined typePoint
the declarations
func (p *Point) Length() float64 {return math.Sqrt(p.x * p.x + p.y * p.y)}func (p *Point) Scale(factor float64) {p.x *= factorp.y *= factor}
bind the methodsLength
andScale
,with receiver type*Point
,to the base typePoint
.
If the receiver base type is ageneric type, thereceiver specification must declare corresponding type parameters for the methodto use. This makes the receiver type parameters available to the method.Syntactically, this type parameter declaration looks like aninstantiation of the receiver base type: the typearguments must be identifiers denoting the type parameters being declared, onefor each type parameter of the receiver base type.The type parameter names do not need to match their corresponding parameter names in thereceiver base type definition, and all non-blank parameter names must be unique in thereceiver parameter section and the method signature.The receiver type parameter constraints are implied by the receiver base type definition:corresponding type parameters have corresponding constraints.
type Pair[A, B any] struct {a Ab B}func (p Pair[A, B]) Swap() Pair[B, A] { … } // receiver declares A, Bfunc (p Pair[First, _]) First() First { … } // receiver declares First, corresponds to A in Pair
If the receiver type is denoted by (a pointer to) analias,the alias must not be generic and it must not denote an instantiated generic type, neitherdirectly nor indirectly via another alias, and irrespective of pointer indirections.
type GPoint[P any] = Pointtype HPoint = *GPoint[int]type IPair = Pair[int, int]func (*GPoint[P]) Draw(P) { … } // illegal: alias must not be genericfunc (HPoint) Draw(P) { … } // illegal: alias must not denote instantiated type GPoint[int]func (*IPair) Second() int { … } // illegal: alias must not denote instantiated type Pair[int, int]
Expressions
An expression specifies the computation of a value by applyingoperators and functions to operands.
Operands
Operands denote the elementary values in an expression. An operand may be aliteral, a (possiblyqualified)non-blank identifier denoting aconstant,variable, orfunction,or a parenthesized expression.
Operand =Literal |OperandName [TypeArgs ] | "("Expression ")" .Literal =BasicLit |CompositeLit |FunctionLit .BasicLit =int_lit |float_lit |imaginary_lit |rune_lit |string_lit .OperandName =identifier |QualifiedIdent .
An operand name denoting ageneric functionmay be followed by a list oftype arguments; theresulting operand is aninstantiated function.
Theblank identifier may appear as anoperand only on the left-hand side of anassignment statement.
Implementation restriction: A compiler need not report an error if an operand'stype is atype parameter with an emptytype set. Functions with such type parameterscannot beinstantiated; any attempt will leadto an error at the instantiation site.
Qualified identifiers
Aqualified identifier is an identifier qualified with a package name prefix.Both the package name and the identifier must not beblank.
QualifiedIdent =PackageName "."identifier .
A qualified identifier accesses an identifier in a different package, whichmust beimported.The identifier must beexported anddeclared in thepackage block of that package.
math.Sin // denotes the Sin function in package math
Composite literals
Composite literals construct new composite values each time they are evaluated.They consist of the type of the literal followed by a brace-bound list of elements.Each element may optionally be preceded by a corresponding key.
CompositeLit =LiteralTypeLiteralValue .LiteralType =StructType |ArrayType | "[" "..." "]"ElementType |SliceType |MapType |TypeName [TypeArgs ] .LiteralValue = "{" [ElementList [ "," ] ] "}" .ElementList =KeyedElement { ","KeyedElement } .KeyedElement = [Key ":" ]Element .Key =FieldName |Expression |LiteralValue .FieldName =identifier .Element =Expression |LiteralValue .
The LiteralType'score typeT
must be a struct, array, slice, or map type(the syntax enforces this constraint except when the type is givenas a TypeName).The types of the elements and keys must beassignableto the respective field, element, and key types of typeT
;there is no additional conversion.The key is interpreted as a field name for struct literals,an index for array and slice literals, and a key for map literals.For map literals, all elements must have a key. It is an errorto specify multiple elements with the same field name orconstant key value. For non-constant map keys, see the section onevaluation order.
For struct literals the following rules apply:
- A key must be a field name declared in the struct type.
- An element list that does not contain any keys must list an element for each struct field in the order in which the fields are declared.
- If any element has a key, every element must have a key.
- An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
- A literal may omit the element list; such a literal evaluates to the zero value for its type.
- It is an error to specify an element for a non-exported field of a struct belonging to a different package.
Given the declarations
type Point3D struct { x, y, z float64 }type Line struct { p, q Point3D }
one may write
origin := Point3D{} // zero value for Point3Dline := Line{origin, Point3D{y: -4, z: 12.3}} // zero value for line.q.x
For array and slice literals the following rules apply:
- Each element has an associated integer index marking its position in the array.
- An element with a key uses the key as its index. The key must be a non-negative constantrepresentable by a value of type
int
; and if it is typed it must be ofinteger type. - An element without a key uses the previous element's index plus one. If the first element has no key, its index is zero.
Taking the address of a composite literalgenerates a pointer to a uniquevariable initializedwith the literal's value.
var pointer *Point3D = &Point3D{y: 1000}
Note that thezero value for a slice or maptype is not the same as an initialized but empty value of the same type.Consequently, taking the address of an empty slice or map composite literaldoes not have the same effect as allocating a new slice or map value withnew.
p1 := &[]int{} // p1 points to an initialized, empty slice with value []int{} and length 0p2 := new([]int) // p2 points to an uninitialized slice with value nil and length 0
The length of an array literal is the length specified in the literal type.If fewer elements than the length are provided in the literal, the missingelements are set to the zero value for the array element type.It is an error to provide elements with index values outside the index rangeof the array. The notation...
specifies an array length equalto the maximum element index plus one.
buffer := [10]string{} // len(buffer) == 10intSet := [6]int{1, 2, 3, 5} // len(intSet) == 6days := [...]string{"Sat", "Sun"} // len(days) == 2
A slice literal describes the entire underlying array literal.Thus the length and capacity of a slice literal are the maximumelement index plus one. A slice literal has the form
[]T{x1, x2, … xn}
and is shorthand for a slice operation applied to an array:
tmp := [n]T{x1, x2, … xn}tmp[0 : n]
Within a composite literal of array, slice, or map typeT
,elements or map keys that are themselves composite literals may elide the respectiveliteral type if it is identical to the element or key type ofT
.Similarly, elements or keys that are addresses of composite literals may elidethe&T
when the element or key type is*T
.
[...]Point{{1.5, -3.5}, {0, 0}} // same as [...]Point{Point{1.5, -3.5}, Point{0, 0}}[][]int{{1, 2, 3}, {4, 5}} // same as [][]int{[]int{1, 2, 3}, []int{4, 5}}[][]Point{{{0, 1}, {1, 2}}} // same as [][]Point{[]Point{Point{0, 1}, Point{1, 2}}}map[string]Point{"orig": {0, 0}} // same as map[string]Point{"orig": Point{0, 0}}map[Point]string{{0, 0}: "orig"} // same as map[Point]string{Point{0, 0}: "orig"}type PPoint *Point[2]*Point{{1.5, -3.5}, {}} // same as [2]*Point{&Point{1.5, -3.5}, &Point{}}[2]PPoint{{1.5, -3.5}, {}} // same as [2]PPoint{PPoint(&Point{1.5, -3.5}), PPoint(&Point{})}
A parsing ambiguity arises when a composite literal using theTypeName form of the LiteralType appears as an operand between thekeyword and the opening brace of the blockof an "if", "for", or "switch" statement, and the composite literalis not enclosed in parentheses, square brackets, or curly braces.In this rare case, the opening brace of the literal is erroneously parsedas the one introducing the block of statements. To resolve the ambiguity,the composite literal must appear within parentheses.
if x == (T{a,b,c}[i]) { … }if (x == T{a,b,c}[i]) { … }
Examples of valid array, slice, and map literals:
// list of prime numbersprimes := []int{2, 3, 5, 7, 9, 2147483647}// vowels[ch] is true if ch is a vowelvowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}// the array [10]float32{-1, 0, 0, 0, -0.1, -0.1, 0, 0, 0, -1}filter := [10]float32{-1, 4: -0.1, -0.1, 9: -1}// frequencies in Hz for equal-tempered scale (A4 = 440Hz)noteFrequency := map[string]float32{"C0": 16.35, "D0": 18.35, "E0": 20.60, "F0": 21.83,"G0": 24.50, "A0": 27.50, "B0": 30.87,}
Function literals
A function literal represents an anonymousfunction.Function literals cannot declare type parameters.
FunctionLit = "func"SignatureFunctionBody .
func(a, b int, z float64) bool { return a*b < int(z) }
A function literal can be assigned to a variable or invoked directly.
f := func(x, y int) int { return x + y }func(ch chan int) { ch <- ACK }(replyChan)
Function literals areclosures: they may refer to variablesdefined in a surrounding function. Those variables are then shared betweenthe surrounding function and the function literal, and they survive as longas they are accessible.
Primary expressions
Primary expressions are the operands for unary and binary expressions.
PrimaryExpr =Operand |Conversion |MethodExpr |PrimaryExprSelector |PrimaryExprIndex |PrimaryExprSlice |PrimaryExprTypeAssertion |PrimaryExprArguments .Selector = "."identifier .Index = "["Expression [ "," ] "]" .Slice = "[" [Expression ] ":" [Expression ] "]" | "[" [Expression ] ":"Expression ":"Expression "]" .TypeAssertion = "." "("Type ")" .Arguments = "(" [ (ExpressionList |Type [ ","ExpressionList ] ) [ "..." ] [ "," ] ] ")" .
x2(s + ".txt")f(3.1415, true)Point{1, 2}m["foo"]s[i : j + 1]obj.colorf.p[i].x()
Selectors
For aprimary expressionx
that is not apackage name, theselector expression
x.f
denotes the field or methodf
of the valuex
(or sometimes*x
; see below).The identifierf
is called the (field or method)selector;it must not be theblank identifier.The type of the selector expression is the type off
.Ifx
is a package name, see the section onqualified identifiers.
A selectorf
may denote a field or methodf
ofa typeT
, or it may referto a field or methodf
of a nestedembedded field ofT
.The number of embedded fields traversedto reachf
is called itsdepth inT
.The depth of a field or methodf
declared inT
is zero.The depth of a field or methodf
declared inan embedded fieldA
inT
is thedepth off
inA
plus one.
The following rules apply to selectors:
- For a value
x
of typeT
or*T
whereT
is not a pointer or interface type,x.f
denotes the field or method at the shallowest depthinT
where there is such anf
.If there is not exactlyonef
with shallowest depth, the selector expression is illegal. - For a value
x
of typeI
whereI
is an interface type,x.f
denotes the actual method with namef
of the dynamic value ofx
.If there is no method with namef
in themethod set ofI
, the selectorexpression is illegal. - As an exception, if the type of
x
is adefinedpointer type and(*x).f
is a valid selector expression denoting a field(but not a method),x.f
is shorthand for(*x).f
. - In all other cases,
x.f
is illegal. - If
x
is of pointer type and has the valuenil
andx.f
denotes a struct field,assigning to or evaluatingx.f
causes arun-time panic. - If
x
is of interface type and has the valuenil
,calling orevaluating the methodx.f
causes arun-time panic.
For example, given the declarations:
type T0 struct {x int}func (*T0) M0()type T1 struct {y int}func (T1) M1()type T2 struct {z intT1*T0}func (*T2) M2()type Q *T2var t T2 // with t.T0 != nilvar p *T2 // with p != nil and (*p).T0 != nilvar q Q = p
one may write:
t.z // t.zt.y // t.T1.yt.x // (*t.T0).xp.z // (*p).zp.y // (*p).T1.yp.x // (*(*p).T0).xq.x // (*(*q).T0).x (*q).x is a valid field selectorp.M0() // ((*p).T0).M0() M0 expects *T0 receiverp.M1() // ((*p).T1).M1() M1 expects T1 receiverp.M2() // p.M2() M2 expects *T2 receivert.M2() // (&t).M2() M2 expects *T2 receiver, see section on Calls
but the following is invalid:
q.M0() // (*q).M0 is valid but not a field selector
Method expressions
IfM
is in themethod set of typeT
,T.M
is a function that is callable as a regular functionwith the same arguments asM
prefixed by an additionalargument that is the receiver of the method.
MethodExpr =ReceiverType "."MethodName .ReceiverType =Type .
Consider a struct typeT
with two methods,Mv
, whose receiver is of typeT
, andMp
, whose receiver is of type*T
.
type T struct {a int}func (tv T) Mv(a int) int { return 0 } // value receiverfunc (tp *T) Mp(f float32) float32 { return 1 } // pointer receivervar t T
The expression
T.Mv
yields a function equivalent toMv
butwith an explicit receiver as its first argument; it has signature
func(tv T, a int) int
That function may be called normally with an explicit receiver, sothese five invocations are equivalent:
t.Mv(7)T.Mv(t, 7)(T).Mv(t, 7)f1 := T.Mv; f1(t, 7)f2 := (T).Mv; f2(t, 7)
Similarly, the expression
(*T).Mp
yields a function value representingMp
with signature
func(tp *T, f float32) float32
For a method with a value receiver, one can derive a functionwith an explicit pointer receiver, so
(*T).Mv
yields a function value representingMv
with signature
func(tv *T, a int) int
Such a function indirects through the receiver to create a valueto pass as the receiver to the underlying method;the method does not overwrite the value whose address is passed inthe function call.
The final case, a value-receiver function for a pointer-receiver method,is illegal because pointer-receiver methods are not in the method setof the value type.
Function values derived from methods are called with function call syntax;the receiver is provided as the first argument to the call.That is, givenf := T.Mv
,f
is invokedasf(t, 7)
nott.f(7)
.To construct a function that binds the receiver, use afunction literal ormethod value.
It is legal to derive a function value from a method of an interface type.The resulting function takes an explicit receiver of that interface type.
Method values
If the expressionx
has static typeT
andM
is in themethod set of typeT
,x.M
is called amethod value.The method valuex.M
is a function value that is callablewith the same arguments as a method call ofx.M
.The expressionx
is evaluated and saved during the evaluation of themethod value; the saved copy is then used as the receiver in any calls,which may be executed later.
type S struct { *T }type T intfunc (t T) M() { print(t) }t := new(T)s := S{T: t}f := t.M // receiver *t is evaluated and stored in fg := s.M // receiver *(s.T) is evaluated and stored in g*t = 42 // does not affect stored receivers in f and g
The typeT
may be an interface or non-interface type.
As in the discussion ofmethod expressions above,consider a struct typeT
with two methods,Mv
, whose receiver is of typeT
, andMp
, whose receiver is of type*T
.
type T struct {a int}func (tv T) Mv(a int) int { return 0 } // value receiverfunc (tp *T) Mp(f float32) float32 { return 1 } // pointer receivervar t Tvar pt *Tfunc makeT() T
The expression
t.Mv
yields a function value of type
func(int) int
These two invocations are equivalent:
t.Mv(7)f := t.Mv; f(7)
Similarly, the expression
pt.Mp
yields a function value of type
func(float32) float32
As withselectors, a reference to a non-interface method with a value receiverusing a pointer will automatically dereference that pointer:pt.Mv
is equivalent to(*pt).Mv
.
As withmethod calls, a reference to a non-interface method with a pointer receiverusing an addressable value will automatically take the address of that value:t.Mp
is equivalent to(&t).Mp
.
f := t.Mv; f(7) // like t.Mv(7)f := pt.Mp; f(7) // like pt.Mp(7)f := pt.Mv; f(7) // like (*pt).Mv(7)f := t.Mp; f(7) // like (&t).Mp(7)f := makeT().Mp // invalid: result of makeT() is not addressable
Although the examples above use non-interface types, it is also legal to create a method valuefrom a value of interface type.
var i interface { M(int) } = myValf := i.M; f(7) // like i.M(7)
Index expressions
A primary expression of the form
a[x]
denotes the element of the array, pointer to array, slice, string or mapa
indexed byx
.The valuex
is called theindex ormap key, respectively.The following rules apply:
Ifa
is neither a map nor a type parameter:
- the index
x
must be an untyped constant or itscore type must be aninteger - a constant index must be non-negative andrepresentable by a value of type
int
- a constant index that is untyped is given type
int
- the index
x
isin range if0 <= x < len(a)
, otherwise it isout of range
Fora
ofarray typeA
:
- aconstant index must be in range
- if
x
is out of range at run time, arun-time panic occurs a[x]
is the array element at indexx
and the type ofa[x]
is the element type ofA
Fora
ofpointer to array type:
a[x]
is shorthand for(*a)[x]
Fora
ofslice typeS
:
- if
x
is out of range at run time, arun-time panic occurs a[x]
is the slice element at indexx
and the type ofa[x]
is the element type ofS
Fora
ofstring type:
- aconstant index must be in range if the string
a
is also constant - if
x
is out of range at run time, arun-time panic occurs a[x]
is the non-constant byte value at indexx
and the type ofa[x]
isbyte
a[x]
may not be assigned to
Fora
ofmap typeM
:
x
's type must beassignable to the key type ofM
- if the map contains an entry with key
x
,a[x]
is the map element with keyx
and the type ofa[x]
is the element type ofM
- if the map is
nil
or does not contain such an entry,a[x]
is thezero value for the element type ofM
Fora
oftype parameter typeP
:
- The index expression
a[x]
must be valid for values of all types inP
's type set. - The element types of all types in
P
's type set must be identical. In this context, the element type of a string type isbyte
. - If there is a map type in the type set of
P
, all types in that type set must be map types, and the respective key types must be all identical. a[x]
is the array, slice, or string element at indexx
, or the map element with keyx
of the type argument thatP
is instantiated with, and the type ofa[x]
is the type of the (identical) element types.a[x]
may not be assigned to ifP
's type set includes string types.
Otherwisea[x]
is illegal.
An index expression on a mapa
of typemap[K]V
used in anassignment statement or initialization of the special form
v, ok = a[x]v, ok := a[x]var v, ok = a[x]
yields an additional untyped boolean value. The value ofok
istrue
if the keyx
is present in the map, andfalse
otherwise.
Assigning to an element of anil
map causes arun-time panic.
Slice expressions
Slice expressions construct a substring or slice from a string, array, pointerto array, or slice. There are two variants: a simple form that specifies a lowand high bound, and a full form that also specifies a bound on the capacity.
Simple slice expressions
The primary expression
a[low : high]
constructs a substring or slice. Thecore type ofa
must be a string, array, pointer to array, slice, or abytestring
.Theindiceslow
andhigh
select which elements of operanda
appearin the result. The result has indices starting at 0 and length equal tohigh
- low
.After slicing the arraya
a := [5]int{1, 2, 3, 4, 5}s := a[1:4]
the slices
has type[]int
, length 3, capacity 4, and elements
s[0] == 2s[1] == 3s[2] == 4
For convenience, any of the indices may be omitted. A missinglow
index defaults to zero; a missinghigh
index defaults to the length of thesliced operand:
a[2:] // same as a[2 : len(a)]a[:3] // same as a[0 : 3]a[:] // same as a[0 : len(a)]
Ifa
is a pointer to an array,a[low : high]
is shorthand for(*a)[low : high]
.
For arrays or strings, the indices arein range if0
<=low
<=high
<=len(a)
,otherwise they areout of range.For slices, the upper index bound is the slice capacitycap(a)
rather than the length.Aconstant index must be non-negative andrepresentable by a value of typeint
; for arrays or constant strings, constant indices must also be in range.If both indices are constant, they must satisfylow <= high
.If the indices are out of range at run time, arun-time panic occurs.
Except foruntyped strings, if the sliced operand is a string or slice,the result of the slice operation is a non-constant value of the same type as the operand.For untyped string operands the result is a non-constant value of typestring
.If the sliced operand is an array, it must beaddressableand the result of the slice operation is a slice with the same element type as the array.
If the sliced operand of a valid slice expression is anil
slice, the resultis anil
slice. Otherwise, if the result is a slice, it shares its underlyingarray with the operand.
var a [10]ints1 := a[3:7] // underlying array of s1 is array a; &s1[2] == &a[5]s2 := s1[1:4] // underlying array of s2 is underlying array of s1 which is array a; &s2[1] == &a[5]s2[1] = 42 // s2[1] == s1[2] == a[5] == 42; they all refer to the same underlying array elementvar s []ints3 := s[:0] // s3 == nil
Full slice expressions
The primary expression
a[low : high : max]
constructs a slice of the same type, and with the same length and elements as the simple sliceexpressiona[low : high]
. Additionally, it controls the resulting slice's capacityby setting it tomax - low
. Only the first index may be omitted; it defaults to 0.Thecore type ofa
must be an array, pointer to array,or slice (but not a string).After slicing the arraya
a := [5]int{1, 2, 3, 4, 5}t := a[1:3:5]
the slicet
has type[]int
, length 2, capacity 4, and elements
t[0] == 2t[1] == 3
As for simple slice expressions, ifa
is a pointer to an array,a[low : high : max]
is shorthand for(*a)[low : high : max]
.If the sliced operand is an array, it must beaddressable.
The indices arein range if0 <= low <= high <= max <= cap(a)
,otherwise they areout of range.Aconstant index must be non-negative andrepresentable by a value of typeint
; for arrays, constant indices must also be in range.If multiple indices are constant, the constants that are present must be in range relative to eachother.If the indices are out of range at run time, arun-time panic occurs.
Type assertions
For an expressionx
ofinterface type,but not atype parameter, and a typeT
,the primary expression
x.(T)
asserts thatx
is notnil
and that the value stored inx
is of typeT
.The notationx.(T)
is called atype assertion.
More precisely, ifT
is not an interface type,x.(T)
assertsthat the dynamic type ofx
isidenticalto the typeT
.In this case,T
mustimplement the (interface) type ofx
;otherwise the type assertion is invalid since it is not possible forx
to store a value of typeT
.IfT
is an interface type,x.(T)
asserts that the dynamic typeofx
implements the interfaceT
.
If the type assertion holds, the value of the expression is the valuestored inx
and its type isT
. If the type assertion is false,arun-time panic occurs.In other words, even though the dynamic type ofx
is known only at run time, the type ofx.(T)
isknown to beT
in a correct program.
var x interface{} = 7 // x has dynamic type int and value 7i := x.(int) // i has type int and value 7type I interface { m() }func f(y I) {s := y.(string) // illegal: string does not implement I (missing method m)r := y.(io.Reader) // r has type io.Reader and the dynamic type of y must implement both I and io.Reader…}
A type assertion used in anassignment statement or initialization of the special form
v, ok = x.(T)v, ok := x.(T)var v, ok = x.(T)var v, ok interface{} = x.(T) // dynamic types of v and ok are T and bool
yields an additional untyped boolean value. The value ofok
istrue
if the assertion holds. Otherwise it isfalse
and the value ofv
isthezero value for typeT
.Norun-time panic occurs in this case.
Calls
Given an expressionf
with acore typeF
offunction type,
f(a1, a2, … an)
callsf
with argumentsa1, a2, … an
.Except for one special case, arguments must be single-valued expressionsassignable to the parameter types ofF
and are evaluated before the function is called.The type of the expression is the result type ofF
.A method invocation is similar but the method itselfis specified as a selector upon a value of the receiver type forthe method.
math.Atan2(x, y) // function callvar pt *Pointpt.Scale(3.5) // method call with receiver pt
Iff
denotes a generic function, it must beinstantiated before it can be calledor used as a function value.
In a function call, the function value and arguments are evaluated inthe usual order.After they are evaluated, new storage is allocated for the function'svariables, which includes its parametersand results.Then, the arguments of the call arepassed to the function,which means that they areassignedto their corresponding function parameters,and the called function begins execution.The return parameters of the function are passedback to the caller when the function returns.
Calling anil
function valuecauses arun-time panic.
As a special case, if the return values of a function or methodg
are equal in number and individuallyassignable to the parameters of another function or methodf
, then the callf(g(parameters_of_g))
will invokef
after passing the return values ofg
to the parameters off
in order.The call off
must contain no parameters other than the call ofg
,andg
must have at least one return value.Iff
has a final...
parameter, it isassigned the return values ofg
that remain afterassignment of regular parameters.
func Split(s string, pos int) (string, string) {return s[0:pos], s[pos:]}func Join(s, t string) string {return s + t}if Join(Split(value, len(value)/2)) != value {log.Panic("test fails")}
A method callx.m()
is valid if themethod setof (the type of)x
containsm
and theargument list can be assigned to the parameter list ofm
.Ifx
isaddressable and&x
's methodset containsm
,x.m()
is shorthandfor(&x).m()
:
var p Pointp.Scale(3.5)
There is no distinct method type and there are no method literals.
Passing arguments to...
parameters
Iff
isvariadic with a finalparameterp
of type...T
, then withinf
the type ofp
is equivalent to type[]T
.Iff
is invoked with no actual arguments forp
,the valuepassed top
isnil
.Otherwise, the value passed is a new sliceof type[]T
with a new underlying array whose successive elementsare the actual arguments, which all must beassignabletoT
. The length and capacity of the slice is thereforethe number of arguments bound top
and may differ for eachcall site.
Given the function and calls
func Greeting(prefix string, who ...string)Greeting("nobody")Greeting("hello:", "Joe", "Anna", "Eileen")
withinGreeting
,who
will have the valuenil
in the first call, and[]string{"Joe", "Anna", "Eileen"}
in the second.
If the final argument is assignable to a slice type[]T
andis followed by...
, it is passed unchanged as the valuefor a...T
parameter. In this case no new slice is created.
Given the slices
and call
s := []string{"James", "Jasmine"}Greeting("goodbye:", s...)
withinGreeting
,who
will have the same value ass
with the same underlying array.
Instantiations
A generic function or type isinstantiated by substitutingtype argumentsfor the type parameters [Go 1.18].Instantiation proceeds in two steps:
- Each type argument is substituted for its corresponding type parameter in the genericdeclaration.This substitution happens across the entire function or type declaration,including the type parameter list itself and any types in that list.
- After substitution, each type argument mustsatisfytheconstraint (instantiated, if necessary)of the corresponding type parameter. Otherwise instantiation fails.
Instantiating a type results in a new non-genericnamed type;instantiating a function produces a new non-generic function.
type parameter list type arguments after substitution[P any] int int satisfies any[S ~[]E, E any] []int, int []int satisfies ~[]int, int satisfies any[P io.Writer] string illegal: string doesn't satisfy io.Writer[P comparable] any any satisfies (but does not implement) comparable
When using a generic function, type arguments may be provided explicitly,or they may be partially or completelyinferredfrom the context in which the function is used.Provided that they can be inferred, type argument lists may be omitted entirely if the function is:
- called with ordinary arguments,
- assigned to a variable with a known type
- passed as an argument to another function, or
- returned as a result.
In all other cases, a (possibly partial) type argument list must be present.If a type argument list is absent or partial, all missing type argumentsmust be inferrable from the context in which the function is used.
// sum returns the sum (concatenation, for strings) of its arguments.func sum[T ~int | ~float64 | ~string](x... T) T { … }x := sum // illegal: the type of x is unknownintSum := sum[int] // intSum has type func(x... int) inta := intSum(2, 3) // a has value 5 of type intb := sum[float64](2.0, 3) // b has value 5.0 of type float64c := sum(b, -1) // c has value 4.0 of type float64type sumFunc func(x... string) stringvar f sumFunc = sum // same as var f sumFunc = sum[string]f = sum // same as f = sum[string]
A partial type argument list cannot be empty; at least the first argument must be present.The list is a prefix of the full list of type arguments, leaving the remaining argumentsto be inferred. Loosely speaking, type arguments may be omitted from "right to left".
func apply[S ~[]E, E any](s S, f func(E) E) S { … }f0 := apply[] // illegal: type argument list cannot be emptyf1 := apply[[]int] // type argument for S explicitly provided, type argument for E inferredf2 := apply[[]string, string] // both type arguments explicitly providedvar bytes []byter := apply(bytes, func(byte) byte { … }) // both type arguments inferred from the function arguments
For a generic type, all type arguments must always be provided explicitly.
Type inference
A use of a generic function may omit some or all type arguments if they can beinferred from the context within which the function is used, includingthe constraints of the function's type parameters.Type inference succeeds if it can infer the missing type argumentsandinstantiation succeeds with theinferred type arguments.Otherwise, type inference fails and the program is invalid.
Type inference uses the type relationships between pairs of types for inference:For instance, a function argument must beassignableto its respective function parameter; this establishes a relationship between thetype of the argument and the type of the parameter.If either of these two types contains type parameters, type inference looks for thetype arguments to substitute the type parameters with such that the assignabilityrelationship is satisfied.Similarly, type inference uses the fact that a type argument mustsatisfy the constraint of its respectivetype parameter.
Each such pair of matched types corresponds to atype equation containingone or multiple type parameters, from one or possibly multiple generic functions.Inferring the missing type arguments means solving the resulting set of typeequations for the respective type parameters.
For example, given
// dedup returns a copy of the argument slice with any duplicate entries removed.func dedup[S ~[]E, E comparable](S) S { … }type Slice []intvar s Slices = dedup(s) // same as s = dedup[Slice, int](s)
the variables
of typeSlice
must be assignable tothe function parameter typeS
for the program to be valid.To reduce complexity, type inference ignores the directionality of assignments,so the type relationship betweenSlice
andS
can beexpressed via the (symmetric) type equationSlice ≡A S
(orS ≡A Slice
for that matter),where theA
in≡A
indicates that the LHS and RHS types must match per assignability rules(see the section ontype unification fordetails).Similarly, the type parameterS
must satisfy its constraint~[]E
. This can be expressed asS ≡C ~[]E
whereX ≡C Y
stands for"X
satisfies constraintY
".These observations lead to a set of two equations
Slice ≡A S (1)S ≡C ~[]E (2)
which now can be solved for the type parametersS
andE
.From (1) a compiler can infer that the type argument forS
isSlice
.Similarly, because the underlying type ofSlice
is[]int
and[]int
must match[]E
of the constraint,a compiler can infer thatE
must beint
.Thus, for these two equations, type inference infers
S ➞ SliceE ➞ int
Given a set of type equations, the type parameters to solve for arethe type parameters of the functions that need to be instantiatedand for which no explicit type arguments is provided.These type parameters are calledbound type parameters.For instance, in thededup
example above, the type parametersS
andE
are bound todedup
.An argument to a generic function call may be a generic function itself.The type parameters of that function are included in the set of boundtype parameters.The types of function arguments may contain type parameters from otherfunctions (such as a generic function enclosing a function call).Those type parameters may also appear in type equations but they arenot bound in that context.Type equations are always solved for the bound type parameters only.
Type inference supports calls of generic functions and assignmentsof generic functions to (explicitly function-typed) variables.This includes passing generic functions as arguments to other(possibly also generic) functions, and returning generic functionsas results.Type inference operates on a set of equations specific to each ofthese cases.The equations are as follows (type argument lists are omitted for clarity):
For a function call
f(a0, a1, …)
wheref
or a function argumentai
isa generic function:
Each pair(ai, pi)
of correspondingfunction arguments and parameters whereai
is not anuntyped constant yields an equationtypeof(pi) ≡A typeof(ai)
.
Ifai
is an untyped constantcj
,andtypeof(pi)
is a bound type parameterPk
,the pair(cj, Pk)
is collected separately fromthe type equations.For an assignment
v = f
of a generic functionf
to a(non-generic) variablev
of function type:typeof(v) ≡A typeof(f)
.For a return statement
return …, f, …
wheref
is ageneric function returned as a result to a (non-generic) result variabler
of function type:typeof(r) ≡A typeof(f)
.
Additionally, each type parameterPk
and corresponding type constraintCk
yields the type equationPk ≡C Ck
.
Type inference gives precedence to type information obtained from typed operandsbefore considering untyped constants.Therefore, inference proceeds in two phases:
The type equations are solved for the boundtype parameters usingtype unification.If unification fails, type inference fails.
For each bound type parameter
Pk
for which no type argumenthas been inferred yet and for which one or more pairs(cj, Pk)
with that same type parameterwere collected, determine theconstant kindof the constantscj
in all those pairs the same way as forconstant expressions.The type argument forPk
is thedefault type for the determined constant kind.If a constant kind cannot be determined due to conflicting constant kinds,type inference fails.
If not all type arguments have been found after these two phases, type inference fails.
If the two phases are successful, type inference determined a type argument for eachbound type parameter:
Pk ➞ Ak
A type argumentAk
may be a composite type,containing other bound type parametersPk
as element types(or even be just another bound type parameter).In a process of repeated simplification, the bound type parameters in each typeargument are substituted with the respective type arguments for those typeparameters until each type argument is free of bound type parameters.
If type arguments contain cyclic references to themselvesthrough bound type parameters, simplification and thus typeinference fails.Otherwise, type inference succeeds.
Type unification
Type inference solves type equations throughtype unification.Type unification recursively compares the LHS and RHS types of anequation, where either or both types may be or contain bound type parameters,and looks for type arguments for those type parameters such that the LHSand RHS match (become identical or assignment-compatible, depending oncontext).To that effect, type inference maintains a map of bound type parametersto inferred type arguments; this map is consulted and updated during type unification.Initially, the bound type parameters are known but the map is empty.During type unification, if a new type argumentA
is inferred,the respective mappingP ➞ A
from type parameter to argumentis added to the map.Conversely, when comparing types, a known type argument(a type argument for which a map entry already exists)takes the place of its corresponding type parameter.As type inference progresses, the map is populated more and moreuntil all equations have been considered, or until unification fails.Type inference succeeds if no unification step fails and the map hasan entry for each type parameter.
For example, given the type equation with the bound type parameterP
[10]struct{ elem P, list []P } ≡A [10]struct{ elem string; list []string }
type inference starts with an empty map.Unification first compares the top-level structure of the LHS and RHStypes.Both are arrays of the same length; they unify if the element types unify.Both element types are structs; they unify if they havethe same number of fields with the same names and if thefield types unify.The type argument forP
is not known yet (there is no map entry),so unifyingP
withstring
addsthe mappingP ➞ string
to the map.Unifying the types of thelist
field requiresunifying[]P
and[]string
andthusP
andstring
.Since the type argument forP
is known at this point(there is a map entry forP
), its type argumentstring
takes the place ofP
.And sincestring
is identical tostring
,this unification step succeeds as well.Unification of the LHS and RHS of the equation is now finished.Type inference succeeds because there is only one type equation,no unification step failed, and the map is fully populated.
Unification uses a combination ofexact andlooseunification depending on whether two types have to beidentical,assignment-compatible, oronly structurally equal.The respectivetype unification rulesare spelled out in detail in theAppendix.
For an equation of the formX ≡A Y
,whereX
andY
are types involvedin an assignment (including parameter passing and return statements),the top-level type structures may unify loosely but element typesmust unify exactly, matching the rules for assignments.
For an equation of the formP ≡C C
,whereP
is a type parameter andC
its corresponding constraint, the unification rules are bitmore complicated:
- If
C
has acore typecore(C)
andP
has a known type argumentA
,core(C)
andA
must unify loosely.IfP
does not have a known type argumentandC
contains exactly one type termT
that is not an underlying (tilde) type, unification adds themappingP ➞ T
to the map. - If
C
does not have a core typeandP
has a known type argumentA
,A
must have all methods ofC
, if any,and corresponding method types must unify exactly.
When solving type equations from type constraints,solving one equation may infer additional type arguments,which in turn may enable solving other equations that dependon those type arguments.Type inference repeats type unification as long as new typearguments are inferred.
Operators
Operators combine operands into expressions.
Expression =UnaryExpr |Expressionbinary_opExpression .UnaryExpr =PrimaryExpr |unary_opUnaryExpr .binary_op = "||" | "&&" |rel_op |add_op |mul_op .rel_op = "==" | "!=" | "<" | "<=" | ">" | ">=" .add_op = "+" | "-" | "|" | "^" .mul_op = "*" | "/" | "%" | "<<" | ">>" | "&" | "&^" .unary_op = "+" | "-" | "!" | "^" | "*" | "&" | "<-" .
Comparisons are discussedelsewhere.For other binary operators, the operand types must beidenticalunless the operation involves shifts or untypedconstants.For operations involving constants only, see the section onconstant expressions.
Except for shift operations, if one operand is an untypedconstantand the other operand is not, the constant is implicitlyconvertedto the type of the other operand.
The right operand in a shift expression must haveinteger type[Go 1.13]or be an untyped constantrepresentable by avalue of typeuint
.If the left operand of a non-constant shift expression is an untyped constant,it is first implicitly converted to the type it would assume if the shift expression werereplaced by its left operand alone.
var a [1024]bytevar s uint = 33// The results of the following examples are given for 64-bit ints.var i = 1<<s // 1 has type intvar j int32 = 1<<s // 1 has type int32; j == 0var k = uint64(1<<s) // 1 has type uint64; k == 1<<33var m int = 1.0<<s // 1.0 has type int; m == 1<<33var n = 1.0<<s == j // 1.0 has type int32; n == truevar o = 1<<s == 2<<s // 1 and 2 have type int; o == falsevar p = 1<<s == 1<<33 // 1 has type int; p == truevar u = 1.0<<s // illegal: 1.0 has type float64, cannot shiftvar u1 = 1.0<<s != 0 // illegal: 1.0 has type float64, cannot shiftvar u2 = 1<<s != 1.0 // illegal: 1 has type float64, cannot shiftvar v1 float32 = 1<<s // illegal: 1 has type float32, cannot shiftvar v2 = string(1<<s) // illegal: 1 is converted to a string, cannot shiftvar w int64 = 1.0<<33 // 1.0<<33 is a constant shift expression; w == 1<<33var x = a[1.0<<s] // panics: 1.0 has type int, but 1<<33 overflows array boundsvar b = make([]byte, 1.0<<s) // 1.0 has type int; len(b) == 1<<33// The results of the following examples are given for 32-bit ints,// which means the shifts will overflow.var mm int = 1.0<<s // 1.0 has type int; mm == 0var oo = 1<<s == 2<<s // 1 and 2 have type int; oo == truevar pp = 1<<s == 1<<33 // illegal: 1 has type int, but 1<<33 overflows intvar xx = a[1.0<<s] // 1.0 has type int; xx == a[0]var bb = make([]byte, 1.0<<s) // 1.0 has type int; len(bb) == 0
Operator precedence
Unary operators have the highest precedence.As the++
and--
operators formstatements, not expressions, they falloutside the operator hierarchy.As a consequence, statement*p++
is the same as(*p)++
.
There are five precedence levels for binary operators.Multiplication operators bind strongest, followed by additionoperators, comparison operators,&&
(logical AND),and finally||
(logical OR):
Precedence Operator 5 * / % << >> & &^ 4 + - | ^ 3 == != < <= > >= 2 && 1 ||
Binary operators of the same precedence associate from left to right.For instance,x / y * z
is the same as(x / y) * z
.
+x // x42 + a - b // (42 + a) - b23 + 3*x[i] // 23 + (3 * x[i])x <= f() // x <= f()^a >> b // (^a) >> bf() || g() // f() || g()x == y+1 && <-chanInt > 0 // (x == (y+1)) && ((<-chanInt) > 0)
Arithmetic operators
Arithmetic operators apply to numeric values and yield a result of the sametype as the first operand. The four standard arithmetic operators (+
,-
,*
,/
) apply tointeger,floating-point, andcomplex types;+
also applies tostrings.The bitwise logical and shift operators apply to integers only.
+ sum integers, floats, complex values, strings- difference integers, floats, complex values* product integers, floats, complex values/ quotient integers, floats, complex values% remainder integers& bitwise AND integers| bitwise OR integers^ bitwise XOR integers&^ bit clear (AND NOT) integers<< left shift integer << integer >= 0>> right shift integer >> integer >= 0
If the operand type is atype parameter,the operator must apply to each type in that type set.The operands are represented as values of the type argument that the type parameterisinstantiated with, and the operation is computedwith the precision of that type argument. For example, given the function:
func dotProduct[F ~float32|~float64](v1, v2 []F) F {var s Ffor i, x := range v1 {y := v2[i]s += x * y}return s}
the productx * y
and the additions += x * y
are computed withfloat32
orfloat64
precision,respectively, depending on the type argument forF
.
Integer operators
For two integer valuesx
andy
, the integer quotientq = x / y
and remainderr = x % y
satisfy the followingrelationships:
x = q*y + r and |r| < |y|
withx / y
truncated towards zero("truncated division").
x y x / y x % y 5 3 1 2-5 3 -1 -2 5 -3 -1 2-5 -3 1 -2
The one exception to this rule is that if the dividendx
isthe most negative value for the int type ofx
, the quotientq = x / -1
is equal tox
(andr = 0
)due to two's-complementinteger overflow:
x, qint8 -128int16 -32768int32 -2147483648int64 -9223372036854775808
If the divisor is aconstant, it must not be zero.If the divisor is zero at run time, arun-time panic occurs.If the dividend is non-negative and the divisor is a constant power of 2,the division may be replaced by a right shift, and computing the remainder maybe replaced by a bitwise AND operation:
x x / 4 x % 4 x >> 2 x & 3 11 2 3 2 3-11 -2 -3 -3 1
The shift operators shift the left operand by the shift count specified by theright operand, which must be non-negative. If the shift count is negative at run time,arun-time panic occurs.The shift operators implement arithmetic shifts if the left operand is a signedinteger and logical shifts if it is an unsigned integer.There is no upper limit on the shift count. Shifts behaveas if the left operand is shiftedn
times by 1 for a shiftcount ofn
.As a result,x << 1
is the same asx*2
andx >> 1
is the same asx/2
but truncated towards negative infinity.
For integer operands, the unary operators+
,-
, and^
are defined asfollows:
+x is 0 + x-x negation is 0 - x^x bitwise complement is m ^ x with m = "all bits set to 1" for unsigned x and m = -1 for signed x
Integer overflow
Forunsigned integer values, the operations+
,-
,*
, and<<
arecomputed modulo 2n, wheren is the bit width ofthe unsigned integer's type.Loosely speaking, these unsigned integer operationsdiscard high bits upon overflow, and programs may rely on "wrap around".
For signed integers, the operations+
,-
,*
,/
, and<<
may legallyoverflow and the resulting value exists and is deterministically definedby the signed integer representation, the operation, and its operands.Overflow does not cause arun-time panic.A compiler may not optimize code under the assumption that overflow doesnot occur. For instance, it may not assume thatx < x + 1
is always true.
Floating-point operators
For floating-point and complex numbers,+x
is the same asx
,while-x
is the negation ofx
.The result of a floating-point or complex division by zero is not specified beyond theIEEE 754 standard; whether arun-time panicoccurs is implementation-specific.
An implementation may combine multiple floating-point operations into a singlefused operation, possibly across statements, and produce a result that differsfrom the value obtained by executing and rounding the instructions individually.An explicitfloating-point typeconversion rounds tothe precision of the target type, preventing fusion that would discard that rounding.
For instance, some architectures provide a "fused multiply and add" (FMA) instructionthat computesx*y + z
without rounding the intermediate resultx*y
.These examples show when a Go implementation can use that instruction:
// FMA allowed for computing r, because x*y is not explicitly rounded:r = x*y + zr = z; r += x*yt = x*y; r = t + z*p = x*y; r = *p + zr = x*y + float64(z)// FMA disallowed for computing r, because it would omit rounding of x*y:r = float64(x*y) + zr = z; r += float64(x*y)t = float64(x*y); r = t + z
String concatenation
Strings can be concatenated using the+
operatoror the+=
assignment operator:
s := "hi" + string(c)s += " and good bye"
String addition creates a new string by concatenating the operands.
Comparison operators
Comparison operators compare two operands and yield an untyped boolean value.
== equal!= not equal< less<= less or equal> greater>= greater or equal
In any comparison, the first operandmust beassignableto the type of the second operand, or vice versa.
The equality operators==
and!=
applyto operands ofcomparable types.The ordering operators<
,<=
,>
, and>=
apply to operands ofordered types.These terms and the result of the comparisons are defined as follows:
- Boolean types are comparable.Two boolean values are equal if they are either both
true
or bothfalse
. - Integer types are comparable and ordered.Two integer values are compared in the usual way.
- Floating-point types are comparable and ordered.Two floating-point values are compared as defined by the IEEE 754 standard.
- Complex types are comparable.Two complex values
u
andv
areequal if bothreal(u) == real(v)
andimag(u) == imag(v)
. - String types are comparable and ordered.Two string values are compared lexically byte-wise.
- Pointer types are comparable.Two pointer values are equal if they point to the same variable or if both have value
nil
.Pointers to distinctzero-size variables may or may not be equal. - Channel types are comparable.Two channel values are equal if they were created by the same call to
make
or if both have valuenil
. - Interface types that are not type parameters are comparable.Two interface values are equal if they haveidentical dynamic typesand equal dynamic values or if both have value
nil
. - A value
x
of non-interface typeX
anda valuet
of interface typeT
can be comparedif typeX
is comparable andX
implementsT
.They are equal ift
's dynamic type is identical toX
andt
's dynamic value is equal tox
. - Struct types are comparable if all their field types are comparable.Two struct values are equal if their correspondingnon-blank field values are equal.The fields are compared in source order, and comparison stops assoon as two field values differ (or all fields have been compared).
- Array types are comparable if their array element types are comparable.Two array values are equal if their corresponding element values are equal.The elements are compared in ascending index order, and comparison stopsas soon as two element values differ (or all elements have been compared).
- Type parameters are comparable if they are strictly comparable (see below).
A comparison of two interface values with identical dynamic typescauses arun-time panic if that typeis not comparable. This behavior applies not only to direct interfacevalue comparisons but also when comparing arrays of interface valuesor structs with interface-valued fields.
Slice, map, and function types are not comparable.However, as a special case, a slice, map, or function value maybe compared to the predeclared identifiernil
.Comparison of pointer, channel, and interface values tonil
is also allowed and follows from the general rules above.
const c = 3 < 4 // c is the untyped boolean constant truetype MyBool boolvar x, y intvar (// The result of a comparison is an untyped boolean.// The usual assignment rules apply.b3 = x == y // b3 has type boolb4 bool = x == y // b4 has type boolb5 MyBool = x == y // b5 has type MyBool)
A type isstrictly comparable if it is comparable and not an interfacetype nor composed of interface types.Specifically:
- Boolean, numeric, string, pointer, and channel types are strictly comparable.
- Struct types are strictly comparable if all their field types are strictly comparable.
- Array types are strictly comparable if their array element types are strictly comparable.
- Type parameters are strictly comparable if all types in their type set are strictly comparable.
Logical operators
Logical operators apply toboolean valuesand yield a result of the same type as the operands.The left operand is evaluated, and then the right if the condition requires it.
&& conditional AND p && q is "if p then q else false"|| conditional OR p || q is "if p then true else q"! NOT !p is "not p"
Address operators
For an operandx
of typeT
, the address operation&x
generates a pointer of type*T
tox
.The operand must beaddressable,that is, either a variable, pointer indirection, or slice indexingoperation; or a field selector of an addressable struct operand;or an array indexing operation of an addressable array.As an exception to the addressability requirement,x
may also be a(possibly parenthesized)composite literal.If the evaluation ofx
would cause arun-time panic,then the evaluation of&x
does too.
For an operandx
of pointer type*T
, the pointerindirection*x
denotes thevariable of typeT
pointedto byx
.Ifx
isnil
, an attempt to evaluate*x
will cause arun-time panic.
&x&a[f(2)]&Point{2, 3}*p*pf(x)var x *int = nil*x // causes a run-time panic&*x // causes a run-time panic
Receive operator
For an operandch
whosecore type is achannel,the value of the receive operation<-ch
is the value receivedfrom the channelch
. The channel direction must permit receive operations,and the type of the receive operation is the element type of the channel.The expression blocks until a value is available.Receiving from anil
channel blocks forever.A receive operation on aclosed channel can always proceedimmediately, yielding the element type'szero valueafter any previously sent values have been received.
v1 := <-chv2 = <-chf(<-ch)<-strobe // wait until clock pulse and discard received value
A receive expression used in anassignment statement or initialization of the special form
x, ok = <-chx, ok := <-chvar x, ok = <-chvar x, ok T = <-ch
yields an additional untyped boolean result reporting whether thecommunication succeeded. The value ofok
istrue
if the value received was delivered by a successful send operation to thechannel, orfalse
if it is a zero value generated because thechannel is closed and empty.
Conversions
A conversion changes thetype of an expressionto the type specified by the conversion.A conversion may appear literally in the source, or it may beimpliedby the context in which an expression appears.
Anexplicit conversion is an expression of the formT(x)
whereT
is a type andx
is an expressionthat can be converted to typeT
.
Conversion =Type "("Expression [ "," ] ")" .
If the type starts with the operator*
or<-
,or if the type starts with the keywordfunc
and has no result list, it must be parenthesized whennecessary to avoid ambiguity:
*Point(p) // same as *(Point(p))(*Point)(p) // p is converted to *Point<-chan int(c) // same as <-(chan int(c))(<-chan int)(c) // c is converted to <-chan intfunc()(x) // function signature func() x(func())(x) // x is converted to func()(func() int)(x) // x is converted to func() intfunc() int(x) // x is converted to func() int (unambiguous)
Aconstant valuex
can be converted totypeT
ifx
isrepresentableby a value ofT
.As a special case, an integer constantx
can be explicitly converted to astring type using thesame ruleas for non-constantx
.
Converting a constant to a type that is not atype parameteryields a typed constant.
uint(iota) // iota value of type uintfloat32(2.718281828) // 2.718281828 of type float32complex128(1) // 1.0 + 0.0i of type complex128float32(0.49999999) // 0.5 of type float32float64(-1e-1000) // 0.0 of type float64string('x') // "x" of type stringstring(0x266c) // "♬" of type stringmyString("foo" + "bar") // "foobar" of type myStringstring([]byte{'a'}) // not a constant: []byte{'a'} is not a constant(*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string typeint(1.2) // illegal: 1.2 cannot be represented as an intstring(65.0) // illegal: 65.0 is not an integer constant
Converting a constant to a type parameter yields anon-constant value of that type,with the value represented as a value of the type argument that the type parameterisinstantiated with.For example, given the function:
func f[P ~float32|~float64]() {… P(1.1) …}
the conversionP(1.1)
results in a non-constant value of typeP
and the value1.1
is represented as afloat32
or afloat64
depending on the type argument forf
.Accordingly, iff
is instantiated with afloat32
type,the numeric value of the expressionP(1.1) + 1.2
will be computedwith the same precision as the corresponding non-constantfloat32
addition.
A non-constant valuex
can be converted to typeT
in any of these cases:
x
isassignabletoT
.- ignoring struct tags (see below),
x
's type andT
are nottype parameters but haveidenticalunderlying types. - ignoring struct tags (see below),
x
's type andT
are pointer typesthat are notnamed types,and their pointer base types are not type parameters buthave identical underlying types. x
's type andT
are both integer or floatingpoint types.x
's type andT
are both complex types.x
is an integer or a slice of bytes or runesandT
is a string type.x
is a string andT
is a slice of bytes or runes.x
is a slice,T
is an array [Go 1.20]or a pointer to an array [Go 1.17],and the slice and array types haveidentical element types.
Additionally, ifT
orx
's typeV
are typeparameters,x
can also be converted to typeT
if one of the following conditions applies:
- Both
V
andT
are type parameters and a value of eachtype inV
's type set can be converted to each type inT
'stype set. - Only
V
is a type parameter and a value of eachtype inV
's type set can be converted toT
. - Only
T
is a type parameter andx
can be converted to eachtype inT
's type set.
Struct tags are ignored when comparing struct typesfor identity for the purpose of conversion:
type Person struct {Name stringAddress *struct {Street stringCity string}}var data *struct {Name string `json:"name"`Address *struct {Street string `json:"street"`City string `json:"city"`} `json:"address"`}var person = (*Person)(data) // ignoring tags, the underlying types are identical
Specific rules apply to (non-constant) conversions between numeric types orto and from a string type.These conversions may change the representation ofx
and incur a run-time cost.All other conversions only change the type but not the representationofx
.
There is no linguistic mechanism to convert between pointers and integers.The packageunsafe
implements this functionality under restricted circumstances.
Conversions between numeric types
For the conversion of non-constant numeric values, the following rules apply:
- When converting betweeninteger types, if the value is a signed integer, it issign extended to implicit infinite precision; otherwise it is zero extended.It is then truncated to fit in the result type's size.For example, if
v := uint16(0x10F0)
, thenuint32(int8(v)) == 0xFFFFFFF0
.The conversion always yields a valid value; there is no indication of overflow. - When converting afloating-point number to an integer, the fraction is discarded(truncation towards zero).
- When converting an integer or floating-point number to a floating-point type,or acomplex number to another complex type, the result value is roundedto the precision specified by the destination type.For instance, the value of a variable
x
of typefloat32
may be stored using additional precision beyond that of an IEEE 754 32-bit number,but float32(x) represents the result of roundingx
's value to32-bit precision. Similarly,x + 0.1
may use more than 32 bitsof precision, butfloat32(x + 0.1)
does not.
In all non-constant conversions involving floating-point or complex values,if the result type cannot represent the value the conversionsucceeds but the result value is implementation-dependent.
Conversions to and from a string type
- Converting a slice of bytes to a string type yieldsa string whose successive bytes are the elements of the slice.
string([]byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"string([]byte{}) // ""string([]byte(nil)) // ""type bytes []bytestring(bytes{'h', 'e', 'l', 'l', '\xc3', '\xb8'}) // "hellø"type myByte bytestring([]myByte{'w', 'o', 'r', 'l', 'd', '!'}) // "world!"myString([]myByte{'\xf0', '\x9f', '\x8c', '\x8d'}) // "🌍"
- Converting a slice of runes to a string type yieldsa string that is the concatenation of the individual rune valuesconverted to strings.
string([]rune{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"string([]rune{}) // ""string([]rune(nil)) // ""type runes []runestring(runes{0x767d, 0x9d6c, 0x7fd4}) // "\u767d\u9d6c\u7fd4" == "白鵬翔"type myRune runestring([]myRune{0x266b, 0x266c}) // "\u266b\u266c" == "♫♬"myString([]myRune{0x1f30e}) // "\U0001f30e" == "🌎"
- Converting a value of a string type to a slice of bytes typeyields a non-nil slice whose successive elements are the bytes of the string.Thecapacity of the resulting slice isimplementation-specific and may be larger than the slice length.
[]byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}[]byte("") // []byte{}bytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'}[]myByte("world!") // []myByte{'w', 'o', 'r', 'l', 'd', '!'}[]myByte(myString("🌏")) // []myByte{'\xf0', '\x9f', '\x8c', '\x8f'}
- Converting a value of a string type to a slice of runes typeyields a slice containing the individual Unicode code points of the string.Thecapacity of the resulting slice isimplementation-specific and may be larger than the slice length.
[]rune(myString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4}[]rune("") // []rune{}runes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4}[]myRune("♫♬") // []myRune{0x266b, 0x266c}[]myRune(myString("🌐")) // []myRune{0x1f310}
- Finally, for historical reasons, an integer value may be converted to a string type.This form of conversion yields a string containing the (possibly multi-byte) UTF-8representation of the Unicode code point with the given integer value.Values outside the range of valid Unicode code points are converted to
"\uFFFD"
.string('a') // "a"string(65) // "A"string('\xf8') // "\u00f8" == "ø" == "\xc3\xb8"string(-1) // "\ufffd" == "\xef\xbf\xbd"type myString stringmyString('\u65e5') // "\u65e5" == "日" == "\xe6\x97\xa5"
Note: This form of conversion may eventually be removed from the language.Thego vet
tool flags certaininteger-to-string conversions as potential errors.Library functions such asutf8.AppendRune
orutf8.EncodeRune
should be used instead.
Conversions from slice to array or array pointer
Converting a slice to an array yields an array containing the elements of the underlying array of the slice.Similarly, converting a slice to an array pointer yields a pointer to the underlying array of the slice.In both cases, if thelength of the slice is less than the length of the array,arun-time panic occurs.
s := make([]byte, 2, 4)a0 := [0]byte(s)a1 := [1]byte(s[1:]) // a1[0] == s[1]a2 := [2]byte(s) // a2[0] == s[0]a4 := [4]byte(s) // panics: len([4]byte) > len(s)s0 := (*[0]byte)(s) // s0 != nils1 := (*[1]byte)(s[1:]) // &s1[0] == &s[1]s2 := (*[2]byte)(s) // &s2[0] == &s[0]s4 := (*[4]byte)(s) // panics: len([4]byte) > len(s)var t []stringt0 := [0]string(t) // ok for nil slice tt1 := (*[0]string)(t) // t1 == nilt2 := (*[1]string)(t) // panics: len([1]string) > len(t)u := make([]byte, 0)u0 := (*[0]byte)(u) // u0 != nil
Constant expressions
Constant expressions may contain onlyconstantoperands and are evaluated at compile time.
Untyped boolean, numeric, and string constants may be used as operandswherever it is legal to use an operand of boolean, numeric, or string type,respectively.
A constantcomparison always yieldsan untyped boolean constant. If the left operand of a constantshift expression is an untyped constant, theresult is an integer constant; otherwise it is a constant of the sametype as the left operand, which must be ofinteger type.
Any other operation on untyped constants results in an untyped constant of thesame kind; that is, a boolean, integer, floating-point, complex, or stringconstant.If the untyped operands of a binary operation (other than a shift) are ofdifferent kinds, the result is of the operand's kind that appears later in thislist: integer, rune, floating-point, complex.For example, an untyped integer constant divided by anuntyped complex constant yields an untyped complex constant.
const a = 2 + 3.0 // a == 5.0 (untyped floating-point constant)const b = 15 / 4 // b == 3 (untyped integer constant)const c = 15 / 4.0 // c == 3.75 (untyped floating-point constant)const Θ float64 = 3/2 // Θ == 1.0 (type float64, 3/2 is integer division)const Π float64 = 3/2. // Π == 1.5 (type float64, 3/2. is float division)const d = 1 << 3.0 // d == 8 (untyped integer constant)const e = 1.0 << 3 // e == 8 (untyped integer constant)const f = int32(1) << 33 // illegal (constant 8589934592 overflows int32)const g = float64(2) >> 1 // illegal (float64(2) is a typed floating-point constant)const h = "foo" > "bar" // h == true (untyped boolean constant)const j = true // j == true (untyped boolean constant)const k = 'w' + 1 // k == 'x' (untyped rune constant)const l = "hi" // l == "hi" (untyped string constant)const m = string(k) // m == "x" (type string)const Σ = 1 - 0.707i // (untyped complex constant)const Δ = Σ + 2.0e-4 // (untyped complex constant)const Φ = iota*1i - 1/1i // (untyped complex constant)
Applying the built-in functioncomplex
to untypedinteger, rune, or floating-point constants yieldsan untyped complex constant.
const ic = complex(0, c) // ic == 3.75i (untyped complex constant)const iΘ = complex(0, Θ) // iΘ == 1i (type complex128)
Constant expressions are always evaluated exactly; intermediate values and theconstants themselves may require precision significantly larger than supportedby any predeclared type in the language. The following are legal declarations:
const Huge = 1 << 100 // Huge == 1267650600228229401496703205376 (untyped integer constant)const Four int8 = Huge >> 98 // Four == 4 (type int8)
The divisor of a constant division or remainder operation must not be zero:
3.14 / 0.0 // illegal: division by zero
The values oftyped constants must always be accuratelyrepresentable by valuesof the constant type. The following constant expressions are illegal:
uint(-1) // -1 cannot be represented as a uintint(3.14) // 3.14 cannot be represented as an intint64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64Four * 300 // operand 300 cannot be represented as an int8 (type of Four)Four * 100 // product 400 cannot be represented as an int8 (type of Four)
The mask used by the unary bitwise complement operator^
matchesthe rule for non-constants: the mask is all 1s for unsigned constantsand -1 for signed and untyped constants.
^1 // untyped integer constant, equal to -2uint8(^1) // illegal: same as uint8(-2), -2 cannot be represented as a uint8^uint8(1) // typed uint8 constant, same as 0xFF ^ uint8(1) = uint8(0xFE)int8(^1) // same as int8(-2)^int8(1) // same as -1 ^ int8(1) = -2
Implementation restriction: A compiler may use rounding whilecomputing untyped floating-point or complex constant expressions; seethe implementation restriction in the sectiononconstants. This rounding may cause afloating-point constant expression to be invalid in an integercontext, even if it would be integral when calculated using infiniteprecision, and vice versa.
Order of evaluation
At package level,initialization dependenciesdetermine the evaluation order of individual initialization expressions invariable declarations.Otherwise, when evaluating theoperands of anexpression, assignment, orreturn statement,all function calls, method calls,receive operations,andbinary logical operationsare evaluated in lexical left-to-right order.
For example, in the (function-local) assignment
y[f()], ok = g(z || h(), i()+x[j()], <-c), k()
the function calls and communication happen in the orderf()
,h()
(ifz
evaluates to false),i()
,j()
,<-c
,g()
, andk()
.However, the order of those events compared to the evaluationand indexing ofx
and the evaluationofy
andz
is not specified,except as required lexically. For instance,g
cannot be called before its arguments are evaluated.
a := 1f := func() int { a++; return a }x := []int{a, f()} // x may be [1, 2] or [2, 2]: evaluation order between a and f() is not specifiedm := map[int]int{a: 1, a: 2} // m may be {2: 1} or {2: 2}: evaluation order between the two map assignments is not specifiedn := map[int]int{a: f()} // n may be {2: 3} or {3: 3}: evaluation order between the key and the value is not specified
At package level, initialization dependencies override the left-to-right rulefor individual initialization expressions, but not for operands within eachexpression:
var a, b, c = f() + v(), g(), sqr(u()) + v()func f() int { return c }func g() int { return a }func sqr(x int) int { return x*x }// functions u and v are independent of all other variables and functions
The function calls happen in the orderu()
,sqr()
,v()
,f()
,v()
, andg()
.
Floating-point operations within a single expression are evaluated according tothe associativity of the operators. Explicit parentheses affect the evaluationby overriding the default associativity.In the expressionx + (y + z)
the additiony + z
is performed before addingx
.
Statements
Statements control execution.
Statement =Declaration |LabeledStmt |SimpleStmt |GoStmt |ReturnStmt |BreakStmt |ContinueStmt |GotoStmt |FallthroughStmt |Block |IfStmt |SwitchStmt |SelectStmt |ForStmt |DeferStmt .SimpleStmt =EmptyStmt |ExpressionStmt |SendStmt |IncDecStmt |Assignment |ShortVarDecl .
Terminating statements
Aterminating statement interrupts the regular flow of control inablock. The following statements are terminating:
- A"return" or"goto" statement.
- A call to the built-in function
panic
. - Ablock in which the statement list ends in a terminating statement.
- An"if" statement in which:
- the "else" branch is present, and
- both branches are terminating statements.
- A"for" statement in which:
- there are no "break" statements referring to the "for" statement, and
- the loop condition is absent, and
- the "for" statement does not use a range clause.
- A"switch" statement in which:
- there are no "break" statements referring to the "switch" statement,
- there is a default case, and
- the statement lists in each case, including the default, end in a terminating statement, or a possibly labeled"fallthrough" statement.
- A"select" statement in which:
- there are no "break" statements referring to the "select" statement, and
- the statement lists in each case, including the default if present, end in a terminating statement.
- Alabeled statement labelinga terminating statement.
All other statements are not terminating.
Astatement list ends in a terminating statement if the listis not empty and its final non-empty statement is terminating.
Empty statements
The empty statement does nothing.
EmptyStmt = .
Labeled statements
A labeled statement may be the target of agoto
,break
orcontinue
statement.
LabeledStmt =Label ":"Statement .Label =identifier .
Error: log.Panic("error encountered")
Expression statements
With the exception of specific built-in functions,function and methodcalls andreceive operationscan appear in statement context. Such statements may be parenthesized.
ExpressionStmt =Expression .
The following built-in functions are not permitted in statement context:
append cap complex imag len make new realunsafe.Add unsafe.Alignof unsafe.Offsetof unsafe.Sizeof unsafe.Slice unsafe.SliceData unsafe.String unsafe.StringData
h(x+y)f.Close()<-ch(<-ch)len("foo") // illegal if len is the built-in function
Send statements
A send statement sends a value on a channel.The channel expression'score typemust be achannel,the channel direction must permit send operations,and the type of the value to be sent must beassignableto the channel's element type.
SendStmt =Channel "<-"Expression .Channel =Expression .
Both the channel and the value expression are evaluated before communicationbegins. Communication blocks until the send can proceed.A send on an unbuffered channel can proceed if a receiver is ready.A send on a buffered channel can proceed if there is room in the buffer.A send on a closed channel proceeds by causing arun-time panic.A send on anil
channel blocks forever.
ch <- 3 // send value 3 to channel ch
IncDec statements
The "++" and "--" statements increment or decrement their operandsby the untypedconstant1
.As with an assignment, the operand must beaddressableor a map index expression.
IncDecStmt =Expression ( "++" | "--" ) .
The followingassignment statements are semanticallyequivalent:
IncDec statement Assignmentx++ x += 1x-- x -= 1
Assignment statements
Anassignment replaces the current value stored in avariablewith a new value specified by anexpression.An assignment statement may assign a single value to a single variable, or multiple values to amatching number of variables.
Assignment =ExpressionListassign_opExpressionList .assign_op = [add_op |mul_op ] "=" .
Each left-hand side operand must beaddressable,a map index expression, or (for=
assignments only) theblank identifier.Operands may be parenthesized.
x = 1*p = f()a[i] = 23(k) = <-ch // same as: k = <-ch
Anassignment operationx
op=
y
whereop is a binaryarithmetic operatoris equivalent tox
=
x
op(y)
but evaluatesx
only once. Theop=
construct is a single token.In assignment operations, both the left- and right-hand expression listsmust contain exactly one single-valued expression, and the left-handexpression must not be the blank identifier.
a[i] <<= 2i &^= 1<<n
A tuple assignment assigns the individual elements of a multi-valuedoperation to a list of variables. There are two forms. In thefirst, the right hand operand is a single multi-valued expressionsuch as a function call, achannel ormap operation, or atype assertion.The number of operands on the lefthand side must match the number of values. For instance, iff
is a function returning two values,
x, y = f()
assigns the first value tox
and the second toy
.In the second form, the number of operands on the left must equal the numberof expressions on the right, each of which must be single-valued, and thenth expression on the right is assigned to thenthoperand on the left:
one, two, three = '一', '二', '三'
Theblank identifier provides a way toignore right-hand side values in an assignment:
_ = x // evaluate x but ignore itx, _ = f() // evaluate f() but ignore second result value
The assignment proceeds in two phases.First, the operands ofindex expressionsandpointer indirections(including implicit pointer indirections inselectors)on the left and the expressions on the right are allevaluated in the usual order.Second, the assignments are carried out in left-to-right order.
a, b = b, a // exchange a and bx := []int{1, 2, 3}i := 0i, x[i] = 1, 2 // set i = 1, x[0] = 2i = 0x[i], i = 2, 1 // set x[0] = 2, i = 1x[0], x[0] = 1, 2 // set x[0] = 1, then x[0] = 2 (so x[0] == 2 at end)x[1], x[3] = 4, 5 // set x[1] = 4, then panic setting x[3] = 5.type Point struct { x, y int }var p *Pointx[2], p.x = 6, 7 // set x[2] = 6, then panic setting p.x = 7i = 2x = []int{3, 5, 7}for i, x[i] = range x { // set i, x[2] = 0, x[0]break}// after this loop, i == 0 and x is []int{3, 5, 3}
In assignments, each value must beassignableto the type of the operand to which it is assigned, with the following special cases:
- Any typed value may be assigned to the blank identifier.
- If an untyped constantis assigned to a variable of interface type or the blank identifier,the constant is first implicitlyconverted to itsdefault type.
- If an untyped boolean value is assigned to a variable of interface type orthe blank identifier, it is first implicitly converted to type
bool
.
When a value is assigned to a variable, only the data that is stored in the variableis replaced. If the value contains areference,the assignment copies the reference but does not make a copy of the referenced data(such as the underlying array of a slice).
var s1 = []int{1, 2, 3}var s2 = s1 // s2 stores the slice descriptor of s1s1 = s1[:1] // s1's length is 1 but it still shares its underlying array with s2s2[0] = 42 // setting s2[0] changes s1[0] as wellfmt.Println(s1, s2) // prints [42] [42 2 3]var m1 = make(map[string]int)var m2 = m1 // m2 stores the map descriptor of m1m1["foo"] = 42 // setting m1["foo"] changes m2["foo"] as wellfmt.Println(m2["foo"]) // prints 42
If statements
"If" statements specify the conditional execution of two branchesaccording to the value of a boolean expression. If the expressionevaluates to true, the "if" branch is executed, otherwise, ifpresent, the "else" branch is executed.
IfStmt = "if" [SimpleStmt ";" ]ExpressionBlock [ "else" (IfStmt |Block ) ] .
if x > max {x = max}
The expression may be preceded by a simple statement, whichexecutes before the expression is evaluated.
if x := f(); x < y {return x} else if x > z {return z} else {return y}
Switch statements
"Switch" statements provide multi-way execution.An expression or type is compared to the "cases"inside the "switch" to determine which branchto execute.
SwitchStmt =ExprSwitchStmt |TypeSwitchStmt .
There are two forms: expression switches and type switches.In an expression switch, the cases contain expressions that are comparedagainst the value of the switch expression.In a type switch, the cases contain types that are compared against thetype of a specially annotated switch expression.The switch expression is evaluated exactly once in a switch statement.
Expression switches
In an expression switch,the switch expression is evaluated andthe case expressions, which need not be constants,are evaluated left-to-right and top-to-bottom; the first one that equals theswitch expressiontriggers execution of the statements of the associated case;the other cases are skipped.If no case matches and there is a "default" case,its statements are executed.There can be at most one default case and it may appear anywhere in the"switch" statement.A missing switch expression is equivalent to the boolean valuetrue
.
ExprSwitchStmt = "switch" [SimpleStmt ";" ] [Expression ] "{" {ExprCaseClause } "}" .ExprCaseClause =ExprSwitchCase ":"StatementList .ExprSwitchCase = "case"ExpressionList | "default" .
If the switch expression evaluates to an untyped constant, it is first implicitlyconverted to itsdefault type.The predeclared untyped valuenil
cannot be used as a switch expression.The switch expression type must becomparable.
If a case expression is untyped, it is first implicitlyconvertedto the type of the switch expression.For each (possibly converted) case expressionx
and the valuet
of the switch expression,x == t
must be a validcomparison.
In other words, the switch expression is treated as if it were used to declare andinitialize a temporary variablet
without explicit type; it is thatvalue oft
against which each case expressionx
is testedfor equality.
In a case or default clause, the last non-empty statementmay be a (possiblylabeled)"fallthrough" statement toindicate that control should flow from the end of this clause tothe first statement of the next clause.Otherwise control flows to the end of the "switch" statement.A "fallthrough" statement may appear as the last statement of allbut the last clause of an expression switch.
The switch expression may be preceded by a simple statement, whichexecutes before the expression is evaluated.
switch tag {default: s3()case 0, 1, 2, 3: s1()case 4, 5, 6, 7: s2()}switch x := f(); { // missing switch expression means "true"case x < 0: return -xdefault: return x}switch {case x < y: f1()case x < z: f2()case x == 4: f3()}
Implementation restriction: A compiler may disallow multiple caseexpressions evaluating to the same constant.For instance, the current compilers disallow duplicate integer,floating point, or string constants in case expressions.
Type switches
A type switch compares types rather than values. It is otherwise similarto an expression switch. It is marked by a special switch expression thathas the form of atype assertionusing the keywordtype
rather than an actual type:
switch x.(type) {// cases}
Cases then match actual typesT
against the dynamic type of theexpressionx
. As with type assertions,x
must be ofinterface type, but not atype parameter, and each non-interface typeT
listed in a case must implement the type ofx
.The types listed in the cases of a type switch must all bedifferent.
TypeSwitchStmt = "switch" [SimpleStmt ";" ]TypeSwitchGuard "{" {TypeCaseClause } "}" .TypeSwitchGuard = [identifier ":=" ]PrimaryExpr "." "(" "type" ")" .TypeCaseClause =TypeSwitchCase ":"StatementList .TypeSwitchCase = "case"TypeList | "default" .
The TypeSwitchGuard may include ashort variable declaration.When that form is used, the variable is declared at the end of theTypeSwitchCase in theimplicit block of each clause.In clauses with a case listing exactly one type, the variablehas that type; otherwise, the variable has the type of the expressionin the TypeSwitchGuard.
Instead of a type, a case may use the predeclared identifiernil
;that case is selected when the expression in the TypeSwitchGuardis anil
interface value.There may be at most onenil
case.
Given an expressionx
of typeinterface{}
,the following type switch:
switch i := x.(type) {case nil:printString("x is nil") // type of i is type of x (interface{})case int:printInt(i) // type of i is intcase float64:printFloat64(i) // type of i is float64case func(int) float64:printFunction(i) // type of i is func(int) float64case bool, string:printString("type is bool or string") // type of i is type of x (interface{})default:printString("don't know the type") // type of i is type of x (interface{})}
could be rewritten:
v := x // x is evaluated exactly onceif v == nil {i := v // type of i is type of x (interface{})printString("x is nil")} else if i, isInt := v.(int); isInt {printInt(i) // type of i is int} else if i, isFloat64 := v.(float64); isFloat64 {printFloat64(i) // type of i is float64} else if i, isFunc := v.(func(int) float64); isFunc {printFunction(i) // type of i is func(int) float64} else {_, isBool := v.(bool)_, isString := v.(string)if isBool || isString {i := v // type of i is type of x (interface{})printString("type is bool or string")} else {i := v // type of i is type of x (interface{})printString("don't know the type")}}
Atype parameter or ageneric typemay be used as a type in a case. If uponinstantiation that type turnsout to duplicate another entry in the switch, the first matching case is chosen.
func f[P any](x any) int {switch x.(type) {case P:return 0case string:return 1case []P:return 2case []byte:return 3default:return 4}}var v1 = f[string]("foo") // v1 == 0var v2 = f[byte]([]byte{}) // v2 == 2
The type switch guard may be preceded by a simple statement, whichexecutes before the guard is evaluated.
The "fallthrough" statement is not permitted in a type switch.
For statements
A "for" statement specifies repeated execution of a block. There are three forms:The iteration may be controlled by a single condition, a "for" clause, or a "range" clause.
ForStmt = "for" [Condition |ForClause |RangeClause ]Block .Condition =Expression .
For statements with single condition
In its simplest form, a "for" statement specifies the repeated execution ofa block as long as a boolean condition evaluates to true.The condition is evaluated before each iteration.If the condition is absent, it is equivalent to the boolean valuetrue
.
for a < b {a *= 2}
For statements withfor
clause
A "for" statement with a ForClause is also controlled by its condition, butadditionally it may specify aninitand apost statement, such as an assignment,an increment or decrement statement. The init statement may be ashort variable declaration, but the post statement must not.
ForClause = [InitStmt ] ";" [Condition ] ";" [PostStmt ] .InitStmt =SimpleStmt .PostStmt =SimpleStmt .
for i := 0; i < 10; i++ {f(i)}
If non-empty, the init statement is executed once before evaluating thecondition for the first iteration;the post statement is executed after each execution of the block (andonly if the block was executed).Any element of the ForClause may be empty but thesemicolons arerequired unless there is only a condition.If the condition is absent, it is equivalent to the boolean valuetrue
.
for cond { S() } is the same as for ; cond ; { S() }for { S() } is the same as for true { S() }
Each iteration has its own separate declared variable (or variables)[Go 1.22].The variable used by the first iteration is declared by the init statement.The variable used by each subsequent iteration is declared implicitly beforeexecuting the post statement and initialized to the value of the previousiteration's variable at that moment.
var prints []func()for i := 0; i< 5; i++ {prints = append(prints, func() { println(i) })i++}for _, p := range prints {p()}
prints
135
Prior to [Go 1.22], iterations share one set of variablesinstead of having their own separate variables.In that case, the example above prints
666
For statements withrange
clause
A "for" statement with a "range" clauseiterates through all entries of an array, slice, string or map, values received ona channel, integer values from zero to an upper limit [Go 1.22],or values passed to an iterator function's yield function [Go 1.23].For each entry it assignsiteration valuesto correspondingiteration variables if present and then executes the block.
RangeClause = [ExpressionList "=" |IdentifierList ":=" ] "range"Expression .
The expression on the right in the "range" clause is called therange expression,itscore type must bean array, pointer to an array, slice, string, map, channel permittingreceive operations, an integer, ora function with specific signature (see below).As with an assignment, if present the operands on the left must beaddressable or map index expressions; theydenote the iteration variables.If the range expression is a function, the maximum number of iteration variables depends onthe function signature.If the range expression is a channel or integer, at most one iteration variable is permitted;otherwise there may be up to two.If the last iteration variable is theblank identifier,the range clause is equivalent to the same clause without that identifier.
The range expressionx
is evaluated before beginning the loop,with one exception: if at most one iteration variable is present andx
orlen(x)
isconstant,the range expression is not evaluated.
Function calls on the left are evaluated once per iteration.For each iteration, iteration values are produced as followsif the respective iteration variables are present:
Range expression 1st value 2nd valuearray or slice a [n]E, *[n]E, or []E index i int a[i] Estring s string type index i int see below runemap m map[K]V key k K m[k] Vchannel c chan E, <-chan E element e Einteger value n integer type, or untyped int value i see belowfunction, 0 values f func(func() bool)function, 1 value f func(func(V) bool) value v Vfunction, 2 values f func(func(K, V) bool) key k K v V
- For an array, pointer to array, or slice value
a
, the index iterationvalues are produced in increasing order, starting at element index 0.If at most one iteration variable is present, the range loop producesiteration values from 0 up tolen(a)-1
and does not index into the arrayor slice itself. For anil
slice, the number of iterations is 0. - For a string value, the "range" clause iterates over the Unicode code pointsin the string starting at byte index 0. On successive iterations, the index value will be theindex of the first byte of successive UTF-8-encoded code points in the string,and the second value, of type
rune
, will be the value ofthe corresponding code point. If the iteration encounters an invalidUTF-8 sequence, the second value will be0xFFFD
,the Unicode replacement character, and the next iteration will advancea single byte in the string. - The iteration order over maps is not specifiedand is not guaranteed to be the same from one iteration to the next.If a map entry that has not yet been reached is removed during iteration,the corresponding iteration value will not be produced. If a map entry iscreated during iteration, that entry may be produced during the iteration ormay be skipped. The choice may vary for each entry created and from oneiteration to the next.If the map is
nil
, the number of iterations is 0. - For channels, the iteration values produced are the successive values sent onthe channel until the channel isclosed. If the channelis
nil
, the range expression blocks forever. - For an integer value
n
, wheren
is ofinteger typeor an untypedinteger constant, the iteration values 0 throughn-1
are produced in increasing order.Ifn
is of integer type, the iteration values have that same type.Otherwise, the type ofn
is determined as if it were assigned to theiteration variable.Specifically:if the iteration variable is preexisting, the type of the iteration values is the type of the iterationvariable, which must be of integer type.Otherwise, if the iteration variable is declared by the "range" clause or is absent,the type of the iteration values is thedefault type forn
.Ifn
<= 0, the loop does not run any iterations. - For a function
f
, the iteration proceeds by callingf
with a new, synthesizedyield
function as its argument.Ifyield
is called beforef
returns,the arguments toyield
become the iteration valuesfor executing the loop body once.After each successive loop iteration,yield
returns trueand may be called again to continue the loop.As long as the loop body does not terminate, the "range" clause will continueto generate iteration values this way for eachyield
call untilf
returns.If the loop body terminates (such as by abreak
statement),yield
returns false and must not be called again.
The iteration variables may be declared by the "range" clause using a form ofshort variable declaration(:=
).In this case theirscope is the block of the "for" statementand each iteration has its own new variables [Go 1.22](see also"for" statements with a ForClause).The variables have the types of their respective iteration values.
If the iteration variables are not explicitly declared by the "range" clause,they must be preexisting.In this case, the iteration values are assigned to the respective variablesas in anassignment statement.
var testdata *struct {a *[7]int}for i, _ := range testdata.a {// testdata.a is never evaluated; len(testdata.a) is constant// i ranges from 0 to 6f(i)}var a [10]stringfor i, s := range a {// type of i is int// type of s is string// s == a[i]g(i, s)}var key stringvar val interface{} // element type of m is assignable to valm := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}for key, val = range m {h(key, val)}// key == last map key encountered in iteration// val == map[key]var ch chan Work = producer()for w := range ch {doWork(w)}// empty a channelfor range ch {}// call f(0), f(1), ... f(9)for i := range 10 {// type of i is int (default type for untyped constant 10)f(i)}// invalid: 256 cannot be assigned to uint8var u uint8for u = range 256 {}// invalid: 1e3 is a floating-point constantfor range 1e3 {}// fibo generates the Fibonacci sequencefibo := func(yield func(x int) bool) {f0, f1 := 0, 1for yield(f0) {f0, f1 = f1, f0+f1}}// print the Fibonacci numbers below 1000:for x := range fibo {if x >= 1000 {break}fmt.Printf("%d ", x)}// output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987// iteration support for a recursive tree data structuretype Tree[K cmp.Ordered, V any] struct {left, right *Tree[K, V]key Kvalue V}func (t *Tree[K, V]) walk(yield func(key K, val V) bool) bool {return t == nil || t.left.walk(yield) && yield(t.key, t.value) && t.right.walk(yield)}func (t *Tree[K, V]) Walk(yield func(key K, val V) bool) {t.walk(yield)}// walk tree t in-ordervar t Tree[string, int]for k, v := range t.Walk {// process k, v}
Go statements
A "go" statement starts the execution of a function callas an independent concurrent thread of control, orgoroutine,within the same address space.
GoStmt = "go"Expression .
The expression must be a function or method call; it cannot be parenthesized.Calls of built-in functions are restricted as forexpression statements.
The function value and parameters areevaluated as usualin the calling goroutine, butunlike with a regular call, program execution does not waitfor the invoked function to complete.Instead, the function begins executing independentlyin a new goroutine.When the function terminates, its goroutine also terminates.If the function has any return values, they are discarded when thefunction completes.
go Server()go func(ch chan<- bool) { for { sleep(10); ch <- true }} (c)
Select statements
A "select" statement chooses which of a set of possiblesend orreceiveoperations will proceed.It looks similar to a"switch" statement but with thecases all referring to communication operations.
SelectStmt = "select" "{" {CommClause } "}" .CommClause =CommCase ":"StatementList .CommCase = "case" (SendStmt |RecvStmt ) | "default" .RecvStmt = [ExpressionList "=" |IdentifierList ":=" ]RecvExpr .RecvExpr =Expression .
A case with a RecvStmt may assign the result of a RecvExpr to one ortwo variables, which may be declared using ashort variable declaration.The RecvExpr must be a (possibly parenthesized) receive operation.There can be at most one default case and it may appear anywherein the list of cases.
Execution of a "select" statement proceeds in several steps:
- For all the cases in the statement, the channel operands of receive operationsand the channel and right-hand-side expressions of send statements areevaluated exactly once, in source order, upon entering the "select" statement.The result is a set of channels to receive from or send to,and the corresponding values to send.Any side effects in that evaluation will occur irrespective of which (if any)communication operation is selected to proceed.Expressions on the left-hand side of a RecvStmt with a short variable declarationor assignment are not yet evaluated.
- If one or more of the communications can proceed,a single one that can proceed is chosen via a uniform pseudo-random selection.Otherwise, if there is a default case, that case is chosen.If there is no default case, the "select" statement blocks untilat least one of the communications can proceed.
- Unless the selected case is the default case, the respective communicationoperation is executed.
- If the selected case is a RecvStmt with a short variable declaration oran assignment, the left-hand side expressions are evaluated and thereceived value (or values) are assigned.
- The statement list of the selected case is executed.
Since communication onnil
channels can never proceed,a select with onlynil
channels and no default case blocks forever.
var a []intvar c, c1, c2, c3, c4 chan intvar i1, i2 intselect {case i1 = <-c1:print("received ", i1, " from c1\n")case c2 <- i2:print("sent ", i2, " to c2\n")case i3, ok := (<-c3): // same as: i3, ok := <-c3if ok {print("received ", i3, " from c3\n")} else {print("c3 is closed\n")}case a[f()] = <-c4:// same as:// case t := <-c4//a[f()] = tdefault:print("no communication\n")}for { // send random sequence of bits to cselect {case c <- 0: // note: no statement, no fallthrough, no folding of casescase c <- 1:}}select {} // block forever
Return statements
A "return" statement in a functionF
terminates the executionofF
, and optionally provides one or more result values.Any functionsdeferred byF
are executed beforeF
returns to its caller.
ReturnStmt = "return" [ExpressionList ] .
In a function without a result type, a "return" statement must notspecify any result values.
func noResult() {return}
There are three ways to return values from a function with a resulttype:
- The return value or values may be explicitly listedin the "return" statement. Each expression must be single-valuedandassignableto the corresponding element of the function's result type.
func simpleF() int {return 2}func complexF1() (re float64, im float64) {return -7.0, -4.0}
- The expression list in the "return" statement may be a singlecall to a multi-valued function. The effect is as if each valuereturned from that function were assigned to a temporaryvariable with the type of the respective value, followed by a"return" statement listing these variables, at which point therules of the previous case apply.
func complexF2() (re float64, im float64) {return complexF1()}
- The expression list may be empty if the function's resulttype specifies names for itsresult parameters.The result parameters act as ordinary local variablesand the function may assign values to them as necessary.The "return" statement returns the values of these variables.
func complexF3() (re float64, im float64) {re = 7.0im = 4.0return}func (devnull) Write(p []byte) (n int, _ error) {n = len(p)return}
Regardless of how they are declared, all the result values are initialized tothezero values for their type upon entry to thefunction. A "return" statement that specifies results sets the result parameters beforeany deferred functions are executed.
Implementation restriction: A compiler may disallow an empty expression listin a "return" statement if a different entity (constant, type, or variable)with the same name as a result parameter is inscope at the place of the return.
func f(n int) (res int, err error) {if _, err := f(n-1); err != nil {return // invalid return statement: err is shadowed}return}
Break statements
A "break" statement terminates execution of the innermost"for","switch", or"select" statementwithin the same function.
BreakStmt = "break" [Label ] .
If there is a label, it must be that of an enclosing"for", "switch", or "select" statement,and that is the one whose execution terminates.
OuterLoop:for i = 0; i < n; i++ {for j = 0; j < m; j++ {switch a[i][j] {case nil:state = Errorbreak OuterLoopcase item:state = Foundbreak OuterLoop}}}
Continue statements
A "continue" statement begins the next iteration of theinnermost enclosing"for" loopby advancing control to the end of the loop block.The "for" loop must be within the same function.
ContinueStmt = "continue" [Label ] .
If there is a label, it must be that of an enclosing"for" statement, and that is the one whose executionadvances.
RowLoop:for y, row := range rows {for x, data := range row {if data == endOfRow {continue RowLoop}row[x] = data + bias(x, y)}}
Goto statements
A "goto" statement transfers control to the statement with the corresponding labelwithin the same function.
GotoStmt = "goto"Label .
goto Error
Executing the "goto" statement must not cause any variables to come intoscope that were not already in scope at the point of the goto.For instance, this example:
goto L // BADv := 3L:
is erroneous because the jump to labelL
skipsthe creation ofv
.
A "goto" statement outside ablock cannot jump to a label inside that block.For instance, this example:
if n%2 == 1 {goto L1}for n > 0 {f()n--L1:f()n--}
is erroneous because the labelL1
is insidethe "for" statement's block but thegoto
is not.
Fallthrough statements
A "fallthrough" statement transfers control to the first statement of thenext case clause in anexpression "switch" statement.It may be used only as the final non-empty statement in such a clause.
FallthroughStmt = "fallthrough" .
Defer statements
A "defer" statement invokes a function whose execution is deferredto the moment the surrounding function returns, either because thesurrounding function executed areturn statement,reached the end of itsfunction body,or because the corresponding goroutine ispanicking.
DeferStmt = "defer"Expression .
The expression must be a function or method call; it cannot be parenthesized.Calls of built-in functions are restricted as forexpression statements.
Each time a "defer" statementexecutes, the function value and parameters to the call areevaluated as usualand saved anew but the actual function is not invoked.Instead, deferred functions are invoked immediately beforethe surrounding function returns, in the reverse orderthey were deferred. That is, if the surrounding functionreturns through an explicitreturn statement,deferred functions are executedafter any result parameters are setby that return statement butbefore the function returns to its caller.If a deferred function value evaluatestonil
, executionpanicswhen the function is invoked, not when the "defer" statement is executed.
For instance, if the deferred function isafunction literal and the surroundingfunction hasnamed result parameters thatare in scope within the literal, the deferred function may access and modifythe result parameters before they are returned.If the deferred function has any return values, they are discarded whenthe function completes.(See also the section onhandling panics.)
lock(l)defer unlock(l) // unlocking happens before surrounding function returns// prints 3 2 1 0 before surrounding function returnsfor i := 0; i <= 3; i++ {defer fmt.Print(i)}// f returns 42func f() (result int) {defer func() {// result is accessed after it was set to 6 by the return statementresult *= 7}()return 6}
Built-in functions
Built-in functions arepredeclared.They are called like any other function but some of themaccept a type instead of an expression as the first argument.
The built-in functions do not have standard Go types,so they can only appear incall expressions;they cannot be used as function values.
Appending to and copying slices
The built-in functionsappend
andcopy
assist incommon slice operations.For both functions, the result is independent of whether the memory referencedby the arguments overlaps.
Thevariadic functionappend
appends zero or more valuesx
to a slices
and returns the resulting slice of the same type ass
.Thecore type ofs
must be a sliceof type[]E
.The valuesx
are passed to a parameter of type...E
and the respectiveparameterpassing rules apply.As a special case, if the core type ofs
is[]byte
,append
also accepts a second argument with core typebytestring
followed by...
.This form appends the bytes of the byte slice or string.
append(s S, x ...E) S // core type of S is []E
If the capacity ofs
is not large enough to fit the additionalvalues,append
allocates a new, sufficiently large underlyingarray that fits both the existing slice elements and the additional values.Otherwise,append
re-uses the underlying array.
s0 := []int{0, 0}s1 := append(s0, 2) // append a single element s1 is []int{0, 0, 2}s2 := append(s1, 3, 5, 7) // append multiple elements s2 is []int{0, 0, 2, 3, 5, 7}s3 := append(s2, s0...) // append a slice s3 is []int{0, 0, 2, 3, 5, 7, 0, 0}s4 := append(s3[3:6], s3[2:]...) // append overlapping slice s4 is []int{3, 5, 7, 2, 3, 5, 7, 0, 0}var t []interface{}t = append(t, 42, 3.1415, "foo") // t is []interface{}{42, 3.1415, "foo"}var b []byteb = append(b, "bar"...) // append string contents b is []byte{'b', 'a', 'r' }
The functioncopy
copies slice elements froma sourcesrc
to a destinationdst
and returns thenumber of elements copied.Thecore types of both arguments must be sliceswithidentical element type.The number of elements copied is the minimum oflen(src)
andlen(dst)
.As a special case, if the destination's core type is[]byte
,copy
also accepts a source argument with core typebytestring
.This form copies the bytes from the byte slice or string into the byte slice.
copy(dst, src []T) intcopy(dst []byte, src string) int
Examples:
var a = [...]int{0, 1, 2, 3, 4, 5, 6, 7}var s = make([]int, 6)var b = make([]byte, 5)n1 := copy(s, a[0:]) // n1 == 6, s is []int{0, 1, 2, 3, 4, 5}n2 := copy(s, s[2:]) // n2 == 4, s is []int{2, 3, 4, 5, 4, 5}n3 := copy(b, "Hello, World!") // n3 == 5, b is []byte("Hello")
Clear
The built-in functionclear
takes an argument ofmap,slice, ortype parameter type,and deletes or zeroes out all elements[Go 1.21].
Call Argument type Resultclear(m) map[K]T deletes all entries, resulting in an empty map (len(m) == 0)clear(s) []T sets all elements up to the length ofs
to the zero value of Tclear(t) type parameter see below
If the type of the argument toclear
is atype parameter,all types in its type set must be maps or slices, andclear
performs the operation corresponding to the actual type argument.
If the map or slice isnil
,clear
is a no-op.
Close
For an argumentch
with acore typethat is achannel, the built-in functionclose
records that no more values will be sent on the channel.It is an error ifch
is a receive-only channel.Sending to or closing a closed channel causes arun-time panic.Closing the nil channel also causes arun-time panic.After callingclose
, and after any previouslysent values have been received, receive operations will returnthe zero value for the channel's type without blocking.The multi-valuedreceive operationreturns a received value along with an indication of whether the channel is closed.
Manipulating complex numbers
Three functions assemble and disassemble complex numbers.The built-in functioncomplex
constructs a complexvalue from a floating-point real and imaginary part, whilereal
andimag
extract the real and imaginary parts of a complex value.
complex(realPart, imaginaryPart floatT) complexTreal(complexT) floatTimag(complexT) floatT
The type of the arguments and return value correspond.Forcomplex
, the two arguments must be of the samefloating-point type and the return type is thecomplex typewith the corresponding floating-point constituents:complex64
forfloat32
arguments, andcomplex128
forfloat64
arguments.If one of the arguments evaluates to an untyped constant, it is first implicitlyconverted to the type of the other argument.If both arguments evaluate to untyped constants, they must be non-complexnumbers or their imaginary parts must be zero, and the return value ofthe function is an untyped complex constant.
Forreal
andimag
, the argument must beof complex type, and the return type is the corresponding floating-pointtype:float32
for acomplex64
argument, andfloat64
for acomplex128
argument.If the argument evaluates to an untyped constant, it must be a number,and the return value of the function is an untyped floating-point constant.
Thereal
andimag
functions together form the inverse ofcomplex
, so for a valuez
of a complex typeZ
,z == Z(complex(real(z), imag(z)))
.
If the operands of these functions are all constants, the returnvalue is a constant.
var a = complex(2, -2) // complex128const b = complex(1.0, -1.4) // untyped complex constant 1 - 1.4ix := float32(math.Cos(math.Pi/2)) // float32var c64 = complex(5, -x) // complex64var s int = complex(1, 0) // untyped complex constant 1 + 0i can be converted to int_ = complex(1, 2<<s) // illegal: 2 assumes floating-point type, cannot shiftvar rl = real(c64) // float32var im = imag(a) // float64const c = imag(b) // untyped constant -1.4_ = imag(3 << s) // illegal: 3 assumes complex type, cannot shift
Arguments of type parameter type are not permitted.
Deletion of map elements
The built-in functiondelete
removes the element with keyk
from amapm
. Thevaluek
must beassignableto the key type ofm
.
delete(m, k) // remove element m[k] from map m
If the type ofm
is atype parameter,all types in that type set must be maps, and they must all have identical key types.
If the mapm
isnil
or the elementm[k]
does not exist,delete
is a no-op.
Length and capacity
The built-in functionslen
andcap
take argumentsof various types and return a result of typeint
.The implementation guarantees that the result always fits into anint
.
Call Argument type Resultlen(s) string type string length in bytes [n]T, *[n]T array length (== n) []T slice length map[K]T map length (number of defined keys) chan T number of elements queued in channel buffer type parameter see belowcap(s) [n]T, *[n]T array length (== n) []T slice capacity chan T channel buffer capacity type parameter see below
If the argument type is atype parameterP
,the calllen(e)
(orcap(e)
respectively) must be valid foreach type inP
's type set.The result is the length (or capacity, respectively) of the argument whose typecorresponds to the type argument with whichP
wasinstantiated.
The capacity of a slice is the number of elements for which there isspace allocated in the underlying array.At any time the following relationship holds:
0 <= len(s) <= cap(s)
The length of anil
slice, map or channel is 0.The capacity of anil
slice or channel is 0.
The expressionlen(s)
isconstant ifs
is a string constant. The expressionslen(s)
andcap(s)
are constants if the type ofs
is an arrayor pointer to an array and the expressions
does not containchannel receives or (non-constant)function calls; in this cases
is not evaluated.Otherwise, invocations oflen
andcap
are notconstant ands
is evaluated.
const (c1 = imag(2i) // imag(2i) = 2.0 is a constantc2 = len([10]float64{2}) // [10]float64{2} contains no function callsc3 = len([10]float64{c1}) // [10]float64{c1} contains no function callsc4 = len([10]float64{imag(2i)}) // imag(2i) is a constant and no function call is issuedc5 = len([10]float64{imag(z)}) // invalid: imag(z) is a (non-constant) function call)var z complex128
Making slices, maps and channels
The built-in functionmake
takes a typeT
,optionally followed by a type-specific list of expressions.Thecore type ofT
mustbe a slice, map or channel.It returns a value of typeT
(not*T
).The memory is initialized as described in the section oninitial values.
Call Core type Resultmake(T, n) slice slice of type T with length n and capacity nmake(T, n, m) slice slice of type T with length n and capacity mmake(T) map map of type Tmake(T, n) map map of type T with initial space for approximately n elementsmake(T) channel unbuffered channel of type Tmake(T, n) channel buffered channel of type T, buffer size n
Each of the size argumentsn
andm
must be ofinteger type,have atype set containing only integer types,or be an untypedconstant.A constant size argument must be non-negative andrepresentableby a value of typeint
; if it is an untyped constant it is given typeint
.If bothn
andm
are provided and are constant, thenn
must be no larger thanm
.For slices and channels, ifn
is negative or larger thanm
at run time,arun-time panic occurs.
s := make([]int, 10, 100) // slice with len(s) == 10, cap(s) == 100s := make([]int, 1e3) // slice with len(s) == cap(s) == 1000s := make([]int, 1<<63) // illegal: len(s) is not representable by a value of type ints := make([]int, 10, 0) // illegal: len(s) > cap(s)c := make(chan int, 10) // channel with a buffer size of 10m := make(map[string]int, 100) // map with initial space for approximately 100 elements
Callingmake
with a map type and size hintn
willcreate a map with initial space to holdn
map elements.The precise behavior is implementation-dependent.
Min and max
The built-in functionsmin
andmax
compute thesmallest—or largest, respectively—value of a fixed number ofarguments ofordered types.There must be at least one argument[Go 1.21].
The same type rules as foroperators apply:forordered argumentsx
andy
,min(x, y)
is valid ifx + y
is valid,and the type ofmin(x, y)
is the type ofx + y
(and similarly formax
).If all arguments are constant, the result is constant.
var x, y intm := min(x) // m == xm := min(x, y) // m is the smaller of x and ym := max(x, y, 10) // m is the larger of x and y but at least 10c := max(1, 2.0, 10) // c == 10.0 (floating-point kind)f := max(0, float32(x)) // type of f is float32var s []string_ = min(s...) // invalid: slice arguments are not permittedt := max("", "foo", "bar") // t == "foo" (string kind)
For numeric arguments, assuming all NaNs are equal,min
andmax
arecommutative and associative:
min(x, y) == min(y, x)min(x, y, z) == min(min(x, y), z) == min(x, min(y, z))
For floating-point arguments negative zero, NaN, and infinity the following rules apply:
x y min(x, y) max(x, y) -0.0 0.0 -0.0 0.0 // negative zero is smaller than (non-negative) zero -Inf y -Inf y // negative infinity is smaller than any other number +Inf y y +Inf // positive infinity is larger than any other number NaN y NaN NaN // if any argument is a NaN, the result is a NaN
For string arguments the result formin
is the first argumentwith the smallest (or formax
, largest) value,compared lexically byte-wise:
min(x, y) == if x<= y then x else ymin(x, y, z) == min(min(x, y), z)
Allocation
The built-in functionnew
takes a typeT
,allocates storage for avariable of that typeat run time, and returns a value of type*T
pointing to it.The variable is initialized as described in the section oninitial values.
new(T)
For instance
type S struct { a int; b float64 }new(S)
allocates storage for a variable of typeS
,initializes it (a=0
,b=0.0
),and returns a value of type*S
containing the addressof the location.
Handling panics
Two built-in functions,panic
andrecover
,assist in reporting and handlingrun-time panicsand program-defined error conditions.
func panic(interface{})func recover() interface{}
While executing a functionF
,an explicit call topanic
or arun-time panicterminates the execution ofF
.Any functionsdeferred byF
are then executed as usual.Next, any deferred functions run byF
's caller are run,and so on up to any deferred by the top-level function in the executing goroutine.At that point, the program is terminated and the errorcondition is reported, including the value of the argument topanic
.This termination sequence is calledpanicking.
panic(42)panic("unreachable")panic(Error("cannot parse"))
Therecover
function allows a program to manage behaviorof a panicking goroutine.Suppose a functionG
defers a functionD
that callsrecover
and a panic occurs in a function on the same goroutine in whichG
is executing.When the running of deferred functions reachesD
,the return value ofD
's call torecover
will be the value passed to the call ofpanic
.IfD
returns normally, without starting a newpanic
, the panicking sequence stops. In that case,the state of functions called betweenG
and the call topanic
is discarded, and normal execution resumes.Any functions deferred byG
beforeD
are then run andG
'sexecution terminates by returning to its caller.
The return value ofrecover
isnil
when thegoroutine is not panicking orrecover
was not called directly by a deferred function.Conversely, if a goroutine is panicking andrecover
was called directly by a deferred function,the return value ofrecover
is guaranteed not to benil
.To ensure this, callingpanic
with anil
interface value (or an untypednil
)causes arun-time panic.
Theprotect
function in the example below invokesthe function argumentg
and protects callers fromrun-time panics raised byg
.
func protect(g func()) {defer func() {log.Println("done") // Println executes normally even if there is a panicif x := recover(); x != nil {log.Printf("run time panic: %v", x)}}()log.Println("start")g()}
Bootstrapping
Current implementations provide several built-in functions useful duringbootstrapping. These functions are documented for completeness but are notguaranteed to stay in the language. They do not return a result.
Function Behaviorprint prints all arguments; formatting of arguments is implementation-specificprintln like print but prints spaces between arguments and a newline at the end
Implementation restriction:print
andprintln
need notaccept arbitrary argument types, but printing of boolean, numeric, and stringtypes must be supported.
Packages
Go programs are constructed by linking togetherpackages.A package in turn is constructed from one or more source filesthat together declare constants, types, variables and functionsbelonging to the package and which are accessible in all filesof the same package. Those elements may beexported and used in another package.
Source file organization
Each source file consists of a package clause defining the packageto which it belongs, followed by a possibly empty set of importdeclarations that declare packages whose contents it wishes to use,followed by a possibly empty set of declarations of functions,types, variables, and constants.
SourceFile =PackageClause ";" {ImportDecl ";" } {TopLevelDecl ";" } .
Package clause
A package clause begins each source file and defines the packageto which the file belongs.
PackageClause = "package"PackageName .PackageName =identifier .
The PackageName must not be theblank identifier.
package math
A set of files sharing the same PackageName form the implementation of a package.An implementation may require that all source files for a package inhabit the same directory.
Import declarations
An import declaration states that the source file containing the declarationdepends on functionality of theimported package(§Program initialization and execution)and enables access toexported identifiersof that package.The import names an identifier (PackageName) to be used for access and an ImportPaththat specifies the package to be imported.
ImportDecl = "import" (ImportSpec | "(" {ImportSpec ";" } ")" ) .ImportSpec = [ "." |PackageName ]ImportPath .ImportPath =string_lit .
The PackageName is used inqualified identifiersto access exported identifiers of the package within the importing source file.It is declared in thefile block.If the PackageName is omitted, it defaults to the identifier specified in thepackage clause of the imported package.If an explicit period (.
) appears instead of a name, all thepackage's exported identifiers declared in that package'spackage block will be declared in the importing sourcefile's file block and must be accessed without a qualifier.
The interpretation of the ImportPath is implementation-dependent butit is typically a substring of the full file name of the compiledpackage and may be relative to a repository of installed packages.
Implementation restriction: A compiler may restrict ImportPaths tonon-empty strings using only characters belonging toUnicode'sL, M, N, P, and S general categories (the Graphic characters withoutspaces) and may also exclude the characters!"#$%&'()*,:;<=>?[\]^`{|}
and the Unicode replacement character U+FFFD.
Consider a compiled a package containing the package clausepackage math
, which exports functionSin
, andinstalled the compiled package in the file identified by"lib/math"
.This table illustrates howSin
is accessed in filesthat import the package after thevarious types of import declaration.
Import declaration Local name of Sinimport "lib/math" math.Sinimport m "lib/math" m.Sinimport . "lib/math" Sin
An import declaration declares a dependency relation betweenthe importing and imported package.It is illegal for a package to import itself, directly or indirectly,or to directly import a package withoutreferring to any of its exported identifiers. To import a package solely forits side-effects (initialization), use theblankidentifier as explicit package name:
import _ "lib/math"
An example package
Here is a complete Go package that implements a concurrent prime sieve.
package mainimport "fmt"// Send the sequence 2, 3, 4, … to channel 'ch'.func generate(ch chan<- int) {for i := 2; ; i++ {ch <- i // Send 'i' to channel 'ch'.}}// Copy the values from channel 'src' to channel 'dst',// removing those divisible by 'prime'.func filter(src <-chan int, dst chan<- int, prime int) {for i := range src { // Loop over values received from 'src'.if i%prime != 0 {dst <- i // Send 'i' to channel 'dst'.}}}// The prime sieve: Daisy-chain filter processes together.func sieve() {ch := make(chan int) // Create a new channel.go generate(ch) // Start generate() as a subprocess.for {prime := <-chfmt.Print(prime, "\n")ch1 := make(chan int)go filter(ch, ch1, prime)ch = ch1}}func main() {sieve()}
Program initialization and execution
The zero value
When storage is allocated for avariable,either through a declaration or a call ofnew
, or whena new value is created, either through a composite literal or a callofmake
,and no explicit initialization is provided, the variable or value isgiven a default value. Each element of such a variable or value isset to thezero value for its type:false
for booleans,0
for numeric types,""
for strings, andnil
for pointers, functions, interfaces, slices, channels, and maps.This initialization is done recursively, so for instance each element of anarray of structs will have its fields zeroed if no value is specified.
These two simple declarations are equivalent:
var i intvar i int = 0
After
type T struct { i int; f float64; next *T }t := new(T)
the following holds:
t.i == 0t.f == 0.0t.next == nil
The same would also be true after
var t T
Package initialization
Within a package, package-level variable initialization proceeds stepwise,with each step selecting the variable earliest indeclaration orderwhich has no dependencies on uninitialized variables.
More precisely, a package-level variable is consideredready forinitialization if it is not yet initialized and either hasnoinitialization expression orits initialization expression has nodependencies on uninitialized variables.Initialization proceeds by repeatedly initializing the next package-levelvariable that is earliest in declaration order and ready for initialization,until there are no variables ready for initialization.
If any variables are still uninitialized when thisprocess ends, those variables are part of one or more initialization cycles,and the program is not valid.
Multiple variables on the left-hand side of a variable declaration initializedby single (multi-valued) expression on the right-hand side are initializedtogether: If any of the variables on the left-hand side is initialized, allthose variables are initialized in the same step.
var x = avar a, b = f() // a and b are initialized together, before x is initialized
For the purpose of package initialization,blankvariables are treated like any other variables in declarations.
The declaration order of variables declared in multiple files is determinedby the order in which the files are presented to the compiler: Variablesdeclared in the first file are declared before any of the variables declaredin the second file, and so on.To ensure reproducible initialization behavior, build systems are encouragedto present multiple files belonging to the same package in lexical file nameorder to a compiler.
Dependency analysis does not rely on the actual values of thevariables, only on lexicalreferences to them in the source,analyzed transitively. For instance, if a variablex
'sinitialization expression refers to a function whose body refers tovariabley
thenx
depends ony
.Specifically:
- A reference to a variable or function is an identifier denoting thatvariable or function.
- A reference to a method
m
is amethod value ormethod expression of the formt.m
, where the (static) type oft
isnot an interface type, and the methodm
is in themethod set oft
.It is immaterial whether the resulting function valuet.m
is invoked. - A variable, function, or method
x
depends on a variabley
ifx
's initialization expression or body(for functions and methods) contains a reference toy
or to a function or method that depends ony
.
For example, given the declarations
var (a = c + b // == 9b = f() // == 4c = f() // == 5d = 3 // == 5 after initialization has finished)func f() int {d++return d}
the initialization order isd
,b
,c
,a
.Note that the order of subexpressions in initialization expressions is irrelevant:a = c + b
anda = b + c
result in the same initializationorder in this example.
Dependency analysis is performed per package; only references referringto variables, functions, and (non-interface) methods declared in the currentpackage are considered. If other, hidden, data dependencies exists betweenvariables, the initialization order between those variables is unspecified.
For instance, given the declarations
var x = I(T{}).ab() // x has an undetected, hidden dependency on a and bvar _ = sideEffect() // unrelated to x, a, or bvar a = bvar b = 42type I interface { ab() []int }type T struct{}func (T) ab() []int { return []int{a, b} }
the variablea
will be initialized afterb
butwhetherx
is initialized beforeb
, betweenb
anda
, or aftera
, andthus also the moment at whichsideEffect()
is called (beforeor afterx
is initialized) is not specified.
Variables may also be initialized using functions namedinit
declared in the package block, with no arguments and no result parameters.
func init() { … }
Multiple such functions may be defined per package, even within a singlesource file. In the package block, theinit
identifier canbe used only to declareinit
functions, yet the identifieritself is notdeclared. Thusinit
functions cannot be referred to from anywherein a program.
The entire package is initialized by assigning initial valuesto all its package-level variables followed by callingallinit
functions in the order they appearin the source, possibly in multiple files, as presentedto the compiler.
Program initialization
The packages of a complete program are initialized stepwise, one package at a time.If a package has imports, the imported packages are initializedbefore initializing the package itself. If multiple packages importa package, the imported package will be initialized only once.The importing of packages, by construction, guarantees that therecan be no cyclic initialization dependencies.More precisely:
Given the list of all packages, sorted by import path, in each step the firstuninitialized package in the list for which all imported packages (if any) arealready initialized isinitialized.This step is repeated until all packages are initialized.
Package initialization—variable initialization and the invocation ofinit
functions—happens in a single goroutine,sequentially, one package at a time.Aninit
function may launch other goroutines, which can runconcurrently with the initialization code. However, initializationalways sequencestheinit
functions: it will not invoke the next oneuntil the previous one has returned.
Program execution
A complete program is created by linking a single, unimported packagecalled themain package with all the packages it imports, transitively.The main package musthave package namemain
anddeclare a functionmain
that takes noarguments and returns no value.
func main() { … }
Program execution begins byinitializing the programand then invoking the functionmain
in packagemain
.When that function invocation returns, the program exits.It does not wait for other (non-main
) goroutines to complete.
Errors
The predeclared typeerror
is defined as
type error interface {Error() string}
It is the conventional interface for representing an error condition,with the nil value representing no error.For instance, a function to read data from a file might be defined:
func Read(f *File, b []byte) (n int, err error)
Run-time panics
Execution errors such as attempting to index an array outof bounds trigger arun-time panic equivalent to a call ofthe built-in functionpanic
with a value of the implementation-defined interface typeruntime.Error
.That type satisfies the predeclared interface typeerror
.The exact error values thatrepresent distinct run-time error conditions are unspecified.
package runtimetype Error interface {error// and perhaps other methods}
System considerations
Packageunsafe
The built-in packageunsafe
, known to the compilerand accessible through theimport path"unsafe"
,provides facilities for low-level programming including operationsthat violate the type system. A package usingunsafe
must be vetted manually for type safety and may not be portable.The package provides the following interface:
package unsafetype ArbitraryType int // shorthand for an arbitrary Go type; it is not a real typetype Pointer *ArbitraryTypefunc Alignof(variable ArbitraryType) uintptrfunc Offsetof(selector ArbitraryType) uintptrfunc Sizeof(variable ArbitraryType) uintptrtype IntegerType int // shorthand for an integer type; it is not a real typefunc Add(ptr Pointer, len IntegerType) Pointerfunc Slice(ptr *ArbitraryType, len IntegerType) []ArbitraryTypefunc SliceData(slice []ArbitraryType) *ArbitraryTypefunc String(ptr *byte, len IntegerType) stringfunc StringData(str string) *byte
APointer
is apointer type but aPointer
value may not bedereferenced.Any pointer or value ofcore typeuintptr
can beconverted to a type of core typePointer
and vice versa.The effect of converting betweenPointer
anduintptr
is implementation-defined.
var f float64bits = *(*uint64)(unsafe.Pointer(&f))type ptr unsafe.Pointerbits = *(*uint64)(ptr(&f))func f[P ~*B, B any](p P) uintptr {return uintptr(unsafe.Pointer(p))}var p ptr = nil
The functionsAlignof
andSizeof
take an expressionx
of any type and return the alignment or size, respectively, of a hypothetical variablev
as ifv
were declared viavar v = x
.
The functionOffsetof
takes a (possibly parenthesized)selectors.f
, denoting a fieldf
of the struct denoted bys
or*s
, and returns the field offset in bytes relative to the struct's address.Iff
is anembedded field, it must be reachablewithout pointer indirections through fields of the struct.For a structs
with fieldf
:
uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&s.f))
Computer architectures may require memory addresses to bealigned;that is, for addresses of a variable to be a multiple of a factor,the variable's type'salignment. The functionAlignof
takes an expression denoting a variable of any type and returns thealignment of the (type of the) variable in bytes. For a variablex
:
uintptr(unsafe.Pointer(&x)) % unsafe.Alignof(x) == 0
A (variable of) typeT
hasvariable size ifT
is atype parameter, or if it is anarray or struct type containing elementsor fields of variable size. Otherwise the size isconstant.Calls toAlignof
,Offsetof
, andSizeof
are compile-timeconstant expressions oftypeuintptr
if their arguments (or the structs
inthe selector expressions.f
forOffsetof
) are typesof constant size.
The functionAdd
addslen
toptr
and returns the updated pointerunsafe.Pointer(uintptr(ptr) + uintptr(len))
[Go 1.17].Thelen
argument must be ofinteger type or an untypedconstant.A constantlen
argument must berepresentable by a value of typeint
;if it is an untyped constant it is given typeint
.The rules forvalid uses ofPointer
still apply.
The functionSlice
returns a slice whose underlying array starts atptr
and whose length and capacity arelen
.Slice(ptr, len)
is equivalent to
(*[len]ArbitraryType)(unsafe.Pointer(ptr))[:]
except that, as a special case, ifptr
isnil
andlen
is zero,Slice
returnsnil
[Go 1.17].
Thelen
argument must be ofinteger type or an untypedconstant.A constantlen
argument must be non-negative andrepresentable by a value of typeint
;if it is an untyped constant it is given typeint
.At run time, iflen
is negative,or ifptr
isnil
andlen
is not zero,arun-time panic occurs[Go 1.17].
The functionSliceData
returns a pointer to the underlying array of theslice
argument.If the slice's capacitycap(slice)
is not zero, that pointer is&slice[:1][0]
.Ifslice
isnil
, the result isnil
.Otherwise it is a non-nil
pointer to an unspecified memory address[Go 1.20].
The functionString
returns astring
value whose underlying bytes start atptr
and whose length islen
.The same requirements apply to theptr
andlen
argument as in the functionSlice
. Iflen
is zero, the result is the empty string""
.Since Go strings are immutable, the bytes passed toString
must not be modified afterwards.[Go 1.20]
The functionStringData
returns a pointer to the underlying bytes of thestr
argument.For an empty string the return value is unspecified, and may benil
.Since Go strings are immutable, the bytes returned byStringData
must not be modified[Go 1.20].
Size and alignment guarantees
For thenumeric types, the following sizes are guaranteed:
type size in bytesbyte, uint8, int8 1uint16, int16 2uint32, int32, float32 4uint64, int64, float64, complex64 8complex128 16
The following minimal alignment properties are guaranteed:
- For a variable
x
of any type:unsafe.Alignof(x)
is at least 1. - For a variable
x
of struct type:unsafe.Alignof(x)
is the largest of all the valuesunsafe.Alignof(x.f)
for each fieldf
ofx
, but at least 1. - For a variable
x
of array type:unsafe.Alignof(x)
is the same asthe alignment of a variable of the array's element type.
A 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.
Appendix
Language versions
TheGo 1 compatibility guarantee ensures thatprograms written to the Go 1 specification will continue to compile and runcorrectly, unchanged, over the lifetime of that specification.More generally, as adjustments are made and features added to the language,the compatibility guarantee ensures that a Go program that works with aspecific Go language version will continue to work with any subsequent version.
For instance, the ability to use the prefix0b
for binaryinteger literals was introduced with Go 1.13, indicatedby [Go 1.13] in the section oninteger literals.Source code containing an integer literal such as0b1011
will be rejected if the implied or required language version used bythe compiler is older than Go 1.13.
The following table describes the minimum language version required forfeatures introduced after Go 1.
Go 1.9
- Analias declaration may be used to declare an alias name for a type.
Go 1.13
- Integer literals may use the prefixes
0b
,0B
,0o
,and0O
for binary, and octal literals, respectively. - Hexadecimalfloating-point literals may be written using the prefixes
0x
and0X
. - Theimaginary suffix
i
may be used with any (binary, decimal, hexadecimal)integer or floating-point literal, not just decimal literals. - The digits of any number literal may beseparated (grouped)using underscores
_
. - The shift count in ashift operation may be a signed integer type.
Go 1.14
- Emdedding a method more than once through differentembedded interfacesis not an error.
Go 1.17
- A slice may beconverted to an array pointer if the slice and array elementtypes match, and the array is not longer than the slice.
- The built-inpackage
unsafe
includes the new functionsAdd
andSlice
.
Go 1.18
The 1.18 release adds polymorphic functions and types ("generics") to the language.Specifically:
- The set ofoperators and punctuation includes the new token
~
. - Function and type declarations may declaretype parameters.
- Interface types mayembed arbitrary types (not just type names of interfaces)as well as union and
~T
type elements. - The set ofpredeclared types includes the new types
any
andcomparable
.
Go 1.20
- A slice may beconverted to an array if the slice and array elementtypes match and the array is not longer than the slice.
- The built-inpackage
unsafe
includes the new functionsSliceData
,String
, andStringData
. - Comparable types (such as ordinary interfaces) may satisfy
comparable
constraints, even if the type arguments are not strictly comparable.
Go 1.21
- The set ofpredeclared functions includes the new functions
min
,max
, andclear
. - Type inference uses the types of interface methods for inference.It also infers type arguments for generic functions assigned to variables orpassed as arguments to other (possibly generic) functions.
Go 1.22
- In a"for" statement, each iteration has its own set of iterationvariables rather than sharing the same variables in each iteration.
- A "for" statement with"range" clause may iterate overinteger values from zero to an upper limit.
Go 1.23
- A "for" statement with"range" clause accepts an iteratorfunction as range expression.
Go 1.24
- Analias declaration may declaretype parameters.
Type unification rules
The type unification rules describe if and how two types unify.The precise details are relevant for Go implementations,affect the specifics of error messages (such as whethera compiler reports a type inference or other error),and may explain why type inference fails in unusual code situations.But by and large these rules can be ignored when writing Go code:type inference is designed to mostly "work as expected",and the unification rules are fine-tuned accordingly.
Type unification is controlled by amatching mode, which maybeexact orloose.As unification recursively descends a composite type structure,the matching mode used for elements of the type, theelement matching mode,remains the same as the matching mode except when two types are unified forassignability (≡A
):in this case, the matching mode isloose at the top level butthen changes toexact for element types, reflecting the factthat types don't have to be identical to be assignable.
Two types that are not bound type parameters unify exactly if any offollowing conditions is true:
- Both types areidentical.
- Both types have identical structure and their element typesunify exactly.
- Exactly one type is anunboundtype parameter with acore type,and that core type unifies with the other type per theunification rules for
≡A
(loose unification at the top level and exact unificationfor element types).
If both types are bound type parameters, they unify per the givenmatching modes if:
- Both type parameters are identical.
- At most one of the type parameters has a known type argument.In this case, the type parameters arejoined:they both stand for the same type argument.If neither type parameter has a known type argument yet,a future type argument inferred for one the type parametersis simultaneously inferred for both of them.
- Both type parameters have a known type argumentand the type arguments unify per the given matching modes.
A single bound type parameterP
and another typeT
unifyper the given matching modes if:
P
doesn't have a known type argument.In this case,T
is inferred as the type argument forP
.P
does have a known type argumentA
,A
andT
unify per the given matching modes,and one of the following conditions is true:- Both
A
andT
are interface types:In this case, if bothA
andT
arealsodefined types,they must beidentical.Otherwise, if neither of them is a defined type, they musthave the same number of methods(unification ofA
andT
alreadyestablished that the methods match). - Neither
A
norT
are interface types:In this case, ifT
is a defined type,T
replacesA
as the inferred type argument forP
.
- Both
Finally, two types that are not bound type parameters unify loosely(and per the element matching mode) if:
- Both types unify exactly.
- One type is adefined type,the other type is a type literal, but not an interface,and their underlying types unify per the element matching mode.
- Both types are interfaces (but not type parameters) withidenticaltype terms,both or neither embed the predeclared typecomparable,corresponding method types unify exactly,and the method set of one of the interfaces is a subset ofthe method set of the other interface.
- Only one type is an interface (but not a type parameter),corresponding methods of the two types unify per the element matching mode,and the method set of the interface is a subset ofthe method set of the other type.
- Both types have the same structure and their element typesunify per the element matching mode.