PPysolate SpineREAD THE CODE · UNDERSTAND THE SYSTEM
课程与章节
源码索引 / CURRENT IMPLEMENTATION

learning/go-patterns/patterns/ownership/ownership.go

36 行 · 点击行号可定位;函数链接随声明位置更新,不手填行号。

跳到函数 / 声明
// Package ownership demonstrates a single-owner mutable queue and an explicit
// move-like Drain operation.
package ownership

// Queue is intended to be used by one goroutine at a time. Its zero value is
// ready to use; use shared-map (or another synchronization boundary) when
// multiple goroutines need shared mutable state.
type Queue struct {
	items []string
}

// NewQueue creates a queue with an optional initial capacity.
func NewQueue(capacity int) *Queue {
	if capacity < 0 {
		capacity = 0
	}
	return &Queue{items: make([]string, 0, capacity)}
}

// Push adds an item to the queue owned by q.
func (q *Queue) Push(item string) {
	q.items = append(q.items, item)
}

// Len reports the number of queued items.
func (q *Queue) Len() int {
	return len(q.items)
}

// Drain transfers the backing slice to the caller and leaves q empty. After
// this call the returned slice is the caller's mutable data, not queue state.
func (q *Queue) Drain() []string {
	items := q.items
	q.items = nil
	return items
}