Rodrigo Martins

I'm a Catholic Christian, software developer, Passionate about life, codes, questions, theories and theorems. :)

[Go] Difference Between Map, Slice and Array #go

| Comments

Hi,

Let’s talk a little about map, slice and array in Go language.

I go start talk with map:

Maps

Maps are Go’s built-in associative data type (sometimes called hashes or dicts in other languages).

Go create a map empty, use the structure make(map[key-type]val-type):

map empty
1
  m := make(map[string]int)

By setting the key and value:

set key/value
1
2
  m["one"] = 12
  m["two"] = 05

Get a value of key:

get valeu
1
value := m["one"]

Easy!

To return size the map:

size map
1
len := len(m)

Deleted a key:

delete key
1
delete(m, "two")

If want get m["two"] after delete key, the return is 0, but can use _ (blank identifier).

get value deleted
1
_, can_valeu := m["two"]

Then the value of can_valeu is false.

Create map with key type integer:

key integer
1
m := make(map[int]int)
set key/value of type integer
1
2
  m[1] = 12
  m[2] = 05

Using a map in a loop:

1
2
3
for i := range m {
    fmt.Println("i:", i)
}

Slice

Go talk about Slice.

Slices are a key data type in Go, giving a more powerful interface to sequences than arrays.

Create a slice the values of string type and with the length 3:

1
2
myslice := make([]string, 3)
fmt.Println("myslice:", myslice)

The myslice slice is [ ], initially zero valued. Now go set values.

1
2
3
myslice[0] = "a"
myslice[1] = "b"
myslice[2] = "c"

To get value, use slice[key].

1
myslice[2]

When create a slice, the default type of key is integer.

Get length is equal the map:

length slice
1
len(myslice)

To add new values in our slice, use append(slice, value[s]):

append
1
2
3
myslice = append(myslice, "d")
myslice = append(myslice, "e")
myslice = append(myslice, "f", "g", "h")

We can cut a slice from one location to another:

cut a slice
1
2
3
myslice[1:4] // from position 1 to the position 4
myslice[1:] // from position 1 to the end
myslice[:4] // from position 0 to the position 4

We have other ways of working with slice.

Array

Go talk about Array.

In Go, an array is a numbered sequence of elements of a specific length.

Array is most simple.

Create a array with position 10, of type string:

create a array
1
var arr [10]string

The default valeu an array is zero-valued, which for string means “”, if the array were of type integer, then the default values would be 0.

To set value, is need speak key of array.

set value
1
arr[0] = "one str"

Get is equal map and slice:

get value
1
arr[0] // easy! :)

Get the length of array, len():

len()
1
len(arr)

Many other functions of array are similar of map and slices.

References:

Comments