gpt4 book ai didi

rust - 如何在 Rust 中存储不变类型变量

转载 作者:行者123 更新时间:2023-12-03 11:48:18 25 4
gpt4 key购买 nike

我想解析来自 tokio-postgresql 的一行数据中每个值的类型
这是从 postgresql 获取一行数据的单个值的示例:

...
let rows = client
.query("select * from ExampleTable;")
.await?;

// This is how you read a string if you know the first column is a string type.
let thisValue: &str = rows[0].get(0);
在此示例中,在设计时已知第一列中的类型是字符串,因此 thisValue 的类型是是 &str .我想接受一个不变的类型。
我打算使用 std::any::type_name::<T>()导出 thisValue 中的类型名称然后使用条件逻辑(if/switch)根据类型以不同的方式处理这些数据。
有没有一种不变的方式来在 Rust 中存储变量?将 std::any::type_name::<T>()处理那个变量?还有另一种方法来“装箱”变量吗?
我了解 std::any::type_name::<T>()正在使用一种泛型接口(interface)。对我来说,这意味着它可能是一种编译时策略,而不是运行时策略。所以我怀疑我正在研究的方式是否可行,但我希望我走在正确的轨道上,只需要最后一 block :不变类型。
我应该使用 &dyn AnyTypeId::of::<TypeHere>() == thisValue.type_id() ?
在这种情况下, get此 API 的功能 tokio-postgresql使用泛型并且不返回装箱值。因此在这种情况下,我可能需要使用 columns()确定 Rust 类型并使用单独的函数调用 get具有不同的变量类型。
总体问题仍然需要回答“如何在 Rust 中存储一个不变的类型变量”,不管我曾经问过标题问题的具体细节。

最佳答案

  • 首选的不变类型是 &dyn any

  • &dyn any : any是特征, dyn表示特征的类型。
    声明:
    let thisValue: &dyn Any = rows[0].get(0); //This works if tokio-postgresql returned a "dyn any" type, which it doesn't
    测试引用什么类型的示例:
    TypeId::of::<String>() == thisValue.type_id() //type checking using TypeId of boxed value.
    使用 downcast 测试类型的示例:
    if let Some(string) = thisValue.downcast_ref::<String>() {
    println!("String ({}): {}", string.len(), string);
    }
  • 盒装

  • Box强制堆分配(如有必要)。这个策略也包括在内,所以你可以看到 &dyn AnyBoxed 合作 dyn Any 的“装箱”值是不变的:
    let thisValue: Boxed<dyn Any> = rows[0].get(0);  //This works if tokio-postgresql returned a "dyn any" type, which it doesn't
    在这种情况下,所使用的 API 需要通用推理,因此对于 tokio-postgresql 这将不起作用,但它是标题问题的答案。
    使用 downcast 测试类型的示例 Boxed的功能:
    if let Ok(string) = thisValue.downcast::<String>() {
    println!("String ({}): {}", string.len(), string);
    }
    关于postgresql子问题
    根据原帖,

    In this situation, the get function of this API tokio-postgresql usesgenerics and doesn't return a boxed value. Therefore in this situationI may need to use columns() to determine the Rust type and the useseparate functions to call get with different variables types.


    所以这个答案解决了这个问题,虽然它不适用于 tokio-postgresql API,但它让您了解您想要查找/构建/等待的 API 类型。

    关于rust - 如何在 Rust 中存储不变类型变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62749560/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com