Skip to content

Instantly share code, notes, and snippets.

@mikroskeem
Created March 2, 2022 16:13
Show Gist options
  • Save mikroskeem/1809ff2b44440ac5e207041594b17c5c to your computer and use it in GitHub Desktop.
Save mikroskeem/1809ff2b44440ac5e207041594b17c5c to your computer and use it in GitHub Desktop.
Doing weird stuff with Go generics
// ~/go/bin/go1.18beta2
package main
type Closeable interface {
Close() error
}
type CloseableChan[T any] struct {
ch chan T
}
func NewCloseableChan[T any](ch chan T) *CloseableChan[T] {
return &CloseableChan[T]{
ch: ch,
}
}
func (cc *CloseableChan[T]) Close() (err error) {
close(cc.ch)
return
}
func CloseAll(closeable ...Closeable) (err error) {
for _, cl := range closeable {
if err = cl.Close(); err != nil {
return
}
}
return
}
func main() {
a := NewCloseableChan(make(chan string))
b := NewCloseableChan(make(chan bool))
c := NewCloseableChan(make(chan error))
err := CloseAll(a, b, c)
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment