當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Rust Iterator.by_ref用法及代碼示例

本文簡要介紹rust語言中 std::iter::Iterator.by_ref 的用法。

用法

fn by_ref(&mut self) -> &mut Self

借用一個迭代器,而不是使用它。

這對於允許應用迭代器適配器同時仍保留原始迭代器的所有權很有用。

例子

基本用法:

let mut words = vec!["hello", "world", "of", "Rust"].into_iter();

// Take the first two words.
let hello_world: Vec<_> = words.by_ref().take(2).collect();
assert_eq!(hello_world, vec!["hello", "world"]);

// Collect the rest of the words.
// We can only do this because we used `by_ref` earlier.
let of_rust: Vec<_> = words.collect();
assert_eq!(of_rust, vec!["of", "Rust"]);

相關用法


注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 std::iter::Iterator.by_ref。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。