Skip to content

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

@igotfr

Description

@igotfr

when assigning to a variable, 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

  • 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

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

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions