std-method

slice::iter — borrow each element

A shared slice iterator yields &T. The source remains owned by its original binding; incompatible mutable access is restricted while the borrow is active. Expected stdout (not executed): 3 4 2 Common mistake: Trying to move a String out of a shared item reference.

Formal Syntax & Structure

rust syntaxrust
fn iter(&self) -> std::slice::Iter<'_, T>

Working Example

Example Snippetrust
fn main() {    let names = vec![String::from("tea"), String::from("rice")];    for name in names.iter() { println!("{}", name.len()); }    println!("{}", names.len());}
Rust Reference