Open In App

ring package in Golang

Improve
Improve
Like Article
Like
Save
Share
Report

Go language provides a ring package that implements operations on circular lists. To access the functions of the ring package you need to import the ring package in your program with the help of the import keyword.

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().

Example 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()) 
  


Output:

5

Example 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)) 
    }) 


Output:

GFG
GFG
GFG
GoLang
GoLang
GoLang


Last Updated : 28 Jul, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads