如何将数据从切片写入同一个切片? [英] How can I write data from a slice to the same slice?

查看:54
本文介绍了如何将数据从切片写入同一个切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将切片的末尾写入同一切片的顶部.

I want to write the end of a slice to the top of the same slice.

let mut foo = [1, 2, 3, 4, 5];

foo[..2].copy_from_slice(&[4..]); // error: multiple references to same data (mut and not)

assert!(foo, [4, 5, 3, 4, 5]);

我看过如何操作在 Rust 数组的 2 个可变切片上

我想要最大的性能(例如,通过使用 foo.as_ptr()).

I want the maximum performance possible (for example, by using foo.as_ptr()).

推荐答案

我找到了一个更好的方法来做我想做的事:

I found a better way to do what I want:

fn main() {
    let mut v = [1, 2, 3, 4, 5, 6];

    // scoped to restrict the lifetime of the borrows
    {
        let (left, right) = v.split_at_mut(3);
        assert!(left == [1, 2, 3]);
        assert!(right == [4, 5, 6]);
        for (l, r) in left.iter_mut().zip(right) {
            *l = *r;
        }
    }

    assert!(v == [4, 5, 6, 4, 5, 6]);
}

这篇关于如何将数据从切片写入同一个切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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