rust 我想给trait添加一个额外的实现方法,并使结构体可调用

ecfdbz9o  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(102)

我想给trait添加一个额外的实现方法,使结构体可调用,但我不知道如何实现。
我不知道什么标题更适合我的问题。
示例:

pub struct A {}

impl A {
  pub fn main(self){

    let boxed: Box<A> = Box::new(self);
    boxed.test(); // method not found in `Box<A>`
    // expect working

    let boxed: Box<dyn Trait> = boxed;
    boxed.test(); // working

  }
}

pub trait Trait {
  fn whatever(&self) -> u32
}

impl Trait for A {
    fn whatever(&self) -> u32 { unimplemented!() }
}

impl dyn Trait {
  pub fn test(&self) {
    unimplemented!()
  }
}

字符串

xriantvc

xriantvc1#

你可以把额外的方法放在一个新的trait中,并为所有实现了另一个trait(Trait)的类型实现该trait(Test):

pub struct A {}

impl A {
  pub fn main(self){

    let boxed: Box<A> = Box::new(self);
    boxed.test();

    let boxed: Box<dyn Test> = boxed;
    boxed.test();

  }
}

pub trait Trait {
  fn whatever(&self) -> u32;
}

impl Trait for A {
    fn whatever(&self) -> u32 { unimplemented!() }
}

pub trait Test {
  fn test(&self);
}

impl<T> Test for T where T: Trait + Sized {
  fn test(&self) {
    unimplemented!()
  }
}

fn main() {
}

字符串
如果你想在Test中继承Trait的功能,你可以引入相应的trait绑定:

pub struct A {}

impl A {
  pub fn main(self){

    let boxed: Box<A> = Box::new(self);
    boxed.test();

    let boxed: Box<dyn Test> = boxed;
    boxed.test();
    boxed.whatever();
  }
}

pub trait Trait {
  fn whatever(&self) -> u32;
}

impl Trait for A {
    fn whatever(&self) -> u32 { unimplemented!() }
}

pub trait Test: Trait {
  fn test(&self);
}

impl<T> Test for T where T: Trait + Sized {
  fn test(&self) {
    unimplemented!()
  }
}

fn main() {
}

相关问题