gpt4 book ai didi

generics - 在 Rust 中,如何检查泛型参数是否属于特定类型并转换为它

转载 作者:行者123 更新时间:2023-11-29 07:59:22 25 4
gpt4 key购买 nike

我有几种实现特征(关系)的类型。我需要在它们之间传递数据,例如来自 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com