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 private field in Rust
- Example of Rust struct with closure
- Example of struct of structs in Rust
- How to get struct value in Rust
- Example of bit field in Rust struct
- Rust struct without fields
- How to init zero struct in Rust
- How to convert struct to bytes in Rust
- Example of struct with vector field in Rust
- How to compare structs in Rust
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace all using regex in Rust?
- How to replace all matches using Rust regex?
- How to borrow from vector in Rust
- How to split a string with Rust regex?
- How to match a URL with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to parse a file with Rust regex?
- How to get a capture group using Rust regex?
See more codes...