type switch in Go
tags: learning go programming
content
- we have this code:
func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg {
switch {
case key.Matches(msg, m.keymap.Cancel):
return m, CancelMsg
}
case key.Matches(msg, someotherkey):
// do something else
}
default:
// do something
}
}
}- in this case we have a type switch:
switch msg := msg.(type)
- statement like
msg.(type)can only be used in a switch statement- you can’t do
msgType := msg.(type) - so the below code is not valid
- you can’t do
msgType := msg.(type) // this is NOT ALLOWED
if msgType != tea.KeyMsg { return m, nil }- if you wanna do
ifstatement with types, need to do go-type-assertion-1
msgType, ok := msg.(tea.KeyMsg)