Skip to content

[Language] for-else and while-else #3361

@igotfr

Description

@igotfr

when binding to a bindable, break in for and while isn't allowed, this proposal allow it using a else

  • when break is not reached, evaluates to value in else (because the condition is false? I'm not sure)

  • semantic similar to Zig

https://ziglang.org/documentation/master/#for

read the comment:

// For loops can also be used as expressions.
// Similar to while loops, when you break from a for loop, the else branch is not evaluated.
  • semantic different of Python (break and the proposed else block outputs an expression in Rust, in Python you can't do it)

Example:

fn main() {
  let result = for counter in 0..5 {
    if counter == 3 {
      break counter
    }
  } else { -7 };

  println!("The result is {result}") // 3
}
fn main() {
  let result = for counter in 0..5 {
    if counter == 90 {
      break counter
    }
  } else { -7 };

  println!("The result is {result}") // -7
}

Alternatives

https://rust-lang.github.io/rfcs/2046-label-break-value.html

Alternatives to else keyword

IDK

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions