在实现指定trait的结构体中添加成员



假设我在Rust中有这样一个结构体:

// Trait that allows objects that
// implement it to return themselves
// to the caller.
trait ReturnsSelf {
fn get_self(self) -> Self {
self
}
}
struct Data {
member: u32
}

我怎么能说member不一定是u32,但应该简单地实现ReturnsSelf作为一个特征?我也可以说成员应该要么实现ReturnsSelf,要么成为u32?或者两者都有?

你用一个trait绑定声明一个泛型:

struct Data<T: RetursSelf> {
member: T,
}

最新更新