What is an idiomatic way to collect an iterator of &T into a collection of Ts?

前端 未结 2 1539
情歌与酒
情歌与酒 2020-12-19 10:55

I need to collect an iterator over a slice of &strs into a collection of &strs. The problem is that the iterator yields &&str

2条回答
  •  没有蜡笔的小新
    2020-12-19 11:31

    If T implements Copy then you can use Iterator::copied. Otherwise, if it implements Clone then you can use Iterator::cloned. Like any immutable reference, &str implements both Clone and Copy, so you can use copied:

    let hashset: HashSet<&str> = words.iter().copied().collect();
    

提交回复
热议问题