0%

GO_Learning_Fundamental_Array_Slice_Map

Array

Array is primarily as the building block for Slice.

Features:

  • Arrays are values. Assigning one array to another copies all the elements.
  • In particular, if you pass an array to a function, it will receive a copy of the array, not a pointer to it.
  • The size of an array is part of its type. The types [10]int and [20]int are distinct.

The value property can be useful but also expensive; if you want C-like behavior and efficiency, you can pass a pointer to the array.

1
2
3
4
5
6
7
8
9
func Sum(a *[3]float64) (sum float64) {
for _, v := range *a {
sum += v
}
return
}

array := [...]float64{7.0, 8.5, 9.1}
x := Sum(&array) // Note the explicit address-of operator

But even this style isn’t idiomatic Go. Use slices instead.

Slice

Slice wrap arrays to give a more general, powerful and convinent interface to sequence of data. Most array programming in GO is done with slices rather than simple arrays.

Features:

  • Slices hold the references to an underlaying array
    • if you assign one slice to another, both refer to the same array.
    • If a functions take Slice argument, changes it makes to the slices elements will be visible to the caller.

The length of a slice may be changed as long as it still fits within the limits of the underlying array; just assign it to a slice of itself. The capacity of a slice, accessible by the built-in function cap, reports the maximum length the slice may assume. Here is a function to append data to a slice. If the data exceeds the capacity, the slice is reallocated. The resulting slice is returned. The function uses the fact that len and cap are legal when applied to the nil slice, and return 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
func Append(slice, data []byte) []byte {
l := len(slice)
if l + len(data) > cap(slice) { // reallocate
// Allocate double what's needed, for future growth.
newSlice := make([]byte, (l+len(data))*2)
// The copy function is predeclared and works for any slice type.
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0:l+len(data)]
copy(slice[l:], data)
return slice
}

We must return the slice afterwards because, although Append can modify the elements of slice, the slice itself (the run-time data structure holding the pointer, length, and capacity) is passed by value.

Map

What Map ?

The key can be of any type for which the equality operator is defined, such as integers, floating point and complex numbers, strings, pointers, interfaces (as long as the dynamic type supports equality), structs and arrays. Slices cannot be used as map keys, because equality is not defined on them. Like slices, maps hold references to an underlying data structure. If you pass a map to a function that changes the contents of the map, the changes will be visible in the caller.

initialize Map

Maps can be constructed using the usual composite literal syntax with colon-separated key-value pairs, so it’s easy to build them during initialization.

1
2
3
4
5
6
7
var timeZone = map[string]int{
"UTC": 0*60*60,
"EST": -5*60*60,
"CST": -6*60*60,
"MST": -7*60*60,
"PST": -8*60*60,
}

Features

  • get value: simliar with slice

    1
    offset := timeZone["EST"]
  • apply the key which not in map : return zeros of value type

    1
    2
    3
    4
    5
    6
    7
    8
    9
    attended := map[string]bool{
    "Ann": true,
    "Joe": true,
    ...
    }

    if attended[person] { // will be false if person is not in the map
    fmt.Println(person, "was at the meeting")
    }
  • two var is accept : get gistinguish a missing entry from zeros value

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var seconds int
    var ok bool
    seconds, ok = timeZone[tz]
    func offset(tz string) int {
    if seconds, ok := timeZone[tz]; ok {
    return seconds
    }
    log.Println("unknown time zone:", tz)
    return 0
    }
  • Omit value: _

    1
    _, present := timeZone[tz]
  • Delete map entry:delete function

    SAFE function even if the key is already absent from the map.

    1
    delete(timeZone, "PDT")  // Now on Standard Time