Numbers
Conversion between numbers can be done using a global built-in function with the type name.
myId := 10
myTicketPrice := 55.7
myIdAsFloat := float64(myId)
myTicketPriceAsInt := int(myTicketPrice)
Not every conversion is possible, e.g. a
string
into abool
.
Strings
Multiline strings can be created using backticks.
strSingle := "Just a single line of text."
strMulti := `We are
on multiple
lines here!`
Collections
What do we have?
Arrays
Fixed length
[5]int
Slices
Similar to dynamic length arrays, but are in practice chunks of arrays
[]int
Maps
Key-value dictionaries
map[keyType]valueType
// Example
map[string]int
Generics
Since Go version 1.18
TRY IT OUT
- Declare a new array with a length of
20
and typestring
. - Declare a new slice with the type
int
. - Declare a new map with a key of type
int
and a value of typestring
. - Discuss the special function
init
. This is not the same as main() ! Not a constructor. - The
len()
function returns the length of a collection.
Collections are not objects. We use global functions to work with collections, such as
len()
andcap()
.
Arrays and slices
Remember, arrays are fixed length and slices are dynamic length.
Arrays
var countries [180]string
countries[0] = "Denmark"
// Initialize with values, shorthand notation
accounts := [5]int{1, 2, 3, 4, 5}
Slices
Declaring a string slice.
We use append to add values and note that the new slice is assigned back to the variable.
var countries []string
countries = append(countries, "Denmark")
Initialize with values.
Overrides any capacity defined in the declaration.
var countries = []string{"Denmark", "Sweden", "Norway"}
println(len(countries))
Initialize with a capacity of 5.
This defines the default increment size when the slice runs out of space.
var countries = make([]string, 5)
Maps
Pay attention to the type definition.
- For maps the default value is
nil
—initialization is required.
var platformUsers = map[string]int{"Facebook": 1000000, "Twitter": 500000}
The make()
function can also be used to initialize a map and this is most commonly what is done as maps are rarely small in size.
var platformUsers = make(map[string]int)
platformUsers["Facebook"] = 1000000
platformUsers["Twitter"] = 500000