Go基础编程实践,四—— 数组和map

数组去重

package main

import "fmt"

func main(){
  intSlice := []int{1,5,5,5,5,7,8,6,6, 6}
  fmt.Println(intSlice)
  uniqueIntSlice := unique(intSlice)
  fmt.Println(uniqueIntSlice)
}

func unique(intSlice []int) []int{
  keys := make(map[int]bool)
  uniqueElements := []int{}
  for _,entry := range intSlice {
    if _, value := keys[entry]; !value{
      keys[entry] =true
      uniqueElements = append(uniqueElements, entry)
    }
  }
  return uniqueElements
}

查找元素

package main

import (
  "fmt"
  "sort"
)

func main() {
  str := []string{"Sandy", "Provo", "St.george", "Salt lake City", "Draper", "South Jordan", "Murray"}

  // for循环查找
  for i, v := range str {
    if v == "Sandy" {
      fmt.Println(i)
    }
  }

  // sort包排序后查找
  // StringSlice给[]string添加方法以满足Interface接口,以便排序为递增序列。
  sortedList := sort.StringSlice(str)
  // 升序
  sortedList.Sort()
  fmt.Println(sortedList)
  index := sortedList.Search("Sandy")
  fmt.Println(index)
}

数组降序

package main

import (
  "sort"
  "fmt"
)

func main() {
  numbers := []int{1, 5, 3, 6, 2, 10, 8}
  // IntSlice给[]int添加方法以满足Interface接口,以便排序为递增序列。
  tobeSorted := sort.IntSlice(numbers)
  // Reverse包装一个Interface接口并返回一个新的Interface接口,对该接口排序可生成递减序列。
  sort.Sort(sort.Reverse(tobeSorted))
  fmt.Println(tobeSorted)
}

迭代数组

package main

import "fmt"

func main(){
  numbers := []int{1, 5, 3, 6, 2, 10, 8}

  for index,value := range numbers{
     fmt.Printf("Index: %v and Value: %v\n", index, value)
  }
}

将map转为数组

package main

import "fmt"

type NameAge struct{
  Name string
  Age int
}

func main(){
  var nameAgeSlice []NameAge
  nameAges := map[string]int{
    "Michael": 30,
    "John": 25,
    "Jessica": 26,
    "Ali": 18,
  }
  for key, value := range nameAges{
    nameAgeSlice = append(nameAgeSlice, NameAge {key, value})
  }

  fmt.Println(nameAgeSlice)

}

合并数组

package main

import "fmt"

func main(){
  items1 := []int{3,4}
  items2 := []int{1,2}
  result := append(items1, items2...)
  fmt.Println(result)
}

合并map

package main

import "fmt"

func main(){
  map1 := map[string]int {
   "Michael":10,
   "Jessica":20,
   "Tarik":33,
   "Jon": 22,
  }
  fmt.Println(map1)

  map2 := map[string]int {
    "Lord":11,
    "Of":22,
    "The":36,
    "Rings": 23,
  }
  for key, value := range map2{
    map1[key] = value
  }
  fmt.Println(map1)
}

判断map中key是否存在

package main

import "fmt"

func main() {
  nameAges := map[string]int{
    "Tarik": 32,
    "Michael": 30,
    "Jon": 25,
    "Jessica" : 20,
  }
  if _, exists := nameAges["Jessica"]; exists{
    fmt.Println("Jessica can be found")
  }else {
    fmt.Println("Jessica cannot be found")
  }
}