From 2163c9b567a050b29f8974dd0a6bf4b77ee918d0 Mon Sep 17 00:00:00 2001 From: devlights Date: Fri, 20 Sep 2024 07:59:05 +0000 Subject: [PATCH] Add examples/singleapp/ring-index --- examples/singleapp/ring_index/Taskfile.yml | 8 +++ examples/singleapp/ring_index/main.go | 57 ++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 examples/singleapp/ring_index/Taskfile.yml create mode 100644 examples/singleapp/ring_index/main.go diff --git a/examples/singleapp/ring_index/Taskfile.yml b/examples/singleapp/ring_index/Taskfile.yml new file mode 100644 index 00000000..6210a5f1 --- /dev/null +++ b/examples/singleapp/ring_index/Taskfile.yml @@ -0,0 +1,8 @@ +# https://taskfile.dev + +version: '3' + +tasks: + default: + cmds: + - go run . diff --git a/examples/singleapp/ring_index/main.go b/examples/singleapp/ring_index/main.go new file mode 100644 index 00000000..65b8e6be --- /dev/null +++ b/examples/singleapp/ring_index/main.go @@ -0,0 +1,57 @@ +package main + +import ( + "context" + "fmt" + "log" +) + +type ( + ring struct { + curr int + last int + next int + } +) + +func newRing() *ring { + return &ring{curr: 0, last: 2, next: 1} +} + +func (me *ring) rotate() { + me.curr = (me.curr + 1) % 3 + me.last = (me.last + 1) % 3 + me.next = (me.next + 1) % 3 +} + +func (me *ring) String() string { + return fmt.Sprintf("(curr=%d,last=%d,next=%d)", me.curr, me.last, me.next) +} + +func main() { + log.SetFlags(0) + + ctx := context.Background() + if err := run(ctx); err != nil { + log.Panic(err) + } +} + +func run(ctx context.Context) error { + var ( + r = newRing() + ) + + for range 10 { + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + log.Println(r) + r.rotate() + } + + return nil +}