简体   繁体   English

如何通过引用传递拥有的数组

[英]How to pass an owned array by reference

I'm just playing around with rust for the first time, implementing quicksort, and I'm stuck on references to dynamically sized arrays (I had no problem with fixed size arrays). 我只是第一次玩弄锈,实现了快速排序,而且还停留在对动态大小数组的引用上(固定大小数组没有问题)。

I would like to have an indefinitely sized array of integers to sort, which I gather I can create with something like: 我希望有一个不确定大小的整数数组来排序,我可以用以下类似的方式创建该数组:

let array = ~[1,2,3,4,3,2,1];

However, I am not sure how I can pass this by reference into a partition function. 但是,我不确定如何通过引用将其传递给分区函数。

partition ( a : &mut ~[uint], p: uint, i: uint) {
     // partition a, in place
}

As soon as I try to reorder any elements in a, the compiler complains: 一旦我尝试对a中的任何元素重新排序,编译器就会抱怨:

error: cannot assign to immutable vec content a[..] 错误:无法分配给不变的vec内容a[..]

You should use a mutable borrow of the vector rather than a mutable borrow of a pointer to a vector, so you should get rid of that ~ pointer in the type of your partition function. 您应该使用向量的可变借用,而不是向量的指针的可变借用,因此您应该在分区函数的类型中摆脱该~指针。 For example: 例如:

fn partition(_: &mut [uint], _: uint, _: uint) { }

fn main() {
    let mut array = ~[1, 2, 3, 4, 3, 2, 1];
    partition(array, 0, 0);
}

Notice that array is automatically passed as a mutable borrowed pointer. 请注意, array作为可变的借入指针自动传递。

If you use a Vec instead , then you need to explicitly create a slice: 如果改用Vec ,则需要显式创建一个切片:

fn partition(_: &mut [uint], _: uint, _: uint) { }

fn main() {
    let mut array = vec!(1, 2, 3, 4, 3, 2, 1);
    partition(array.as_mut_slice(), 0, 0);
}

Both code snippets should compile on the latest Rust (from tip). 这两个代码片段都应在最新的Rust上编译(摘自技巧)。

With 0.10 the language is undergoing some changes to array types at the moment, so things are a bit messy. 使用0.10时,该语言目前正在对数组类型进行一些更改,因此情况有些混乱。 Vec<T> is Rust's intended dynamically sized array type. Vec<T>是Rust预期的动态大小的数组类型。

let vec = vec!(1u,2,3,4,3,2,1);

partition ( a : &mut Vec<uint>, p: uint, i: uint) {
     // partition a, in place
}

Note that indexing of a Vec via brackets is currently only possible by first calling .as_slice() or .as_mut_slice() on it since the respective traits are not yet implemented. 请注意,目前只有通过首先在其上调用.as_slice()或.as_mut_slice()才能通过括号对Vec进行索引,因为尚未实现各个特征。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM