简单的环实现,也就是首尾相接的双向链表
// src/container/ring/ring.go ---- line 8// A Ring is an element of a circular list, or ring.// Rings do not have a beginning or end; a pointer to any ring element// serves as reference to the entire ring. Empty rings are represented// as nil Ring pointers. The zero value for a Ring is a one-element// ring with a nil Value.//type Ring struct {next, prev *RingValue interface{} // for use by client; untouched by this library}
理所当然的结构体
比较有意思的是 Move,Link,Unlink 三个方法
// src/container/ring/ring.go ---- line 41// Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0)// in the ring and returns that ring element. r must not be empty.//func (r *Ring) Move(n int) *Ring {if r.next == nil {return r.init()}switch {case n < 0:for ; n < 0; n++ {r = r.prev}case n > 0:for ; n > 0; n-- {r = r.next}}return r}// src/container/ring/ring.go ---- line 77// Link connects ring r with ring s such that r.Next()// becomes s and returns the original value for r.Next().// r must not be empty.//// If r and s point to the same ring, linking// them removes the elements between r and s from the ring.// The removed elements form a subring and the result is a// reference to that subring (if no elements were removed,// the result is still the original value for r.Next(),// and not nil).//// If r and s point to different rings, linking// them creates a single ring with the elements of s inserted// after r. The result points to the element following the// last element of s after insertion.//func (r *Ring) Link(s *Ring) *Ring {n := r.Next()if s != nil {p := s.Prev()// Note: Cannot use multiple assignment because// evaluation order of LHS is not specified.r.next = ss.prev = rn.prev = pp.next = n}return n}// Unlink removes n % r.Len() elements from the ring r, starting// at r.Next(). If n % r.Len() == 0, r remains unchanged.// The result is the removed subring. r must not be empty.//func (r *Ring) Unlink(n int) *Ring {if n <= 0 {return nil}return r.Link(r.Move(n + 1))}
Move 倒是很简单,是因为 Unlink 用到了所以也贴出来。
Link 对参数是单节点或多节点环都能正常工作,非常神奇。而用语言描述清楚这个过程对表达能力不强的我似乎有些为难,还是画图直观些。

图中的 1,2,3,4 就分别是那四条语句建立的链接,而带 ‘ 的是指它们对应的原来的链接。在图一中因为 s 是单节点所以 s.Prev() 也就是 p 其实就是 s 所以画在一起
至于 Unlink 方法。假设参数 n 等于 2 即需要移出后两个节点
把 r.Move(n+1) 标出来之后就是 Link 了
还有比较有趣的一点是,结构体 Ring 的几乎所有方法(除了 Len 和 Do)都返回 Ring 指针,所以可以链式调用
