如何创建所有实现具有公共数据成员的trait的结构? 我把一些代码从C++移植到RIST,我不确定C++中处理普通基类成员的等价方法是什么。我在C++中拥有的一个示例: class Base { public: Base(int n) : n_(n) {} virtual int foo() = 0; int n_; }; class D1 : public Base { public: D1(int n) : Base(n) {} virtual int foo() {/* return something to do with n_ */} }; class D2 : public Base { public: D1(int n) : Base(n) {} virtual int foo() {/* return some other thing to do with n_ */} }; 在C++中,我可以在基类构造函数中定义一次代码< n> ,并且我可以从任何派生类中使用它。

如何创建所有实现具有公共数据成员的trait的结构? 我把一些代码从C++移植到RIST,我不确定C++中处理普通基类成员的等价方法是什么。我在C++中拥有的一个示例: class Base { public: Base(int n) : n_(n) {} virtual int foo() = 0; int n_; }; class D1 : public Base { public: D1(int n) : Base(n) {} virtual int foo() {/* return something to do with n_ */} }; class D2 : public Base { public: D1(int n) : Base(n) {} virtual int foo() {/* return some other thing to do with n_ */} }; 在C++中,我可以在基类构造函数中定义一次代码< n> ,并且我可以从任何派生类中使用它。,c++,rust,polymorphism,C++,Rust,Polymorphism,我的Rust结构当前如下所示: struct D1 { n_: i32, } struct D2 { n_: i32, } trait Base { fn foo(&self) -> i32; } impl D1 { fn new(n: i32) -> Self { D1 { n_: n } } } impl D2 { fn new(n: i32) -> Self { D2 { n_

我的Rust结构当前如下所示:

struct D1 {
    n_: i32,
}

struct D2 {
    n_: i32,
}

trait Base {
    fn foo(&self) -> i32;
}

impl D1 {
    fn new(n: i32) -> Self {
        D1 { n_: n }
    }
}

impl D2 {
    fn new(n: i32) -> Self {
        D2 { n_: n }
    }
}

impl Base for D1 {
    fn foo(&self) -> i32 {
        // Contrived example to show D1 and D2 have different uses of n_
        self.n_
    }
}

impl Base for D2 {
    fn foo(&self) -> i32 {
        // Contrived example to show D1 and D2 have different uses of n_
        self.n_ * 2
    }
}

这感觉像是比我习惯的更多的代码重复。是否有一种方法可以让<代码> Nu“我怎么能让它们有一个公共数据成员?”-你们有什么,只是我误解了吗?我知道如何在C++中这样做,我不知道如何在锈中做到这一点。我的错误是没有澄清我的错误,我误读了你真正的锈代码是什么?你可以通过让你的Rust
struct
s实现,或者通过创建一个新的特性来返回你想要的值(并为你的
struct
s实现这个新特性)。这种问题在一般情况下是无法解决的。原因是C++对很多事情使用了继承——数据、行为、接口——以及RID对于所有这些问题没有一个解决方案;它有几个可以组合的正交特征。你有一些问题,你已经决定应该通过继承来解决,但这在锈病中是行不通的;你需要丢弃在C++中工作的解决方案,并建立一个新的解决方法。