rustHow to extend struct from another struct in Rust
Structs in Rust can be extended from another struct using the #[derive(PartialEq)]
annotation. This allows the struct to inherit the fields and methods of the parent struct.
Example
#[derive(PartialEq)]
struct Parent {
field1: i32,
field2: i32,
}
struct Child {
field3: i32,
}
impl Child : PartialEq {
fn new(field1: i32, field2: i32, field3: i32) -> Child {
Child {
field1: field1,
field2: field2,
field3: field3,
}
}
}
let parent = Parent { field1: 1, field2: 2 };
let child = Child::new(1, 2, 3);
assert_eq!(parent, child);
Output example
assertion successful
Code explanation
#[derive(PartialEq)]
: This annotation allows the struct to inherit the fields and methods of the parent struct.impl Child : PartialEq
: This line implements thePartialEq
trait for theChild
struct.let parent = Parent { field1: 1, field2: 2 };
: This line creates an instance of theParent
struct.let child = Child::new(1, 2, 3);
: This line creates an instance of theChild
struct.assert_eq!(parent, child);
: This line compares the two structs and checks if they are equal.
Helpful links
Related
- Example of struct of structs in Rust
- Example of struct private field in Rust
- How to init zero struct in Rust
- How to serialize struct to xml in Rust
- Example of Rust struct with closure
- How to get struct value in Rust
- Example of bit field in Rust struct
- Rust struct without fields
- How to update struct in Rust
- How to convert struct to protobuf in Rust
More of Rust
- Hashshet example in Rust
- How to convert Rust bytes to hex?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to get the last element of a Rust slice?
- How to use non-capturing groups in Rust regex?
- How to use groups in a Rust regex?
- How to match the end of a line in a Rust regex?
- How to escape dots with regex in Rust?
- How to use regex to match a group in Rust?
See more codes...