代码示例
package main import ( "bufio" "fmt" "os" "strings" "sync" ) //使用锁实现一个队列 type SliceQueue struct { data []interface{} mu sync.Mutex } func NewSliceQueue(n int) *SliceQueue { return &SliceQueue{data: make([]interface{},0,n)} } func (sq *SliceQueue) Enqueue(v interface{}) { sq.mu.Lock() sq.data = append(sq.data,v) sq.mu.Unlock() } //出队 func (sq *SliceQueue) Dequeue() interface{} { sq.mu.Lock() defer sq.mu.Unlock() v := sq.data[0] sq.data = sq.data[1:] return v } func main() { sq := NewSliceQueue(2) consol := bufio.NewScanner(os.Stdin) for consol.Scan(){ action := consol.Text() item := strings.Split(action," ") switch item[0] { case "push": if len(item) !=2 { fmt.Println("must be set value") continue } sq.Enqueue(item[1]) case "pop": val := sq.Dequeue() fmt.Println(val) case "quit","exit": return default: } } }