rust 在循环的if语句中创建示例并使用它们

wtlkbnrh  于 2023-01-17  发布在  其他
关注(0)|答案(1)|浏览(101)

我正在尝试解析一个包含点和多边形信息的多行字符串。
我面临的问题是Rust中的所有权问题。在C#或C++这样的语言中,我可以声明一个变量,然后在某个点示例化它,然后在以后使用该变量。但在Rust中,这会导致所有权问题。
我该怎么处理拉斯特的这种情况?

fn main() {
    // Point struct
    struct Point {
        x: f64,
        y: f64,
    }

    // Polygon struct that has points
    struct Polygon {
        points: Vec<Point>,
    }

    // Implement the Polygon struct
    impl Polygon {
        fn new() -> Self {
            Self { points: Vec::new() }
        }
    }

    // Surface struct that has polygons
    struct Surface {
        polygons: Vec<Polygon>,
    }

    // Implement the Surface struct
    impl Surface {
        fn new() -> Self {
            Self { polygons: Vec::new() }
        }
    }

    // string polygons
    let strs = "
    SB
        PB
            PT 350 130
            PT 350 170
            PT 450 170
        PE 
        PB
            PT 370 150
            PT 370 160
            PT 430 160
        PE
    SE";

    let mut surface = Surface::new();
    let mut poly:Polygon = Polygon::new();

    let lines: Vec<&str> = strs.lines().collect();
    for line in lines.iter().map(|s| s.trim()) {
        
        if line == "SB" {
            surface = Surface::new();
        } else if line == "PB" {
            poly = Polygon::new();
            surface.polygons.push(poly);
        } else if line.starts_with("PT") {
            let mut parts = line.split_whitespace();
            parts.next(); // skip "PT"
            let x: f64 = parts.next().unwrap().parse().unwrap();
            let y: f64 = parts.next().unwrap().parse().unwrap();
            let pt = Point { x, y };

            poly.points.push(pt); // <-- Error
            // surface.polygons.last_mut().unwrap().points.push(pt); // <-- OK
        }
    }

    // Print the Surface polygons points
    for poly in surface.polygons.iter() {
        println!("PB");
        for point in poly.points.iter() {
            println!("\tx: {}, y: {}", point.x, point.y);
        }
        println!("PE");
    }
}
error[E0382]: borrow of moved value: `poly`
  --> src/main.rs:65:13
   |
48 |     let mut poly:Polygon = Polygon::new();
   |         -------- move occurs because `poly` has type `Polygon`, which does not implement the `Copy` trait
...
57 |             surface.polygons.push(poly);
   |                                   ---- value moved here, in previous iteration of loop
...
65 |             poly.points.push(pt); // <-- Error
   |             ^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
ar5n3qh5

ar5n3qh51#

你的line == "PB"代码有两个问题,第一个问题是你删除了所有在poly中收集的数据,创建一个新的,然后将其移动到surface.polygons中,另一个问题是如果这是第一个多边形,那么在== "PB"上的测试需要一个测试,所以Rust刚刚为你捕获了一个bug!
请尝试以下方法:

//...
} else if line == "PE" {
    surface.polygons.push(poly);
    poly = Polygon::new();
}
//...

相关问题