简体   繁体   English

仅当自我:大小时才具有超级特质

[英]Supertrait only when Self : Sized

Lets suppose I have a trait假设我有一个特质

trait A {
    fn new() -> Self where Self : Sized;
    fn foo(&self) -> i32;
}
struct B {
   data : i32
}
impl A for B {
    fn new() -> Self {
        B {data : 42}
    }
    fn foo(&self) -> i32 {
        self.data
    }
}

Now I can use Box<dyn A> , I just do not have the new() method available.现在我可以使用Box<dyn A> ,只是没有可用的 new() 方法。 And when I have a generic T: A , I can do T::new() .当我有一个通用的T: A时,我可以做T::new() So I can use A as a trait object (without the functions which would prevent this) and I can use it in a templated code and use all functions on it.所以我可以使用 A 作为特征 object (没有阻止这种情况的函数),我可以在模板代码中使用它并使用它上面的所有函数。

My question is, is it possible to get this behavior when having for example Clone as supertrait?我的问题是,当将Clone作为超级特征时,是否有可能获得这种行为? In the dyn A case A does not implement Clone.dyn A情况下A没有实现 Clone。 In the generic case is does.在一般情况下是。

You can do like that:你可以这样做:

trait A {
    fn new() -> Self where Self : Sized;
    fn foo(&self) -> i32;
}

#[derive(Clone)]
struct B {
   data : i32
}

impl A for B {
    fn new() -> Self {
        B {data : 42}
    }
    fn foo(&self) -> i32 {
        self.data
    }
}


fn make_clone<T: Clone + A>(toc: &T) -> T {
    dbg!(toc.foo());
    toc.clone()
}

fn main() {
    let b = B{data: 0};
    make_clone(&b);
}

so you can access A method and the Clone supertrait from make_clone , you can obviously do the same thing with a supertrait instead of a generic method因此您可以从make_clone访问A方法和Clone超特征,显然您可以使用超特征而不是泛型方法做同样的事情

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM