types - 如何避免无约束类型参数错误

标签 types rust

如果不使用不受约束的类型,我想不出一种方法来获得以下功能。

struct Things<T> {
    thing: T
}
trait ThingActions<D> {//will be implemented for 'D's of different types
    fn foo(&self, data: D) {}
    fn bar(&self, data: D) {}
}
impl<T: ThingActions<D>, D> Things<T> {
    fn do_foos(&self, data: D) {//any D with corresponding foo can be used here
        self.thing.foo(data)
    }
}
impl<T: ThingActions<D>, D: Send + Sync> Things<T> {
    fn do_bars_multithreaded(&self, data: D) {
        self.thing.bar(&self.thing, data)//this happens in a different thread
    }
}

我的最终目标是让下面的代码适用于 foo 和 bar 的任何配置,而对它的更改相对较少。
fn main(){
    let number = Things {thing: 5isize};
    number.do_foos(2);
    number.do_foos('a');
}
impl ThingActions<isize> for isize {
    fn foo(&self, data: isize){
        println!("{}", data + self)
    }
}
impl ThingActions<char> for isize {
    fn foo(&self, data: char){
        println!("{}, {}", data, self)
    }
}

也有可能的情况是除了“事物”之外什么都不使用。

最佳答案

你可以尝试绑定(bind)D仅在 fn 上,而不是整个结构:

struct Things<T> {
    thing: T
}
trait ThingActions<D> {//will be implemented for 'D's of different types
    fn foo(&self, data: D) {}
    fn bar(&self, data: D) {}
}
impl<T> Things<T> {
    fn do_foos<D>(&self, data: D)
        where T: ThingActions<D>
    {//any D with corresponding foo can be used here
        self.thing.foo(data)
    }
}
impl<T> Things<T> {
    fn do_bars_multithreaded<D>(&self, data: D)
        where T: ThingActions<D>, D: Send + Sync
    {
        self.thing.bar(data)//this happens in a different thread
    }
}

fn main(){
    let number = Things {thing: 5isize};
    number.do_foos(2);
    number.do_foos('a');
}
impl ThingActions<isize> for isize {
    fn foo(&self, data: isize){
        println!("{}", data + self)
    }
}
impl ThingActions<char> for isize {
    fn foo(&self, data: char){
        println!("{}, {}", data, self)
    }
}

关于types - 如何避免无约束类型参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61970607/

相关文章:

java - 对于集合,我们什么时候更喜欢使用 Object 类型,什么时候使用原始类型

iphone - UI键盘类型

rust - 为什么没有实现 Ord 的 f32 得到 "conflicting implementations of trait"?

rust - 如何将多个整数转换为字节数组

scala 类型问题 : SoftReference, ReferenceQueues, SoftHashMap

Python类解释

C++:比较相同类型的操作数类型

memory-management - 如何将 Box<dyn Trait> 转换为 Rc<dyn Trait>?

performance - 为什么在 Rust 中迭代整数向量比在 Python、C# 和 C++ 中慢?

rust - unistd::read() 总是返回 0