如何从geo_types检查几何类型

问题描述 投票:0回答:1

我是 Rust 新手,我仍在努力解决借用概念与 geo_types 板条箱中的

TryFrom
函数的结合。

我基本上想根据实际的

Geometry
类型做不同的事情:

use geo_types::{Geometry, Point, LineString};

fn some_func(g : Geometry<f64>) {
    if let Ok(p) = Point::try_from(g) {
        print!("POINT");
    } else if let Ok(ls) = LineString::try_from(g) { 
        print!("LINESTRING");
    } else {
        print!("UNKNOWN");
    }
}

但是失败了:

error[E0382]: use of moved value: `g`
 --> src/main.rs:7:49
  |
4 | fn some_func(g : Geometry<f64>) {
  |              - move occurs because `g` has type `Geometry`, which does not implement the `Copy` trait
5 |     if let Ok(p) = Point::try_from(g) {
  |                                    - value moved here
6 |         print!("POINT");
7 |     } else if let Ok(ls) = LineString::try_from(g) { 
  |                                                 ^ value used here after move
  |
help: consider cloning the value if the performance cost is acceptable
  |
5 |     if let Ok(p) = Point::try_from(g.clone()) {
  |                                     ++++++++

所以我正在更改函数以获取几何参考:

fn some_func(g : &Geometry<f64>)

但是失败了:

特征

From<&Geometry>
未针对
geo_types::Point<_>

实现

我尝试的下一步是取消引用几何图形:

Point::try_from(*g)

但这也失败了:

无法移出共享引用后面的

*g
发生移动是因为
*g
的类型为
Geometry
,它没有实现
Copy
特征

那么我该怎么做才能让这段代码正常工作,或者我该如何以不同的方式做到这一点?

rust geometry borrow-checker
1个回答
0
投票

请注意,Geometry是一个枚举,因此您应该使用模式匹配来检查您正在使用哪种变体。

pub enum Geometry<T: CoordNum = f64> {
    Point(Point<T>),
    Line(Line<T>),
    LineString(LineString<T>),
    Polygon(Polygon<T>),
    MultiPoint(MultiPoint<T>),
    MultiLineString(MultiLineString<T>),
    MultiPolygon(MultiPolygon<T>),
    GeometryCollection(GeometryCollection<T>),
    Rect(Rect<T>),
    Triangle(Triangle<T>),
}

所以你可以重写你的函数如下:

use geo_types::{Geometry, Point, LineString};

fn some_func(g : Geometry<f64>) {

    match g {
        Geometry::Point(_) => print!("POINT"),
        Geometry::LineString(_) => print!("LINESTRING"),
        // It's not really unknown, because there are other enum variants,
        // but I left it to not change your original (intended?) bahavior.
        _ -> print!("UNKNOWN")
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.