Menu Close

Go – Unlink() function of ring package in go

Unlink() function of ring package is used to remove the element from ring in go where ring must not be empty.

Unlink removes n % (r.Len()) elements from the ring r and It will start from at r.Next().  If n % (r.Len()) == 0 then r remains unchanged.

Unlink() function prototype of ring package:

func (r *Ring) Unlink(n int) *Ring

Return type in Unlink() function of ring package:

 Unlink() returns ring type pointer to deleted ring element. It's a Ring type.

Example of Unlink() function in ring package:

package main

import (
        "container/ring"
        "fmt"
)

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

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

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

        // Iterate through the ring elements
        fmt.Println("Ring elements are: ")
        r.Do(func(p any) {
                fmt.Println(p.(int))
        })

        // Unlink three elements from r, starting from r.Next()
        x := r.Unlink(3)

        // Iterate through the deleted ring elements
       fmt.Println("\nIterate through the deleted ring elements")
        x.Do(func(p any) {
                fmt.Println(x.Value)
                x = x.Next()
        })
        
        // Iterate through the remaining ring elements
        fmt.Println("\nIterate through the remaining ring elements after deleting")
        r.Do(func(p any) {
                fmt.Println(p.(int))
        })
}

Output:

Ring elements are:
0
1
2
3
4
5

Iterate through the deleted ring elements
1
2
3

Iterate through the remaining ring elements after deleting
0
4
5

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 *