我想解析来自 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 Any
和TypeId::of::<TypeHere>() == thisValue.type_id()
?
在这种情况下,get
该API的功能tokio-postgresql
使用泛型并且不返回装箱值。因此在这种情况下我可能需要使用columns()
确定 Rust 类型并使用单独的函数来调用 get
具有不同的变量类型。
无论我用来提出标题问题的具体细节如何,总体问题仍然需要回答“如何在 Rust 中存储不变类型变量”。
最佳答案
- 首选不变类型是
&dyn any
声明:
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 这不起作用,但它是标题问题的答案。
使用 Boxed
的 downcast
函数测试类型的示例:
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/