簡體   English   中英

如何避免無約束類型參數錯誤

[英]how to avoid unconstrained type paramameter error

如果不使用不受約束的類型,我想不出一種方法來獲得以下功能。

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)
    }
}

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

您可以嘗試僅在fn上綁定D ,而不是在整個結構上:

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)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM