Go 1.18 Type Parameter Inference

182 views
Skip to first unread message

Corin Lawson

unread,
Dec 22, 2021, 12:42:19 AM12/22/21
to golang-nuts
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).  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.

Ian Lance Taylor

unread,
Dec 22, 2021, 12:48:02 AM12/22/21
to Corin Lawson, golang-nuts
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

Corin Lawson

unread,
Dec 22, 2021, 12:50:49 AM12/22/21
to golang-nuts
huh TIL...

Thanks, I now see that there's no problem with the type inference.
Reply all
Reply to author
Forward
0 new messages