【问题标题】:Type conversion and casting类型转换和强制转换
【发布时间】: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&lt;[usize; 2]&gt; 得到coords
  • 我投了“需要详细信息”的票,因为这个问题 IMO 没有足够的问题来正确回答。是的,里面有好几个演员。问题是,如果这些是您必须使用的数据类型,而这是您必须执行的算法——您几乎必须 进行这些转换。如果类型和行为不能改变,那么这段代码对我来说真的没有那么糟糕。像 C 语言那样进行普遍的隐式转换几乎不会改善它。具体来说,它有什么错误
  • @trentcl 我改变了问题。是的,也许这并没有错,我只是想知道一些处理数组和索引的优雅方法(没有多种类型转换)
  • @trentcl 如果您有兴趣,我只想通知您该问题已重新打开。

标签: rust casting type-conversion


【解决方案1】:

您可以使用标准库中的 TryInto 特征来抽象出溢出检查。这就是我将如何实现它:

use std::convert::TryInto;

type Pos = [usize; 2];

fn add_to_coords(coords: Pos, offset: [i8; 2]) -> Option<Pos> {
  let ni: usize = (coords[0] as i8 + direction[0]).try_into().ok()?;
  let nj: usize = (coords[1] as i8 + direction[1]).try_into().ok()?;
  [ni, nj]
}

// ...

  for [ni, nj] in directions.flat_map(|dir| add_to_coords(coords, dir)) {
    // ...
  }

// ...  

flat_map 的调用会过滤掉所有None 的返回值,以防您想知道continue 去了哪里。

【讨论】:

  • 谢谢,很好的解决方案。我还尝试为每个单元格使用早期计算的相邻坐标数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多