What I do
- •Guide the implementation of the Elm Architecture in Go.
- •Enforce the "State Machine" pattern for multi-step TUIs.
- •Prevent common concurrency anti-patterns (e.g., manual goroutines instead of tea.Cmd).
Best Practices
- •Event Loop Speed: Keep
Update()andView()pure and fast. Offload ANY I/O (network, file system, database) to atea.Cmd. - •State Machine: For multi-stage apps, use an
enumforsessionStateand aswitchinUpdateandViewto delegate to sub-models. - •Avoid Manual Concurrency: Never start a goroutine inside
Update. Usetea.Cmdand send messages back to the loop. - •Window Resizing: Always handle
tea.WindowSizeMsgto dynamically update component dimensions.
Example: State Delegation
go
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
// Validate that dimensions are positive before assigning
if msg.Width > 0 && msg.Height > 0 {
m.width, m.height = msg.Width, msg.Height
}
}
// Delegate to active component
switch m.state {
case stateList:
return m.updateList(msg)
case stateForm:
return m.updateForm(msg)
}
return m, nil
}