On Tue, Dec 21, 2021 at 9:42 PM Corin Lawson <corin.law...@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/CAOyqgcVHmzZFP%3DQnVfnZo0rfoAgiMuT9ftDVXSr68xb%2ByFPn_Q%40mail.gmail.com.

Reply via email to