[英]Rust treat two different structs as one
I have two different structs with similar functions.我有两个具有相似功能的不同结构。 Suppose that the program choose which struct to take from the user input.假设程序选择从用户输入中获取哪个结构。 I want to write something like this我想写这样的东西
fn main() {
...
let obj = if a == first {
first_object //struct First
} else {
second_object//struct Second
};
obj.read();
obj.write();
obj.some_another_method();
}
I have tried to make an enumeration我试图进行枚举
pub enum ObjectKind {
FirstObject(First),
SecondObject(Second)
}
But I cannot use methods in this case但在这种情况下我不能使用方法
let something = ObjectKind::FirstObject(first_object);
something.read()
//no method named `read` found for enum `structs::ObjectKind` in the current scope
//method not found in `structs::ObjectKind`
But I cannot use methods in this case但在这种情况下我不能使用方法
An enum
is a proper type in and of itself, it's not a "union" of existing types. enum
本身就是一种适当的类型,它不是现有类型的“联合”。 You can just define the methods on the enum
to forward to the relevant object eg您可以在enum
上定义方法以转发到相关对象,例如
impl ObjectKind {
fn read(&self) {
match self {
FirstObject(f) => f.read()
SecondObject(s) => s.read()
}
}
}
as it would probably be a bit repetitive, you can use a macro to make the forwarding easier.因为它可能有点重复,您可以使用宏来使转发更容易。
Alternatively, you might be able to define a trait for the common behaviour and use a trait object to dynamically dispatch between the two, but that can be somewhat restrictive.或者,您可以为常见行为定义特征并使用特征对象在两者之间动态调度,但这可能会有些限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.