简体   繁体   English

切片数组的切片 arrays

[英]Slice of an array of slices of arrays

I have an 2D array, and I want a function to change it.我有一个二维数组,我想要一个 function 来改变它。 I don't know vectors yet, but since the array is going to have a fixed size, I don't need them.我还不知道矢量,但由于数组将具有固定大小,所以我不需要它们。 I wanted to give the function a slice of an array of slices of arrays, eg fn my_func (arr: &mut [&mut [char]]) {...} , but I don't know how to call it from my int main.我想给 function 一个 arrays 切片数组的切片,例如fn my_func (arr: &mut [&mut [char]]) {...} ,但我不知道如何从我的 int main 中调用它.

Here's an example I've been playing with.这是我一直在玩的一个例子。

fn main() {
    let mut map = [['-'; 3]; 3];

    for row in map {
        for col in row {
            print!("{} ", col);
        }

        println!("");
    }

    println!("Changing...");
    put_plus(???);

    for row in map {
        for col in row {
            print!("{} ", col);
        }

        println!("");
    }
}

fn put_plus(map: &mut [&mut [char]]) {
    map[map.len() - 1][map[map.len() - 1].len() - 2] = '+';
}

The output I expect is:我期望的 output 是:

- - - 
- - - 
- - - 
Changing...
- - -
- - -
- + -

Is there an expression to turn [[char; 3]; 3]是否有一个表达式可以将[[char; 3]; 3] [[char; 3]; 3] [[char; 3]; 3] into [[char]] so that I could put this expression instead of ??? [[char; 3]; 3][[char]]这样我就可以用这个表达式代替??? and everything works??一切正常??

Here's a version of the plus function that works for all sizes:这是适用于所有尺寸的 plus function 版本:

fn put_plus<const COUNT: usize>(map: &mut [[char; COUNT]; COUNT]) {
    map[map.len() - 1][map[map.len() - 1].len() - 2] = '+';
}

As pointed out in the comments, you just need a mutable reference on the "outer" struct.正如评论中所指出的,您只需要对“外部”结构进行可变引用。 In Rust, you don't control mutability at the "element" level.在 Rust 中,您不在“元素”级别控制可变性。 Instead, mutability of a container extends to all the elements within that container.相反,容器的可变性扩展到该容器内的所有元素。 You can't have, for example, a mutable vector containing immutable vectors or a mutable array containing immutable arrays.例如,您不能拥有包含不可变向量的可变向量或包含不可变 arrays 的可变数组。

So, just slapping a &mut to the "outside" of your array means everything in your array, including the inner arrays AND the values contained within those inner arrays, will be mutable.因此,只需将&mut拍到数组的“外部”就意味着数组中的所有内容,包括内部 arrays 和包含在这些内部 arrays 中的值,都将是可变的。

EDIT: My version of put_plus will only work for square arrays. As commenter @cafce25 points out, the outer :COUNT can be removed.编辑:我的put_plus版本仅适用于方形 arrays。正如评论者@cafce25 指出的那样,可以删除外部:COUNT That will make it more general这将使它更通用

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

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