[英]In Rust, how check if a generic parameter is of a specific type and cast to it
我有几种实现特征(Relation)的类型。 我需要在它们之间传递数据,比如从SQL中INSERT INTO FROM SELECT
。
但是,有时我会移动来自相同类型的数据,这意味着我可以使用更直接的方式:
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
}
}
}
你应该尝试使用std::any
。 我想它看起来像这样:
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.