作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有几种实现特征(关系)的类型。我需要在它们之间传递数据,例如来自 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
}
}
}
关于generics - 在 Rust 中,如何检查泛型参数是否属于特定类型并转换为它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53788315/
我是一名优秀的程序员,十分优秀!