rustHow to join structs in Rust
Structs in Rust can be joined using the join method. This method takes two structs and returns a new struct with the combined fields of both.
Example
struct Point {
x: i32,
y: i32,
}
let p1 = Point { x: 1, y: 2 };
let p2 = Point { x: 3, y: 4 };
let p3 = p1.join(p2);
println!("p3.x = {}", p3.x);
println!("p3.y = {}", p3.y);
Output example
p3.x = 1
p3.y = 2
Code explanation
struct Point { x: i32, y: i32, }: Defines a struct with two fields,xandy, both of typei32.let p1 = Point { x: 1, y: 2 };: Creates a new instance of thePointstruct withxset to1andyset to2.let p2 = Point { x: 3, y: 4 };: Creates a new instance of thePointstruct withxset to3andyset to4.let p3 = p1.join(p2);: Joins the two structsp1andp2and stores the result inp3.println!("p3.x = {}", p3.x);: Prints the value ofp3.xto the console.println!("p3.y = {}", p3.y);: Prints the value ofp3.yto the console.
Helpful links
Related
- How to init zero struct in Rust
- Example of struct private field in Rust
- Example of Rust struct with closure
- Example of constant struct in Rust
- Example of bit field in Rust struct
- Example of struct with vector field in Rust
- How to copy struct in Rust
- How to update struct in Rust
- How to convert struct to protobuf in Rust
More of Rust
- How to use binary regex in Rust?
- How to map a Rust slice?
- How to compare two Rust HashMaps?
- How to yield a thread in Rust?
- How to make regex case insensitive in Rust?
- How to use regex to match a group in Rust?
- How to match whitespace with a regex in Rust?
- How to use regex lookbehind in Rust?
- How to match digits with regex in Rust?
- How to use regex to match a double quote in Rust?
See more codes...