I'm writing some package, where channel is only used to interrupt some process, so it is never read any value, just detects that it need to stop, like this:
func myfunc(stop_chan chan /*bool*/) {
for {
//do something time consuming
// ....
// check on channel
select{
case <-stop_chan:
//cleanup
return
default:
}
// continue working
}
}
later I wish this function to accept any type of channel. Is that possible?
I wish this function to accept any type of channel. Is that possible?
No, this is not possible. There are no untyped channels in Go. You could accept a channel of any type, using interface{}
, then using reflection to interact with that channel. But this is cumbersome and slow, so not recommended.
A better approach, probably, is to settle on a single type of channel (chan struct{}
is the natural choice for your use-case), or use a context
variable instead, which can handle cancellation in a standardized way.