Extend Feeds A Custom Collection From Any Iterator
Implement Extend for a custom collection so extend accepts any IntoIterator batch; the method takes &mut self and never seizes ownership of the collection.
Code
#[derive(Debug, Default)]
struct SampleSet {
names: Vec<String>,
}
// Extend:把"整批注入"变成集合的一等能力,任何 IntoIterator 都能灌入
impl Extend<String> for SampleSet {
// 唯一必须提供的方法:逐个消费迭代器元素
fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) {
for name in iter {
self.names.push(name);
}
}
}
fn main() {
let mut set = SampleSet::default();
set.names.push(String::from("ada"));
// 数组按值 IntoIterator(2021 edition)
set.extend(["grace", "linus"].map(String::from));
println!("{:?}", set);
// Vec、转换后的数组同样满足 IntoIterator:调用点零改动
set.extend(vec![String::from("kay")]);
set.extend(["melon", "pear"].map(|s| s.to_uppercase()));
println!("{:?}", set);
// &mut self:extend 不夺取集合所有权,迭代中途也能继续喂
set.extend(["nolan", "wirth"].map(String::from));
println!("count: {}", set.names.len());
}What the code does
Extend Feeds A Custom Collection From Any Iterator keeps everything in the functions extend and main.
Repetition is confined to for name in iter — the rest of the file is straight-line.
Applying it
Running the file prints labeled results such as count: — each operation’s effect is visible in the output.
main calls 1 helper in sequence: extend.
Statements that matter
fn extend<T: IntoIterator<Item = String>>(&mut self, iter: T) {
for name in iter {
self.names.push(name);
}
}
set.extend(["melon", "pear"].map(|s| s.to_uppercase()));
set.extend(["grace", "linus"].map(String::from));
Interactive Tools for This Topic
FAQ
- What does Extend Feeds A Custom Collection From Any Iterator print when run?
- Invoke the file as-is — the `count:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.