如何惯用地复制切片? [英] How to idiomatically copy a slice?

查看:61
本文介绍了如何惯用地复制切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Go 中,复制切片是标准操作,如下所示:

In Go, copying slices is standard-fare and looks like this:

# It will figure out the details to match slice sizes
dst = copy(dst[n:], src[:m])

在 Rust 中,我找不到与替换类似的方法.我想出的东西看起来像这样:

In Rust, I couldn't find a similar method as replacement. Something I came up with looks like this:

fn copy_slice(dst: &mut [u8], src: &[u8]) -> usize {
    let mut c = 0;
    for (&mut d, &s) in dst.iter_mut().zip(src.iter()) {
        d = s;
        c += 1;
    }
    c
}

不幸的是,我遇到了无法解决的编译错误:

Unfortunately, I get this compile-error that I am unable to solve:

error[E0384]: re-assignment of immutable variable `d`
 --> src/main.rs:4:9
  |
3 |     for (&mut d, &s) in dst.iter_mut().zip(src.iter()) {
  |               - first assignment to `d`
4 |         d = s;
  |         ^^^^^ re-assignment of immutable variable

如何设置d?有没有更好的方法来复制切片?

How can I set d? Is there a better way to copy a slice?

推荐答案

是的,使用方法 clone_from_slice(),它对实现Clone的任何元素类型都是通用的.

Yes, use the method clone_from_slice(), it is generic over any element type that implements Clone.

fn main() {
    let mut x = vec![0; 8];
    let y = [1, 2, 3];
    x[..3].clone_from_slice(&y);
    println!("{:?}", x);
    // Output:
    // [1, 2, 3, 0, 0, 0, 0, 0]
}

目标 x 要么是一个 &mut [T] 切片,要么是任何解除引用的东西,比如可变的 Vec代码>矢量.您需要对目标和源进行切片,使它们的长度匹配.

The destination x is either a &mut [T] slice, or anything that derefs to that, like a mutable Vec<T> vector. You need to slice the destination and source so that their lengths match.

从 Rust 1.9 开始,您还可以使用 copy_from_slice().这以相同的方式工作,但使用 Copy 特性而不是 Clone,并且是 memcpy 的直接包装器.如果适用,编译器可以优化 clone_from_slice 以等效于 copy_from_slice,但它仍然有用.

As of Rust 1.9, you can also use copy_from_slice(). This works the same way but uses the Copy trait instead of Clone, and is a direct wrapper of memcpy. The compiler can optimize clone_from_slice to be equivalent to copy_from_slice when applicable, but it can still be useful.

这篇关于如何惯用地复制切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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