Skip to content

Incorrect / incomplete information about where you can break with a value #110758

Closed
@esdevver

Description

@esdevver

Location

https://doc.rust-lang.org/std/keyword.break.html

Summary

The documentation states that "When associated with loop, a break expression may be used to return a value from that loop. This is only valid with loop and not with any other type of loop. If no value is specified, break; returns (). Every break within a loop must return the same type."

"This is only valid with loop" is not true, as one can break with a value from within a non-loop block expression.

Example:

let final_value = 'outer: {
    let value: Option<Value> = get_value();
    'inner: {
        if let Some(value) = value { break 'outer value; }
    }
    // do stuff here maybe
};

Whilst I admit the example I provide seems a little contrived, I use this practice myself.

For context, the technical reason why you can't break from say a while or for loop is because those loops are expected to yield the () type.

I believe that this part of the documentation should be amended/elaborated on as I find this pattern useful and practical for writing readable code.

Metadata

Metadata

Assignees

Labels

A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsE-easyCall for participation: Easy difficulty. Experience needed to fix: Not much. Good first issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions