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

标签 rust rust-tokio

我想解析来自 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 中存储不变类型变量”。

最佳答案

  1. 首选不变类型是 &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.

使用向下转换测试类型的示例:

if let Some(string) = thisValue.downcast_ref::<String>() {
    println!("String ({}): {}", string.len(), string);
}
  • 盒装
  • Box强制堆分配(如果需要)。此策略也包含在内,因此您可以了解 &dyn Any 如何与 Boxed

    配合使用

    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 这不起作用,但它是标题问题的答案。

    使用 Boxeddowncast 函数测试类型的示例:

    if let Ok(string) = thisValue.downcast::<String>() {
        println!("String ({}): {}", string.len(), string);
    }
    

    关于postgresql子问题

    根据原帖,

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

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

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

    相关文章:

    macros - 如何获取宏重复单元素的索引

    multithreading - 使用Mutex防止同时处理同一类型时进行多线程列表迭代

    rust - 你如何在 Rust 中创建一个具有需要生命周期的特征的泛型函数?

    rust - 究竟什么被认为是对库箱的重大改变?

    enums - 带有 if let 枚举匹配的条件编译,其中包含一个项目

    rust - 如何处理 `unused futures::MapErr` 警告?

    asynchronous - 我将如何在 future 流中为每个项目发出 TcpClient 请求?

    rust - MQTT 与 tokio 的连接

    rust - Hyper 服务器在未来返回 Async::NotReady 时断开连接

    multithreading - Rust多线程异步Websocket服务器