Skip to content

Instantly share code, notes, and snippets.

@gabfssilva
Created March 27, 2025 14:19
Show Gist options
  • Save gabfssilva/eef3365dfb8db3c57b2fceb065f652c0 to your computer and use it in GitHub Desktop.
Save gabfssilva/eef3365dfb8db3c57b2fceb065f652c0 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"log"
)
type Element[T any] interface{ element() }
type Success[T any] struct {
Ctx context.Context
Value T
}
func (Success[T]) element() {}
type Failure[T any] struct {
Ctx context.Context
Err error
}
func (Failure[T]) element() {}
type Yield[T any] func(Element[T]) bool
func (yield Yield[T]) Success(ctx context.Context, value T) bool {
return yield(Success[T]{Ctx: ctx, Value: value})
}
func (yield Yield[T]) Failure(ctx context.Context, err error) bool {
return yield(Failure[T]{Ctx: ctx, Err: err})
}
func (yield Yield[T]) New(value T) bool {
return yield.Success(context.Background(), value)
}
type Stream[T any] func(yield Yield[T])
func main() {
numbers := Stream[int](func(yield Yield[int]) {
if !yield.New(1) {
return
}
if !yield.New(2) {
return
}
if !yield.New(3) {
return
}
})
quadraticNumbers := Stream[int](func(yield Yield[int]) {
for number := range numbers {
switch number := number.(type) {
case Success[int]:
if !yield.Success(number.Ctx, number.Value*2) {
return
}
case Failure[int]:
if !yield.Failure(number.Ctx, number.Err) {
return
}
}
}
})
for number := range quadraticNumbers {
log.Printf("%v", number)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment