golang go中的可附加intlist结构,它使用map作为其实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang go中的可附加intlist结构,它使用map作为其实现相关的知识,希望对你有一定的参考价值。

package main
//file to implement expanding/shrinking intlist with a map
import "fmt"

type IntList struct {
	list map[int]int
	//for keeping track of placement indices and insertion spots
	record map[string]int
}

//creates an IntList and returns it
func createIntList() IntList {
	lst := IntList{list:make(map[int]int), record:make(map[string]int)}
	lst.record["insert"] = 0
	lst.record["last"] = -1
	return lst
}
//appends a new element to the end of the list, and updates the insertion and last element positions
func (il IntList) push(elem int) {
	il.list[il.record["insert"]] = elem
	il.record["insert"] += 1
	il.record["last"] += 1
}


func main() {
  tester := createIntList()
  tester.push(5)
  fmt.Println(tester)
  //{map[0:5] map[last:0 insert:1]}
}

golang Go(Golang)中的并发安全SET数据结构

// A very simple example about how to use concurrent-safe SETs (using string as keys) in GO
package main

import (
  "fmt"
	"sync"
)

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

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

func main() {
	// Initialize our Set
	s := New()

	// Add example items
	s.Add("item1")
	s.Add("item1") // duplicate item
	s.Add("item2")
	fmt.Printf("%d items\n", s.Len())

	// Clear all items
	s.Clear()
	if s.IsEmpty() {
		fmt.Printf("0 items\n")
	}

	s.Add("item2")
	s.Add("item3")
	s.Add("item4")

	// Check for existence
	if s.Has("item2") {
		fmt.Println("item2 does exist")
	}

	// Remove some of our items
	s.Remove("item2")
	s.Remove("item4")
	fmt.Println("list of all items:", s.List())
}

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

// Remove deletes the specified item from the map
func (s *Set) Remove(item string) {
	s.Lock()
	defer s.Unlock()
	delete(s.m, item)
}

// Has looks for the existence of an item
func (s *Set) Has(item string) bool {
	s.RLock()
	defer s.RUnlock()
	_, ok := s.m[item]
	return ok
}

// Len returns the number of items in a set.
func (s *Set) Len() int {
	return len(s.List())
}

// Clear removes all items from the set
func (s *Set) Clear() {
	s.Lock()
	defer s.Unlock()
	s.m = make(map[string]bool)
}

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

// Set returns a slice of all items
func (s *Set) List() []string {
	s.RLock()
	defer s.RUnlock()
	list := make([]string, 0)
	for item := range s.m {
		list = append(list, item)
	}
	return list
}

以上是关于golang go中的可附加intlist结构,它使用map作为其实现的主要内容,如果未能解决你的问题,请参考以下文章

golang 包结构

golang 在go中附加切片

golang Go(Golang)中的并发安全SET数据结构

golang go中的基本结构

golang go中的示例列表结构支持

golang 可以推送和弹出的intlist