Movatterモバイル変換


[0]ホーム

URL:


for

Keywordfor 

Source
Expand description

Iteration within, trait implementation withimpl, orhigher-ranked trait bounds(for<'a>).

Thefor keyword is used in many syntactic locations:

  • for is used in for-in-loops (see below).
  • for is used when implementing traits as inimpl Trait for Type (seeimpl for more infoon that).
  • for is also used forhigher-ranked trait bounds as infor<'a> &'a T: PartialEq<i32>.

for-in-loops, or to be more precise, iterator loops, are a simple syntactic sugar over a commonpractice within Rust, which is to loop over anything that implementsIntoIterator until theiterator returned by.into_iter() returnsNone (or the loop body usesbreak).

foriin0..5{println!("{}", i *2);}foriinstd::iter::repeat(5) {println!("turns out {i} never stops being 5");break;// would loop forever otherwise}'outer:forxin5..50{foryin0..10{ifx == y {break'outer;        }    }}

As shown in the example above,for loops (along with all other loops) can be tagged, usingsimilar syntax to lifetimes (only visually similar, entirely distinct in practice). Giving thesame tag tobreak breaks the tagged loop, which is useful for inner loops. It is definitelynot a goto.

Afor loop expands as shown:

forloop_variableiniterator {    code()}
{letresult =matchIntoIterator::into_iter(iterator) {mutiter =>loop{matchiter.next() {None=>break,Some(loop_variable) => { code(); },            };        },    };    result}

More details on the functionality shown can be seen at theIntoIterator docs.

For more information on for-loops, see theRust book or theReference.

See also,loop,while.


[8]ページ先頭

©2009-2026 Movatter.jp