huh TIL...

Thanks, I now see that there's no problem with the type inference.

On Wednesday, 22 December 2021 at 4:48:02 pm UTC+11 Ian Lance Taylor wrote:

> On Tue, Dec 21, 2021 at 9:42 PM Corin Lawson <corin....@gmail.com> wrote:
> >
> > 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). 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?
>
> When you write a case like `case *Build, *Test, *Run:` the type in the
> case body does not change. The type only changes if there is just a
> single type in the case. So the type of actionRequest is
> ActionRequest, which is why you get those results.
>
> Ian
>

-- 
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/602dbfe3-18e2-4cd2-8cf3-72204cfc4ac1n%40googlegroups.com.

Reply via email to