Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Foreach loop
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Rust === {{Main|Rust (programming language)}} The <code>for</code> loop has the structure <syntaxhighlight lang="rust" inline>for <pattern> in <expression> { /* optional statements */ }</syntaxhighlight>. It implicitly calls the [https://doc.rust-lang.org/std/iter/trait.IntoIterator.html <code>IntoIterator::into_iter</code>] method on the expression, and uses the resulting value, which must implement the [https://doc.rust-lang.org/std/iter/trait.Iterator.html <code>Iterator</code>] trait. If the expression is itself an iterator, it is used directly by the <code>for</code> loop through an [https://doc.rust-lang.org/std/iter/trait.IntoIterator.html#impl-IntoIterator-25 implementation of <code>IntoIterator</code> for all <code>Iterator</code>s] that returns the iterator unchanged. The loop calls the <code>Iterator::next</code> method on the iterator before executing the loop body. If <code>Iterator::next</code> returns <code>[[option type|Some(_)]]</code>, the value inside is assigned to the [[pattern matching|pattern]] and the loop body is executed; if it returns <code>None</code>, the loop is terminated. <syntaxhighlight lang="Rust"> let mut numbers = vec![1, 2, 3]; // Immutable reference: for number in &numbers { // calls IntoIterator::into_iter(&numbers) println!("{}", number); } for square in numbers.iter().map(|x| x * x) { // numbers.iter().map(|x| x * x) implements Iterator println!("{}", square); } // Mutable reference: for number in &mut numbers { // calls IntoIterator::into_iter(&mut numbers) *number *= 2; } // prints "[2, 4, 6]": println!("{:?}", numbers); // Consumes the Vec and creates an Iterator: for number in numbers { // calls IntoIterator::into_iter(numbers) // ... } // Errors with "borrow of moved value": // println!("{:?}", numbers); </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)