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?