【发布时间】:2021-01-24 07:56:57
【问题描述】:
我是 Rust 的初学者。我有简单的脚本,但我必须使用太多的类型转换。 脚本要点:在矩阵中搜索具有相同值的相邻单元簇(使用队列https://en.wikipedia.org/wiki/Flood_fill的洪水填充算法)。
这是完整的代码:
fn find_clusters(playground: [[u8; SIZE]; SIZE]) -> Vec<Cluster> {
let directions_cluster: [[i8; 2]; 4] = [[0, 1], [0, -1], [1, 0], [-1, 0]];
let mut clusters: Vec<Cluster> = Vec::new();
let mut queue: Vec<[usize; 2]> = Vec::new();
let mut marked_cells: [[u8; SIZE]; SIZE] = [[0; SIZE]; SIZE];
for i in 0..SIZE {
for j in 0..SIZE {
if marked_cells[i][j] == 1 { continue; }
let code = playground[i][j];
let mut cluster = Cluster::new();
queue.push([i, j]);
marked_cells[i][j] = 1;
while !queue.is_empty() {
let coords = queue.pop().unwrap();
cluster.coords.push(coords);
for direction in &directions_cluster {
let check_i = coords[0] as i8 + direction[0];
if check_i < 0 || check_i as usize >= SIZE {continue;}
let check_j = coords[1] as i8 + direction[1];
if check_j < 0 || check_j as usize >= SIZE {continue;}
let ni = check_i as usize;
let nj = check_j as usize;
if playground[ni][nj] == code && marked_cells[ni][nj] == 0 {
queue.push([ni, nj]);
marked_cells[ni][nj] = 1;
}
}
}
if cluster.coords.len() >= 5 {
cluster.code = code;
clusters.push(cluster);
}
};
};
return clusters;
}
但我不喜欢这部分:
for direction in &directions_cluster {
let check_i = coords[0] as i8 + direction[0];
if check_i < 0 || check_i as usize >= SIZE {continue;}
let check_j = coords[1] as i8 + direction[1];
if check_j < 0 || check_j as usize >= SIZE {continue;}
let ni = check_i as usize;
let nj = check_j as usize;
if playground[ni][nj] == code && marked_cells[ni][nj] == 0 {
queue.push([ni, nj]);
marked_cells[ni][nj] = 1;
}
}
我什至不得不定义额外的变量(check_i、check_j),以便以后每次都不要对 ni/nj 使用强制转换。 在可能的情况下最好的类型转换方法是什么?
【问题讨论】:
-
我建议你从质疑你的声明开始,例如,如果你总是可以将它的值转换为
i8,你为什么要声明coords: [usize; 2]?为什么要像这样混合符号? -
如果我没记错的话,我们可以只使用
usize作为数组的索引。我从坐标的一些queue: Vec<[usize; 2]>得到coords -
我投了“需要详细信息”的票,因为这个问题 IMO 没有足够的问题来正确回答。是的,里面有好几个演员。问题是,如果这些是您必须使用的数据类型,而这是您必须执行的算法——您几乎必须 进行这些转换。如果类型和行为不能改变,那么这段代码对我来说真的没有那么糟糕。像 C 语言那样进行普遍的隐式转换几乎不会改善它。具体来说,它有什么错误?
-
@trentcl 我改变了问题。是的,也许这并没有错,我只是想知道一些处理数组和索引的优雅方法(没有多种类型转换)
-
@trentcl 如果您有兴趣,我只想通知您该问题已重新打开。
标签: rust casting type-conversion