Go data structures(Arrays | Slices | Maps)

Go comes with many handy data structures that can help you store your own data, including arrays,slices, and maps.

  • The most important task that you should be able to perform on any data structure is accessing all of its elements in some way.
  • The second important task is having direct access to a specific tasks are inserting elements and deleting elements from data structures.
  • The last two equally important tasks are inserting elements and deleting from data structures.

Arrays

Arrays are the most popular data structure due to their  speed and are supported by almost all programming languages.

[maxwell@MaxwellDBA godatastructure]$ vim arrays.go
[maxwell@MaxwellDBA godatastructure]$ go run arrays.go
[1 2 4 -4]
[[1 2 3] [4 5 6] [7 8 9]]
[[[1 2] [3 4]] [[5 6] [7 8]]]
[maxwell@MaxwellDBA godatastructure]$ cat arrays.go
package main

import "fmt"

func main(){
  myArray := [4]int{1, 2, 4, -4}
  twoD := [3][3]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
  threeD := [2][2][2]int{{{1, 2}, {3,4}}, {{5, 6}, {7, 8}}}

  fmt.Println(myArray)
  fmt.Println(twoD)
  fmt.Println(threeD)
}
[maxwell@MaxwellDBA godatastructure]$

Go considers compiler issues that can be detected as compiler errors because this helps the development workflow, which is the reason for printing all the out of bounds array access errors of breakMe.go.

[maxwell@MaxwellDBA godatastructure]$ ls -ltr
total 8
-rw-rw-r-- 1 maxwell maxwell 276 Dec  9 11:04 breakMe.go
-rw-rw-r-- 1 maxwell maxwell 255 Dec  9 14:20 arrays.go
[maxwell@MaxwellDBA godatastructure]$ go run breakMe.go
# command-line-arguments
./breakMe.go:8:39: error: array index out of bounds
   fmt.Println("myArray[-1]:", myArray[-1])
                                       ^
./breakMe.go:9:39: error: array index out of bounds
   fmt.Println("myArray[10]:", myArray[10])
                                       ^
./breakMe.go:10:48: error: array index out of bounds
   fmt.Println("threeD[-1][20][0]:", threeD[-1][20][0])
                                                ^
./breakMe.go:10:44: error: array index out of bounds
   fmt.Println("threeD[-1][20][0]:", threeD[-1][20][0])
                                            ^
[maxwell@MaxwellDBA godatastructure]$

Go arrays have many and servere shortcomings:

1.First,Once you define an array, you cannot change its size, which means that Go arrays are not dynamic.

2.Second ,when you pass an array to a function, you actually pass a copy of the array.which means that any changes you make to an array inside a func on will be lost after the function finishes.

Slices

Slices have a capacity and length property, which are not always the same.

the length of a slice  can be found using the len() function.

The capacity of a slice is the current room that has been allocated for this particular slice and can be found with the cap() function.

As slices are dynamic in size,  once a slice run out of room, Go automatically doubles its current length to make room for more elements.

[maxwell@MaxwellDBA godatastructure]$ 
[maxwell@MaxwellDBA godatastructure]$ vim slices.go   
[maxwell@MaxwellDBA godatastructure]$ cat slices.go      
package main

import (
    "fmt"
)


func change(x []int){
   x[3] = -2
}


func printSlice(x []int){
   for _, number := range x {
         fmt.Printf("%d ", number)
   }
   fmt.Println()

}

func main() {
   aSlice := []int{-1,  4,  5,  0,  7,  9}
   fmt.Printf("Before change: ")
   printSlice(aSlice)
   change(aSlice)
   fmt.Printf("After change: ")
   printSlice(aSlice)


   fmt.Printf("Before. Cap: %d, length: %d\n", cap(aSlice), len(aSlice))
   aSlice = append(aSlice, -100)
   fmt.Printf("After. Cap: %d, length: %d\n", cap(aSlice), len(aSlice))
   printSlice(aSlice)
   anotherSlice := make([]int, 4)
   fmt.Printf("A new slice with 4 elements: ")
   printSlice(anotherSlice)
}
[maxwell@MaxwellDBA godatastructure]$ go run slices.go
Before change: -1 4 5 0 7 9 
After change: -1 4 5 -2 7 9 
Before. Cap: 6, length: 6
After. Cap: 12, length: 7
-1 4 5 -2 7 9 -100 
A new slice with 4 elements: 0 0 0 0 
[maxwell@MaxwellDBA godatastructure]$ 

According the above the test result, we can know , after adding a new element to the slice using append(), its length goes from 6 to 7 but its capacity doubles and goes from 6 to 12. The main advantage you get from doubling the capacity of a slice is better performance because Go will not have to allocate memory space all the time.

Maps

The Map data type in Go is equivalent to the well-known hash table found in other programming languages.

The main advantage of maps : can use almost any data type as their index, which in this case is called a Key.

[maxwell@MaxwellDBA godatastructure]$ vim maps.go
[maxwell@MaxwellDBA godatastructure]$ cat maps.go
package main

import (
   "fmt"
)


func main() {
   aMap :=  make(map[string]int)

   aMap["Mon"] = 0
   aMap["Tue"] = 1
   aMap["Wed"] = 2
   aMap["Thu"] = 3
   aMap["Fri"] = 4
   aMap["Sat"] = 5
   aMap["Sun"] = 6

   fmt.Printf("Sunday is the %dth day of the week.\n", aMap["Sun"])

   _, ok := aMap["Tuesday"]
   if ok {
        fmt.Printf("The Tuesday key exists!\n")
   } else {
      fmt.Printf("The Tuesday key does not exists!\n")
  }

  count := 0
  for key, _ := range aMap{
       count++
       fmt.Printf("%s ", key)
  }
  fmt.Printf("\n")
  fmt.Printf("The aMap has %d elements\n", count)

  count = 0
  delete(aMap, "Fri")
  for _, _ = range aMap{
       count++
  }
  fmt.Printf("The aMap has now %d elements\n", count)

  anotherMap := map[string]int{
         "One":   1,
         "Two":   2,
         "Three": 3,
         "Four":  4,
  }
  anotherMap["Five"] = 5
  count = 0
  for _, _ = range anotherMap {
         count++
  }

  fmt.Printf("anotherMap has %d elements\n", count)
}
[maxwell@MaxwellDBA godatastructure]$ go run maps.go
Sunday is the 6th day of the week.
The Tuesday key does not exists!
Mon Tue Wed Thu Fri Sat Sun 
The aMap has 7 elements
The aMap has now 6 elements
anotherMap has 5 elements
[maxwell@MaxwellDBA godatastructure]$ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值