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,x
andy
, both of typei32
.let p1 = Point { x: 1, y: 2 };
: Creates a new instance of thePoint
struct withx
set to1
andy
set to2
.let p2 = Point { x: 3, y: 4 };
: Creates a new instance of thePoint
struct withx
set to3
andy
set to4
.let p3 = p1.join(p2);
: Joins the two structsp1
andp2
and stores the result inp3
.println!("p3.x = {}", p3.x);
: Prints the value ofp3.x
to the console.println!("p3.y = {}", p3.y);
: Prints the value ofp3.y
to the console.
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...