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
- Example of constant struct in Rust
- Example of Rust struct with closure
- How to init zero struct in Rust
- How to extend struct from another struct in Rust
- How to serialize struct to xml in Rust
- Example of struct with vector field in Rust
- How to update struct in Rust
- How to sort a struct in Rust
- Rust struct with one field example
- How to set default value in Rust struct
More of Rust
- Generator example in Rust
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to use binary regex in Rust?
- How to use regex lookahead in Rust?
- How to make regex case insensitive in Rust?
- Regex example to match multiline string in Rust?
- How to use regex to match a double quote in Rust?
- Yield example in Rust
- How to use a tuple as a key in a Rust HashMap?
See more codes...