rustHow to borrow struct field in Rust
Borrowing a struct field in Rust is done using the & operator. This operator creates a reference to the field, allowing it to be used without taking ownership of the struct.
Example:
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 0, y: 0 };
let borrowed_x = &point.x;
println!("borrowed_x: {}", borrowed_x);
}
Output example
borrowed_x: 0
Code explanation
&operator: creates a reference to the fieldlet point = Point { x: 0, y: 0 };: creates aPointstructlet borrowed_x = &point.x;: creates a reference to thexfield of thePointstructprintln!("borrowed_x: {}", borrowed_x);: prints the value of thexfield
Helpful links
Related
- How borrow instead of move in Rust
- How to borrow from vector in Rust
- When to use borrow in Rust
- How to borrow as static in Rust
- Rust unsafe borrow example
- How to return borrow in Rust
- Rust partial borrow example
- Rust borrow trait example
- How to borrow with lifetime in Rust
- How to borrow vector element in Rust
More of Rust
- How to use binary regex in Rust?
- How to use regex captures in Rust?
- How to perform matrix operations in Rust?
- How to use regex to match a double quote in Rust?
- How to yield a thread in Rust?
- How to print a Rust HashMap?
- How to match whitespace with a regex in Rust?
- How to add an entry to a Rust HashMap?
- How to extend a Rust HashMap?
- How to replace a capture group using Rust regex?
See more codes...