4 ms·
> I think that switching on types in Go is gererally a total anti-pattern. It's not. It's a standard way of implementing variant types. See https://golang.org/
by burntsushi 10y ago
> I think that switching on types in Go is gererally a total anti-pattern.
It's not. It's a standard way of implementing variant types. See https://golang.org/doc/faq#variant_types https://golang.org/doc/faq#variant_types and https://golang.org/src/go/ast/walk.go?s=1311:1342#L41 https://golang.org/src/go/ast/walk.go?s=1311:1342#L41
True, it's not used often. Sum types aren't a great fit for Go (as the FAQ says), but sometimes they are exactly what you want.
> Otherwise you're just fighting the language, which doesn't make any sense, as you can just switch to Rust then.
I find these types of comments really dismissive and unhelpful. A single comment declaration and one Sunday's worth of hacking (thanks to the incredible tooling provided by Go) makes my experience using Go better. Why do I need to switch to Rust? It would take several months and significant social capital to do. (And I'm saying this as a member of the Rust library team!)
- cube2222 10y agoActually, after reading the walk.go code I still wonder what the best way to do it would be. (Not saying it's bad now, though I'll still remain my devils advocate) As I skimmed through the code, in my opinion you could easily have a Walk(v Visitor) method on each of those node types. This way you'd have no need for casting, and in the Walk method you would be able to use type-specific functionality without the need to cast. The only disadvantage I see is that the Walking functionality would be spread out among the code in different places, but this isn't a problem with modern editors. I'll note this down somewhere and if I have time I'll test it out sometime.
- pbnjay 10y agoGreat minds think alike (IMHO) https://www.reddit.com/r/golang/comments/60dik1/a_utility_for_running_exhaustiveness_checks_on/df669jk/ https://www.reddit.com/r/golang/comments/60dik1/a_utility_fo...
- cube2222 10y agoAnyways, my conclusion is. In most cases it IS an anti-pattern. Only if the, let's say "observing" function (the one that decides on the type), is really just observing the behavior nad trying not to interwind with the mechanics of the actual structures is it justified I think. In that case it provides greater cleanliness of your code. In this case though, as this is the ast package, and walking is a standard functionality of an ast, I think this could just as well be implemented with interfaces.