Menu Close

Go – New() function in ring package in go

In this tutorial, we will learn about New() function in ring package in go golang. New() function is used to creates a ring of n elements.

New() function prototype of ring package:

func New(n int) *Ring

Return value of New() function:

 New() returns Ring type pointer. 

Example of New() function in ring package:

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

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

References:

https://golang.org/doc/

Posted in golang, packages, ring

Leave a Reply

Your email address will not be published. Required fields are marked *