簡體   English   中英

如何在包含銹特質的泛型類型上實現deref?

[英]How do you implement deref on a generic type containing a trait in rust?

能夠使用Deref從通用容器生成&TraitType而不是調用instance.as_ref()會非常方便。 即:

(*my_container).do_thing();

my_container.as_ref().do_thing();

為此,我嘗試在容器類型上實現Deref,但出現此錯誤:

<anon>:9:28: 9:29 error: expected a reference to a trait [E0172]
<anon>:9 impl<T> Deref for HasTrait<T + Send> {

從:

use std::ops::Deref;

trait Foo {}

struct HasTrait<T> {
  data:Box<T>
}

impl<T> Deref for HasTrait<T + Send> {
  type Target = T;
  fn deref<'a>(&'a self) -> &'a T {
    return self.as_ref();
  }
}

struct IsFoo;
unsafe impl Send for IsFoo {}
impl Foo for IsFoo {}


fn main() {
  let is_foo = IsFoo;
  let foo:Box<Foo> = box is_foo as Box<Foo>;
  let has_foo = HasTrait { data: foo };
  let foo_ref:&Foo = *has_foo; 
}

我嘗試使用?Sized增加T的范圍以允許特征,但似乎沒有幫助?

什么是正確的方法?

這有效:

use std::ops::Deref;

struct HasTrait<T: ?Sized> {
    data: Box<T>
}

impl<T: ?Sized> HasTrait<T> {
    fn as_ref(&self) -> &T {
        &*self.data
    }
}

impl<T: ?Sized> Deref for HasTrait<T> {
    type Target = T;

    fn deref<'a>(&'a self) -> &'a T {  // '
        self.as_ref()
    }
}

trait Foo {}
struct IsFoo;
impl Foo for IsFoo {}

fn main() {
    let is_foo = IsFoo;
    let foo: Box<Foo> = box is_foo as Box<Foo>;
    let has_foo = HasTrait { data: foo };
    let foo_ref: &Foo = &*has_foo; 
}

基本上,您的問題與大小無關。 僅僅是HasTrait<T + Send>在這里:

impl<T> Deref<T> for HasTrait<T + Send>

是沒有意義的。 T可以是任意類型,而u64 + Send類的東西就沒有意義。 因此,恐怕您將無法將HasTrait約束為包含特征,並且包含Send類型。 只是沒有語法,我很確定類型系統不支持它。

暫無
暫無

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

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