Go语言中的Array、Slice、Map和Set使用详解

2019-11-10 08:57:44于海丽

     "AliceBlue":   "#f0f8ff",
     "Coral":       "#ff7F50",
     "DarkGray":    "#a9a9a9",
     "ForestGreen": "#228b22",
  }

  for key, value := range colors {
      fmt.Printf("Key: %s  Value: %sn", key, value)
  }

  removeColor(colors, "Coral")

  for key, value := range colors {
      fmt.Printf("Key: %s  Value: %sn", key, value)
  }
}

func removeColor(colors map[string]string, key string) {
    delete(colors, key)
}

执行会得到以下结果:


Key: AliceBlue Value: #F0F8FF
Key: Coral Value: #FF7F50
Key: DarkGray Value: #A9A9A9
Key: ForestGreen Value: #228B22
   
Key: AliceBlue Value: #F0F8FF
Key: DarkGray Value: #A9A9A9
Key: ForestGreen Value: #228B22

可以看出来传递 map 也是十分廉价的,类似 slice。

Set

Go 语言本身是不提供 set 的,但是我们可以自己实现它,下面就来试试:


package main

import(
  "fmt"
  "sync"
)

type Set struct {
  m map[int]bool
  sync.RWMutex
}

func New() *Set {
  return &Set{
    m: map[int]bool{},
  }
}

func (s *Set) Add(item int) {
  s.Lock()
  defer s.Unlock()
  s.m[item] = true
}

func (s *Set) Remove(item int) {
  s.Lock()
  s.Unlock()
  delete(s.m, item)
}

func (s *Set) Has(item int) bool {
  s.RLock()
  defer s.RUnlock()
  _, ok := s.m[item]
  return ok
}

func (s *Set) Len() int {
  return len(s.List())
}

func (s *Set) Clear() {
  s.Lock
  defer s.Unlock()
  s.m = map[int]bool{}
}

func (s *Set) IsEmpty() bool {
  if s.Len() == 0 {
    return true
  }
  return false
}

func (s *Set) List() []int {
  s.RLock()
  defer s.RUnlock()
  list := []int{}
  for item := range s.m {
    list = append(list, item)
  }
  return list
}

func main() {
  // 初始化
  s := New()
 
  s.Add(1)
  s.Add(1)
  s.Add(2)

  s.Clear()
  if s.IsEmpty() {
    fmt.Println("0 item")
  }
 
  s.Add(1)
  s.Add(2)
  s.Add(3)
 
  if s.Has(2) {
    fmt.Println("2 does exist")