3 ms·
Go's channels also have a lot of footguns and should be abstracted in a handle type in a public API.
by treyd 3y ago
Go's channels also have a lot of footguns and should be abstracted in a handle type in a public API.
- reactordev 3y agoExcept it itself is exposed via a public API. Context interface also exposes a chan Done() <- chan struct{} What are you trying to say? That using a chan as a function argument can shoot yourself in the foot? The whole idea behind channels is to not shoot yourself in the foot with mutex's, deadlocks, etc. What are you trying to say? Wrapping a chan in a type handle is safer than passing a chan of a type? Nope.
- foobiekr 3y agoexactly. you can't abstract over channels easily unless you're missing the point of channels.
- earthboundkid 3y agoI think the rule is: don't use a channel unless at some point you need a select with 2+ branches. The context.Done is a case in point. You're not just waiting around for a context to finish. You do two things: try some network request and wait to see if the context cancels before it finishes. Because it's made to work in a select block like that, there wasn't another, better thing to use than a channel for context.Done. But for just iterating through some stream, you take a context in and return an iterator object that will do all the channel stuff internally.
- treyd 3y agoThat's not at all what I was referring to. It's not merely having channels as function arguments. Channels broadly have footguns around how closed and nil channels are treated and you can run into work contention/starvation issues accidentally, since they do have their own throughput limits. And wrapping them in your own handle types that's specific to the library's use case allows you to deal with those issues and swap out the implementation of the cross-goroutine bits without breaking the downstream API.
- kitd 3y agoChannels broadly have footguns around how closed and nil channels are treated I appreciate your concerns but one could say similar things about nil pointers or accessing slices out of range. Anything you use should be handled with care.
- tw1984 3y agoNo. Being the first class element in the go language, channel is nothing different from a []byte or a regular struct. The whole purposes of having such built-in channel as a part of the core language is to encourage everyone to use it whenever possible, the reason is dead simple - it is much less likely to shoot yourself in the foot.
- politician 3y agoWell, I think read-only channels in public APIs are fine. Writable or write-only channels are dangerous and should be avoided given that the "close ownership" -- to coin a phrase -- is ambiguous. For the write end, I agree that a handle type is appropriate.