Two dimensional vectors in Rust

大兔子大兔子 提交于 2019-11-30 09:15:45

问题


Editor's note: This question predates Rust 0.1 (tagged 2013-07-03) and is not syntactically valid Rust 1.0 code. Answers may still contain valuable information.

Does anyone know how to create mutable two-dimensional vectors in Rust and pass them to function to be manipulated?

This is what I tried so far:

extern crate std;

fn promeni(rec: &[u8]) {
    rec[0][1] = 0x01u8;
}

fn main() {
    let mut rec = ~[[0x00u8,0x00u8],
        [0x00u8,0x00u8]
    ];
    io::println(u8::str(rec[0][1]));
    promeni(rec);
    io::println(u8::str(rec[0][1]));
}

回答1:


You could use the macro vec! to create 2d vectors.

fn test(vec: &mut Vec<Vec<char>>){
    vec[0][0] = 'd';
    ..//
    vec[23][79] = 'd';
}

fn main() {

    let mut vec = vec![vec!['#'; 80]; 24];

    test(&mut vec);
}



回答2:


Did you intend that all of the subarrays will have the length 2, as in this example? In that case, the type of the parameter should not be &[u8], which is a borrowed array of u8's, but rather &[[u8; 2]].



来源:https://stackoverflow.com/questions/13102786/two-dimensional-vectors-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!