Go Concepts - The Type System: Difference between revisions
Line 53: | Line 53: | ||
</pre> | </pre> | ||
We cannot do pointer arithmetic. Assuming <tt>ptr</tt> is a <tt>*int</tt>, we cannot do <tt>ptr + 1</tt> and we can't do <tt>ptr + ptr2</tt> ( | We cannot do pointer arithmetic. Assuming <tt>ptr</tt> is a <tt>*int</tt>, we cannot do <tt>ptr + 1</tt> and we can't do <tt>ptr + ptr2</tt> (compilation error message: <tt>invalid operation: ptr + ptr2 (operator + not defined on pointer)</tt>). | ||
For more details, see [[Go_Concepts_-_Lexical_Structure#Pointers|pointers]]. | For more details, see [[Go_Concepts_-_Lexical_Structure#Pointers|pointers]]. |
Revision as of 01:09, 30 March 2016
Internal
Overview
Go is statically typed. Go designers tried to alleviate some of the "heaviness" associated with statically typed languages and made it "feel" like a dynamic language. For example Go uses local type inference, which eliminates the need to specify the type unnecessarily in program, the compiler figures it out.
Go is strongly typed meaning that yes cannot be unsafely coerced into other types they're not, or at least without programmer giving explicit permission. In JavaScript, for example, implicit conversion is done based on complicated rules that are not always easy to remember.
For more details on typing, see static typing vs. dynamic typing and strong typing vs. loose typing.
Type Definition
Built-in Types
Function Types
A function is member of a function type. The function type is defined by its signature.
Example: func(int) int.
// a variable of type func(int) int is declared var f func(int) int; // the variable is initialized with an actual function f = func(i int) int { return i + 1 }
Pointer Types
A pointer type is declared using the dereference operator * placed in front of the target type - the type of the stored value:
*int
We cannot do pointer arithmetic. Assuming ptr is a *int, we cannot do ptr + 1 and we can't do ptr + ptr2 (compilation error message: invalid operation: ptr + ptr2 (operator + not defined on pointer)).
For more details, see pointers.
User-Defined Types
Interfaces
Interfaces are not types.
Can only structs be interfaces, or there are other things that can be interfaces?
Zero Value
Zero value for a specific type: 0 for ints, 0.0 for floats, "" for string, false for Booleans and nil for pointers. For reference types, their underlying data structures are initialized to their zero values.
Reference Types
Value and Reference Types
Conversion Between Types
In order to convert between types, the type name is used like a function:
var f float64 = 5.0 var i int = 5 ... result = f / float64(i)
Primitive vs. Non-Primitive Nature
Duck Typing
For more details on duck typing go here.