switch without statement

tags: learning go programming

content

  • we have:
func (m *Model) Update(msg tea.Msg) (Model, tea.Cmd) {
	keyMsg, ok := msg.(tea.KeyMsg)
	if !ok {
		return m, nil
	}
	switch {
	case key.Matches(keyMsg, SomeKey):
		// do something
	default:
		// do something
	}
	return m, nil
}
  • in this code, there’s nothing after the switch
  • what is it switching on then??
    • it’s not switching on anything!
    • it’s the same as switch true!
  • because key.Matches() returns a bool, that’s what’s being switched on
    • any true from key.Matches(keyMsg, SomeKey) will be the code path
  • it’s the same as:
keyMsg, ok := msg.(tea.KeyMsg)
if !ok {
	return m, nil
}
if key.Matches(keyMsg, SomeKey) {
	// do something
	return
}
if key.Matches(keyMsg, SomeOtherKey) {
	// do something
	return
}
// do something
return

up

down

reference