08. Type System
Primitive types
Boolean
Numeric
String
Because of this, when adding or removing something from a value of one of these types, a new value should be created. Based on this, when passing values of these types to functions and methods, a copy of the value should be passed.
Structured types
Составные типы образуют более сложные типы путем составления более простых. Для structured типов Go сразу выделяет память, даже если никакие значения не указаны. Поэтому для них всегда существует "нулевое" значение. Structured типы передаются по значению и всегда копируются. Их можно сравнить друг с другом. Не могут иметь nil
значений.
arrays
structs
Reference types
Ссылочные типы в Go:
pointers
slice,
map,
channel,
function types,
interface types
Общим для ссылочных типов является то, что все они обращаются к своим значениям косвенно, так что результат действия операции наблюдается на всех ссылках на это значение.
When you declare a variable from one of these types, the value that’s created is called a header value.
Ссылочные типы могут иметь
nil
значение.All the different header values from the different reference types contain a pointer to an underlying data structure.
Each reference type also contains a set of unique fields that are used to manage the underlying data structure.
You never share reference type values because the header value is designed to be copied.
Default type value
Number =
0
Boolean =
false
String =
""
(empty string)Reference types
nil
Comparable types
Comparable types are
boolean,
numeric,
string,
pointer,
channel,
interface types,
structs or arrays that contain only those types
Go doesn't support comparisons (with the ==
and !=
operators) between values of the following types:
slice types
map types
function types
any struct type with a field whose type is incomparable and any array type which element type is incomparable.
Compilers forbid comparing two values of incomparable types.
Slices, maps, and functions cannot be compared using ==
, only against nil
.
Types which values can be used as arguments of built-in len
function (and cap
, close
, delete
, make
functions)
nil
value
nil
valueIn Go, nil
can represent zero values of the following kinds of types:
pointer types (including type-unsafe ones).
map types.
slice types.
function types.
channel types.
interface types.
Type conversions
Unlike in C, in Go assignment between items of different type requires an explicit conversion.
The expression T(v)
converts the value v
to the type T
.
Преобразования из одного типа в другой разрешено, если они оба имеют один и тот же базовый тип, или если оба являются неименованными указателями на переменные одного и того же базового типа. Такие преобразования изменяют тип, но не представление самого значения.
Conversions of user defined types
Операторы сравнения могут использоваться для сравнения значения именованного типа с другим значением того же типа, или со значением неименованного типа с тем же базовым типом. Но два значения разных именованных типов сравнивать непосредственно нельзя.
Invalid conversions
Conversion can be done only if Go compiler is able to check its correctness. Scenarios where it isn’t verifiable at compile-time are as follows:
interface type → concrete type
interface type → interface type
Type expression
Объявление type
определяет новый именованный тип, который имеет тот же базовый тип, что и существующий. Именованный тип позволяет отличать различные, и возможно несовместимые, использования базового типа, с тем, что бы они не оказались непреднамеренно смешанными.
Even though int64
is acting at the base type for Duration
, it doesn’t mean Go considered them to be the same. Duration
and int64
are two distinct and different types, and Duration
is still its own unique type. Values of two different types can’t be assigned to each other, even if they’re compatible. The compiler doesn’t implicitly convert values of different types.
Type Declaration
a new defined type and its respective source type in type definitions are two distinct types.
two types defined in two type definitions are always two distinct types.
the new defined type and the source type will share the same underlying type (see below for the definition of underlying types), and their values can be converted to each other.
types can be defined within function bodies.
According to Go assignability, a value of type Name1
is assignable to map[string]string
(because the latter is not a named type) but a value of type Name1
is not assignable to Name2
(because both are named types, and the names differ).
Type Aliasing
Type alias declaration, which introduces an alternate name for an existing type.
A type name (or literal) and its aliases all denote an identical type. By the above declarations,
Name
is an alias ofstring
, so both denote the same type.
In this example, because Alias is an alternate spelling for map[string]string
, a value of type Name1
is assignable to Alias
(because Alias is the same as map[string]string
, which is not a named type).
Type switch
switch
A type switch
is a construct that permits several type assertions in series.
A type
switch
is like a regularswitch
statement, but the cases in a typeswitch
specify types (not values), and those values are compared against the type of the value held by the given interface value.x.(type)
можно использовать только в type switch.Cannot type
switch
on non-interface valueThe declaration in a type
switch
has the same syntax as a type assertioni.(T)
, but the specific typeT
is replaced with the keywordtype
.
Example:
Implementation
This
switch
statement tests whether the interface valuei
holds a value of typeT
orS
.In each of the
T
andS
cases, the variablev
will be of typeT
orS
respectively and hold the value held byi
.In the
default
case (where there is no match), the variablev
is of the same interface type and value asi
.
Optional simple statement
Guard can be preceded with simple statement like another short variable declaration:
Type assertions
A type assertion provides access to an interface value's underlying concrete value.
This statement asserts that the interface value i
holds the concrete type T
and assigns the underlying T
value to the variable t
. If i
does not hold a T
, the statement will trigger a panic. i
must always evaluate to interface type otherwise it’s a compile-time error.
If
T
fromi.(T)
is an interface type then such assertion checks if dynamic type ofi
implements interfaceT
.If
T
fromi.(T)
is not an interface type then such assertion checks if dynamic type ofv
is identical toT
.
T
is either a type identifier or type literal like:
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.
If i
holds a T
, then t
will be the underlying value and ok
will be true
. If not, ok
will be false
and t
will be the zero value of type T
, and no panic occurs.
Missing the optional result value in a type assertion will make current goroutine panic if the type assertion fails.
Identical types
Each type in Go has something which is called an underlying type.
Universe block contains some predeclared identifiers binding to types like boolean, string or numeric.
For each predeclared
type T
its underlaying type isT
(no trap here).
Named types are new ones specified using
type
name, optionally prefixed with package name. Package name is used to access name exported from other package (preceded with proper import statement).Unnamed types use type literals while referring to themselves like f.ex.:
Two types in Go are identical or different:
Two named types are identical if both are created through the same
type
declaration.
named and unnamed types are different (no exceptions),
unnamed types are identical if corresponding type literals are the same.
Assignability
T
is an interface type and x
implements T
:
It doesn’t matter how these types are structured:
Methods sets don’t have to be equal:
Last updated
Was this helpful?