文档给的 splice 用例是这样的:
let mut v = vec![1, 2, 3];
let new = [7, 8];
let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
assert_eq!(v, &[7, 8, 3]);
assert_eq!(u, &[1, 2]);
但是看了源码之后我反而糊涂了:
#[inline]
#[stable(feature = "vec_splice", since = "1.21.0")]
pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
where R: RangeBounds<usize>, I: IntoIterator<Item=T>
{
Splice {
drain: self.drain(range),
replace_with: replace_with.into_iter(),
}
}
-
self.drain(range)
改变的是 self 本身,也就是该句执行过后,内容变为[3]
,对吗? -
Splice {...}
这句是返回一个结构体, 参数replace_with
也未作用于 self。那么它是如何/何时改变 self、把[7, 8]
追加到其中,使得最后 self 变成[7, 8, 3]
?