在Rust中,如何检查泛型参数是否为特定类型并将其强制转换为特定类型 [英] In Rust, how check if a generic parameter is of a specific type and cast to it
本文介绍了在Rust中,如何检查泛型参数是否为特定类型并将其强制转换为特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有几种实现特征(关系)的类型.我需要在它们之间传递数据,例如sql中的INSERT INTO FROM SELECT
.
I have several types that implement a trait (Relation). I need to pass data between them, like INSERT INTO FROM SELECT
from sql.
但是,有时我会移动来自相同类型的数据,这意味着我可以使用更直接的方式:
However, some times I will move data that is coming from the same type, meaning I could use a more direct way:
impl Relation for BTree {
fn new_from<R: Relation>(names: Schema, of: R) -> Self {
if of is Btree { //How do this
//Fast path
cast(of as Btree).clone() //And this
} else {
//Generic path
}
}
}
推荐答案
What you are trying to do should be possible using std::any
. I imagine it would look something like this:
use std::any::Any;
trait Trait {
fn foo<T: Trait + Any>(of: T) -> Self;
}
#[derive(Clone)]
struct Special;
impl Trait for Special {
fn foo<T: Trait + Any>(of: T) -> Self {
let of_any = &of as &dyn Any;
if let Some(special) = of_any.downcast_ref::<Special>() {
// Fast path
special.clone()
} else {
// Generic path, pretend this is expensive
Special
}
}
}
这篇关于在Rust中,如何检查泛型参数是否为特定类型并将其强制转换为特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文