将切片附加到向量的惯用方法是什么? [英] What's the idiomatic way to append a slice to a vector?

查看:25
本文介绍了将切片附加到向量的惯用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 &[u8] 片段,我想以最少的复制将其附加到 Vec.以下是我知道有效的两种方法:

I have a slice of &[u8] and I'd like to append it to a Vec<u8> with minimal copying. Here are two approaches that I know work:

let s = [0u8, 1u8, 2u8];
let mut v = Vec::new();
v.extend(s.iter().map(|&i| i));
v.extend(s.to_vec().into_iter()); // allocates an extra copy of the slice

在 Rust stable 中是否有更好的方法来做到这一点?(rustc 1.0.0-beta.2)

Is there a better way to do this in Rust stable? (rustc 1.0.0-beta.2)

推荐答案

有一种方法可以做到这一点:Vec::extend_from_slice

There's a method that does exactly this: Vec::extend_from_slice

示例:

let s = [0u8, 1, 2];
let mut v = Vec::new();
v.extend_from_slice(&s); 

这篇关于将切片附加到向量的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆