php*_*p-- 5 vector mutable rust rust-obsolete
编者注:这个问题早于Rust 0.1(标记为2013-07-03),并且在语法上不是有效的Rust 1.0代码.答案可能仍包含有价值的信息.
有谁知道如何在Rust中创建可变的二维向量并将它们传递给要操作的函数?
这是我到目前为止所尝试的:
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]));
}
Run Code Online (Sandbox Code Playgroud)
您可以使用宏vec!来创建2D向量.
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);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
如果要操作的函数是您的,您可以使用辅助方法创建一个自定义结构,将向量视为 2d:
use std::fmt;
#[derive(Debug)]
pub struct Vec2d<T> {
vec: Vec<T>,
row: usize,
col: usize,
}
impl<T> Vec2d<T> {
pub fn new(vec: Vec<T>, row: usize, col: usize) -> Self {
assert!(vec.len() == row * col);
Self { vec, row, col }
}
pub fn row(&self, row: usize) -> &[T] {
let i = self.col * row;
&self.vec[i..(i + self.col)]
}
pub fn index(&self, row: usize, col: usize) -> &T {
let i = self.col * row;
&self.vec[i + col]
}
pub fn index_mut(&mut self, row: usize, col: usize) -> &mut T {
let i = self.col * row;
&mut self.vec[i + col]
}
}
impl<T: std::fmt::Debug> std::fmt::Display for Vec2d<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut str = String::new();
for i in 0..self.row {
if i != 0 {
str.push_str(", ");
}
str.push_str(&format!("{:?}", &self.row(i)));
}
write!(f, "[{}]", str)
}
}
fn main() {
let mut mv = Vec2d::new(vec![1, 2, 3, 4, 5, 6], 2, 3);
*mv.index_mut(1, 2) = 10;
println!("Display: {}", mv);
println!("Debug: {:?}", mv);
}
Run Code Online (Sandbox Code Playgroud)
关联函数new创建Vec2d,有两个主要方法(index和index_mut,因此您可以借用 immut ou mut 获得索引值)并添加一个Display特征以更好地可视化它(但它存储为Vec<>)。
| 归档时间: |
|
| 查看次数: |
6706 次 |
| 最近记录: |