Created
March 2, 2022 16:13
-
-
Save mikroskeem/1809ff2b44440ac5e207041594b17c5c to your computer and use it in GitHub Desktop.
Doing weird stuff with Go generics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ~/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