Sunday, June 26, 2022

[FIXED] Why slice could call into_iter directly and do not abort?

Issue

I am a Rust newbie, I tested following code and got a question. Is type of slice [T]?If so, [T] is unsized, but it passed when I compiled the code. Why is that?

#[test]
fn test_scilce(){
    let v = vec!['a', 'b', 'v'];
    let slice = (v[1..3]).into_iter();
    // let s: String = slice.collect();
    println!("{:?}", slice);
    println!("{:?}", v);
}

Solution

Since [T]::into_iter(self) doesn't exist, but [T]::into_iter(&self) does, the compiler inserts the missing reference and treats (v[1..3]).into_iter() as (&v[1..3]).into_iter(). That is in turn the same as (&v[1..3]).iter() and gives out references to the elements of the vector. (There is even a clippy lint warning you of using into_iter() on slice or other references.)

The same auto-referencing mechanism is what allows you to write v.len() instead of the "correct" (&v).len(), despite Vec::len taking &self.



Answered By - user4815162342
Answer Checked By - Cary Denson (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.