Skip to content

Latest commit

 

History

History
executable file
·
144 lines (105 loc) · 3.02 KB

File metadata and controls

executable file
·
144 lines (105 loc) · 3.02 KB

Slices and Maps

Slices

https://go.dev/tour/moretypes/7

A slice in go is a dynamically-sized, flexible view into the elements of an array

Example from our maps_and_slices_example.go file:

Create a slice

// create an empty slice of integers
var s1 []int

// create and populate a slice all in one line
s2 := []int{5, 4, 3, 2}

Append to a slice

// add some stuff to the slice
s1 = append(s1, 1, 2, 3)

Get something from a specific index of a slice

fmt.Printf("thing at index 1 in slice s1 is %d\n", s1[1])

Output

thing at index 1 in slice s1 is 2

Iterate through the slice

for index, value := range s1 {
    fmt.Printf("slice s1 of type %T has %d at index %d\n", s1, index, value)
}

Output

slice s1 of type []int has 0 at index 1
slice s1 of type []int has 1 at index 2
slice s1 of type []int has 2 at index 3

Maps

https://go.dev/tour/moretypes/19

Maps are an associative data type (sometimes called hashes or dicts in other languages)

Example from our maps_and_slices_example.go file:

Create a map

// create an empty map of unspecified type (technically the map is nil as we'll see later)
var m1 map[string]interface{}

// create a map and initialize it all in one go
m2 := map[string]int{
    "one":   1,
    "two":   2,
    "three": 3,
}

Append to a map

// add something to the m1 map
// m1["foo"] = "bar" will cause a panic: assignment to entry in nil map because we did not initialize the map
if m1 == nil {
    m1 = make(map[string]interface{})
}

// now that the map is initialized it can be appended to it and since it is of type interface we can append whatever
m1["foo"] = "bar"

Iterate through a map

for key, value := range m1 {
    fmt.Printf("Key %s has a value of  %s\n", key, value)
}

Output

Key one has a value of  1
Key two has a value of  2
Key three has a value of  3

Get a specific item from a map

if value, ok := m2["one"]; ok {
    fmt.Printf("Value %d was found for key 'one' in the m2 map", value)
}

Output

Value 1 was found for key 'one' in the m2 map

Example

You can see this live in action in our maps_and_slices_example.go example. To run this example:

go run examples/maps_and_slices/maps_and_slices_example.go

Output

thing at index 1 in slice s1 is 2
thing at index 1 in slice s2 is 4
slice s1 of type []int has 0 at index 1
slice s1 of type []int has 1 at index 2
slice s1 of type []int has 2 at index 3
slice s2 of type []int has 0 at index 5
slice s2 of type []int has 1 at index 4
slice s2 of type []int has 2 at index 3
slice s2 of type []int has 3 at index 2
Key one has a value of  1
Key two has a value of  2
Key three has a value of  3
Value 1 was found for key 'one' in the m2 map