Hi!

I'm new here, but write Go on a daily basis for fun and profit.  The other 
day I wrote a giant type switch that was intended to organise a bag of 
various things into various bags each containing things of a single 
concrete type.  For example: https://go.dev/play/p/fqYXEP2YG_9 (Note that 
the real world code is consuming structs that have been generated by 
go-swagger <https://github.com/go-swagger/go-swagger>).  The slices in the 
map returned by `partitionByActionRequestType` are more convenient (after a 
type assertion) to work with, but in the example we are simply printing 
them.  Say, what you will about this code; my question is concerned with 
how to use generics to simplify the code (assuming generics is appropriate 
in this case).

My first attempt reduced a lot of the copy'n'paste: 
https://go.dev/play/p/XyTL0eqtwiR?v=gotip. It introduces a generic function 
that performs the slice construction and append of each branch, thereby 
reducing each branch into one line.  This seems like an improvement to me, 
but observe how the body of each branch is identical 
(character-for-character).

My next attempt involved collapsing branches: 
https://go.dev/play/p/t9E7jW6-xtz?v=gotip.  In this case the type inference 
did something unexpected, and we encounter the following error:

```
panic: interface conversion: interface {} is []main.ActionRequest, not 
[]*main.Build
```

The inferred type is more generic than desired; i.e. the type that is known 
prior to the type switch (i.e. the type of `next`) is the type that is 
inferred not the type that the type switch has determined (i.e. the type of 
`actionRequest`).

Am I wrong to expect this behaviour from the type inference?

Cheers,
Corin.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/ca313062-a37b-4f1f-8099-7c476abfa55dn%40googlegroups.com.

Reply via email to