📜  Golang 中的 ring 包

📅  最后修改于: 2021-10-25 02:30:27             🧑  作者: Mango

Go 语言提供了一个 ring 包,可以实现对循环列表的操作。要访问环包的功能,您需要在程序中借助 import 关键字导入环包。

Method Description
func New This method is used to create a ring of the n elements.
func (*Ring) Do This method is used to call function f on each element of the ring in forward order.
func (*Ring) Len This method is used to computes the number of elements in ring r.
func (*Ring) Link This method is used to connects ring r with ring s such that r.
func (*Ring) Move This method is used to moves n % r.Len() elements backward (n < 0) or forward (n >= 0) in the ring and returns that ring element.
func (*Ring) Next This method is used to returns the next ring element.
func (*Ring) Prev This method is used to returns the previous ring element.
func (*Ring) Unlink This method is used to removes n % r.Len() elements from the ring given r, starting at r.Next().

示例 1:

// Golang program to illustrate 
// the ring.Len() function 
package main 
  
import ( 
    "container/ring"
    "fmt"
) 
// Main function 
func main() { 
  
    // Creating a new ring of size 5
    r_ring := ring.New(5) 
  
    // Print out its length 
    fmt.Println(r_ring.Len()) 
  
} 

输出:

5

示例 2:

// Golang program to illustrate 
// the ring.Link() function 
package main 
  
import ( 
    "container/ring"
    "fmt"
) 
  
// Main function 
func main() { 
  
    // Create two rings, r1 and r2, of size 3
    r1 := ring.New(3) 
    r2 := ring.New(3) 
  
    // Get the length of the ring 
    lr := r1.Len() 
    ls := r2.Len() 
  
    // Initialize r1 with "GFG" 
    for i := 0; i < lr; i++ { 
        r1.Value = "GFG"
        r1 = r1.Next() 
    } 
  
    // Initialize r2 with "GOLang" 
    for j := 0; j < ls; j++ { 
        r2.Value = "GoLang"
        r2 = r2.Next() 
    } 
  
    // Link ring r1 and ring r2 
    rs := r1.Link(r2) 
  
    // Iterate through the combined 
    // ring and print its contents 
    rs.Do(func(p interface{}) { 
        fmt.Println(p.(string)) 
    }) 
} 

输出:

GFG
GFG
GFG
GoLang
GoLang
GoLang