Skip to content

Feature Request - Support if, switch, and select as Expressions #47

@YlguYtrid

Description

@YlguYtrid

Summary
Currently, Dingo supports match as a first-class expression (excellent design!), but if, switch, and select remain statement-only constructs. This proposal requests extending expression semantics to these control structures to align with modern language patterns and improve composability.

Motivation

  • Consistency: match is already an expression; extending this pattern to other control flows creates a cohesive mental model.
  • Conciseness: Eliminates boilerplate temporary variables and multi-line assignments.
  • Expressiveness: Enables direct use in assignments, function arguments, struct fields, and nested contexts.
  • Modern Practice: Mirrors patterns in Rust (if/match expressions), Kotlin (when), Scala, Zig, and others where control flowis computation.

Current Limitation (Example)

// Verbose workaround required today
var status string
if x > 0 {
    status = "positive"
} else if x  0 { "positive" }
    else if x < 0 { "negative" }
    else { "zero" }
)

Additional Examples

switch as expression:
label := switch code {
case 200: "OK"
case 404: "Not Found"
default: "Unknown"
}

select as expression (channel context):

msg := select {
case v := <-ch1: format(v)
case v := <-ch2: sanitize(v)
default: "timeout"
}

Key Requirements

  1. All branches must yield values of a consistent, inferable type (enforced at compile time).
  2. Block bodies in branches should return the value of their final expression (like match).
  3. Maintain existing statement semantics where expression context isn't used (backward compatible).
  4. Clear error messages for type mismatches across branches.

Why This Matters

  • Reduces cognitive load: users won’t need to remember which constructs are "expression-capable."
  • Enables functional-style patterns critical for metaprogramming (e.g., generating config values inline during codegen).
  • Strengthens Dingo’s position as a modern, ergonomic meta-language for Go ecosystems.

Optional Consideration
If full block support adds complexity initially, a minimal viable step could be:"Allow single-expression branches (no blocks) for if/switch/select in expression position, matching match's current capabilities."

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2-mediumMedium priority - quality of lifediscussionOpen conversation to listen to opinions.enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions