Mittwoch, 9. Dezember 2009

Container in Go: ring

Ring:

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


package main

import (
. "fmt";
"container/ring";
"strings";
"bytes";
)

// print the elements of the ring
func PrintRing(r *ring.Ring) {
Println("------------------------------");
for value := range r.Iter() {
Println("value: ", value);
}
Println("------------------------------");
}

func main() {
// create a new ring with 10 items
r := ring.New(10);

Println("len of ring: ", r.Len());
PrintRing(r);

// set some value
r.Value = "value 1";
// take the next

r = r.Next();
r.Value = "value 2";

r = r.Next();
r.Value = "value 3";

r = r.Next();
r.Value = "value 4";

PrintRing(r);


// create a second ring with 3 item and set his value
r2 := ring.New(3);
r2.Value = "r2 value 1";
r2 = r2.Next();
r2.Value = "r2 value 2";
r2 = r2.Next();
r2.Value = "r2 value 3";
PrintRing(r2);

// merge ring2 into ring 1
r = r.Link(r2);
PrintRing(r);

// remove a value in ring
for p:=r.Next(); p!=r; p=p.Next() {
if p.Value != nil {
value := p.Value.(string);
if bytes.Equal(strings.Bytes(value),strings.Bytes("r2 value 2")) {
p.Value=nil;
}
}
}

PrintRing(r);
}

output:

len of ring: 10
------------------------------
value:
value:
value:
value:
value:
value:
value:
value:
value:
value:
------------------------------
------------------------------
value: value 4
value:
value:
value:
value:
value:
value:
value: value 1
value: value 2
value: value 3
------------------------------
------------------------------
value: r2 value 3
value: r2 value 1
value: r2 value 2
------------------------------
------------------------------
value:
value:
value:
value:
value:
value:
value: value 1
value: value 2
value: value 3
value: value 4
value: r2 value 3
value: r2 value 1
value: r2 value 2
------------------------------
------------------------------
value:
value:
value:
value:
value:
value:
value: value 1
value: value 2
value: value 3
value: value 4
value: r2 value 3
value: r2 value 1
value:
------------------------------

Keine Kommentare:

Kommentar veröffentlichen