I think you should be able to declare a common interface that all 
instantiations of ResourceUpdateMsg implement, and then you can type-assert 
on that interface and pass it around when any ResourceUpdateMsg is desired.

Runnable example here: https://play.golang.com/p/ciQkOqJSgyw

The main idea is to create an AnyResourceUpdateMsg type, which is an 
interface that is only satisfied by instantiations of ResourceUpdateMsg 
(e.g. add an unexported method), and to match against that.

On Sunday, November 23, 2025 at 10:45:21 AM UTC-7 Matthias Jeschke wrote:

> Hi, 
>
> I'm experimenting with bubbletea for creating a TUI and I came across the 
> following problem:
>
> I have a generic struct declared:
>
> type ResourceUpdateMsg[T any] struct {
> value T
> }
>
> This is used to create messages, e.g.:
>
> func updateCpuStats() tea.Msg {
> cpuStats, _ := cpu.Percent(0, false)
> return ResourceUpdateMsg[Cpu]{
> Cpu{
> Usage: cpuStats[0],
> },
> }
> }
>
> Now, in one update function I'm not interested in the specific type of a 
> message; each message should be routed to another, more specific update 
> function:
>
> switch msg := msg.(type) {
>
> case resources.ResourceUpdateMsg[any]:
> resourceModel, cmd := m.resources.Update(msg)
> m.resources = resourceModel.(resources.Model)
> return m, cmd
>          ....
>          }
>
> In the other, specific update function the switch distinguishes between 
> different types:
>
> switch msg := msg.(type) {
> case ResourceUpdateMsg[Cpu]:
> m.Cpu = msg.value
> cmd := m.Progress.CpuProgress.SetPercent(m.Cpu.Usage / 100)
> return m, tea.Batch(tickCmd(updateCpuStats), cmd)
> case ResourceUpdateMsg[Mem]:
> m.Mem = msg.value
> cmd := m.Progress.MemProgress.SetPercent(m.Mem.Usage / 100)
> return m, tea.Batch(tickCmd(updateMemoryStats), cmd)
>         ...
>         }
>
> But this does not work, the case is never selected in the first update 
> function. I have to write all cases, but each case basically does the same: 
> route the message to the other function.
>
> I'm fairly new to Go and my background is Java / Kotlin. In those 
> languages I would work with inheritance.
>
> Is this possible in Go? To have a "wildcard" type parameter? If not, what 
> would be an alternative to the above?
>
>

-- 
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 [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/04e35414-1a6f-4526-81c9-bdc714647053n%40googlegroups.com.

Reply via email to