PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, June 26, 2022

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

 June 26, 2022     compiler-errors, rust     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing