[英]In Rust, how check if a generic parameter is of a specific type and cast to it
I have several types that implement a trait (Relation). 我有几种实现特征(Relation)的类型。 I need to pass data between them, like
INSERT INTO FROM SELECT
from sql. 我需要在它们之间传递数据,比如从SQL中
INSERT INTO FROM SELECT
。
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
. 你应该尝试使用
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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.