Is there a difference between slicing and an explicit reborrow when converting Strings to &strs?

后端 未结 2 1299
悲哀的现实
悲哀的现实 2021-01-17 14:29

Are the following two examples equivalent?

Example 1:

let x = String::new();
let y = &x[..];

Example 2:

let x =         


        
2条回答
  •  耶瑟儿~
    2021-01-17 14:58

    They are completely the same for String and Vec.

    The [..] syntax results in a call to Index::index() and it's not just sugar for [0..collection.len()]. The latter would introduce the cost of bound checking. Gladly this is not the case in Rust so they both are equally fast.


    Relevant code:

    • index of String
    • deref of String
    • index of Vec (just returns self which triggers the deref coercion thus executes exactly the same code as just deref)
    • deref of Vec

提交回复
热议问题