rust - 是否可以使用类型注释进行解构赋值?

标签 rust

总体问题是如何使用类型注释进行嵌套解构赋值。我将两个 f32 值相乘,但我不确定如果倍数溢出会发生什么。因此,我想将它们分配为 f64 值以防止溢出。

这个例子是从 Rust By Example 的章节 structures: 稍微修改而来的。

struct Point {
    x: f32,
    y: f32,
}

struct Rectangle {
    p1: Point,
    p2: Point,
}

fn area(rect: Rectangle) -> f64 {
    // Here's where I'd like have type annotations
    // while doing destructuring assignment:
    let Rectangle {
        p1: Point { x: x1, y: y1 },
        p2: Point { x: x2, y: y2 },
    } = rect;

    ((x2 - x1) * (y2 - y1)).abs() as f64
}

最佳答案

在类型解构期间不能执行转换。这是因为您无法注释将包含在您正在解构的类型中的类型,因此它不取决于您,而是取决于正在解构的类型。例如:

struct Point {
    x: f32,
    y: f32,
}
let myOtherPoint = Point { x: 0, y: 0 };
let Point {x, y} = myOtherPoint;

xy 的类型由Point 类型定义。另一方面,对于元组和数组,这可以更改:

fn main() {
    let [x, y, z]: [f32; 3] = [1.2, 2.3, 3.4];
    let (x, y, z): (usize, f32, String) = (1, 2.3, "3.4".into());
}

这主要是因为在编写函数签名时元组需要类型注释:

fn foo((a, b, c): (usize, f32, String)) {}

但这只是因为元组本身不是命名类型,所以需要通过注释类型来命名元组。另一方面,structenum 是有名字的,因此是可解构的。


正文中描述的具体问题的解决方案,而不是标题:
使用带有阴影的单独变量以保持可用性。另请注意,浮点类型(f32f64)不能溢出(They have an infinity),只能溢出整数([u, i][size, 8、16、32、64、128])。

fn area(x: Rectangle) -> f64 {
    // Here's where I'd like have type annotations
    // while doing destructuring assignment:
    let Rectangle {
        p1: Point { x: x1, y: y1 },
        p2: Point { x: x2, y: y2 },
    } = rect;

    let (x1, x2, y1, y2) = (x1 as f64, x2 as f64,
                            y1 as f64, y2 as f64);

    ((x2 - x1) * (y2 - y1)).abs()
}

关于rust - 是否可以使用类型注释进行解构赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56193397/

相关文章:

rust - 如何实现任何可变性的特征?

rust - GraphicsMagick FFI 问题

string - 如何为 Vec<u8> 实现修剪?

rust - 如何启用 Rust "crate feature"?

collections - 如何在迭代集合的同时修改集合?

rust - 有条件地迭代几个可能的迭代器之一

rust - 有没有比匹配更好的方法来访问相同类型的枚举值?

rust - 闭包不能返回引用吗?

rust - 有没有办法让结构体包含可能不再有效的引用?

rust - 如何解构元组以使绑定(bind)可变?