Menu Close

Go – ring package in go

In this tutorial, we are going to learn about ring package in go golang. ring package is used to implement operations on circular lists.

A Ring is an element of a circular list or ring. Here, the most important thing is Rings do not have a beginning or end and a pointer to any ring element serves as reference to the entire ring. Empty rings are also represented as nil Ring pointers and the zero value for a Ring is a one-element ring with a nil Value.

Import ring package in go:

 import "container/ring"

Example:

package main

import (
        "container/ring"
        "fmt"
)

func main() {
        // Create a new ring of size 10
        ri := ring.New(10)

        // Get the length of the ring
        n := ri.Len()

        // Initialize the ring with some integer values
        for i := 0; i < n; i++ {
                ri.Value = i
                ri = ri.Next()
        }

        // Iterate through the ring and print its contents
        ri.Do(func(p any) {
                fmt.Println(p.(int))
        })

}

Output:

0
1
2
3
4
5
6
7
8
9

Types

type Ring:

type Ring struct {
	Value any // for use by client; untouched by this library
	// contains filtered or unexported fields
}

Here:
type any = interface{}
any is an alias for interface{} and is equivalent to interface{} in all ways.

type Ring functions:

To learn more about golang, Please refer given below link.

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/

Posted in golang, packages, ring

Leave a Reply

Your email address will not be published.

Contact Us