container/ring 使用示例

package main

import (
    "container/ring"
    "fmt"
)

var size int = 10

func main() {
    myRing := ring.New(size)
    fmt.Println("Empty ring:", *myRing)

    for i := 0; i < myRing.Len()-1; i++ {
        myRing.Value = i
        myRing = myRing.Next()
    }

    myRing.Value = 2

    sum := 0
    myRing.Do(func(x interface{}) {
        t := x.(int)
        sum = sum + t
    })
    fmt.Println("Sum:", sum)

    for i := 0; i < myRing.Len()+5; i++ {
        myRing = myRing.Next()
        fmt.Print(myRing.Value, " ")
    }
    fmt.Println()
}

运行结果:

Empty ring: {0xc00010a020 0xc00010a120 <nil>}
Sum: 38
0 1 2 3 4 5 6 7 8 2 0 1 2 3 4 

 

posted @ 2023-08-05 16:30  salami_china  阅读(19)  评论(0编辑  收藏  举报