rust-lang / rust-lang/rfcs

[Language] for-else and while-else

Open
#3,361 26 comments 42 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

View all comments

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

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading the proposal in issue #3361, including its Zig reference and the alternative RFC 2046 on labeled break values. Clarify the semantics of for-else and while-else, especially break values and when the else expression runs. Done means the behavior and alternatives are resolved well enough to specify an RFC.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Quiet
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.