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 aPoint
structlet borrowed_x = &point.x;
: creates a reference to thex
field of thePoint
structprintln!("borrowed_x: {}", borrowed_x);
: prints the value of thex
field
Helpful links
Related
- Rust partial borrow example
- How to borrow with lifetime in Rust
- When to use borrow in Rust
- How to borrow int in Rust
- How to borrow hashmap in Rust
- How to borrow as static in Rust
- Rust unsafe borrow example
- How to return borrow in Rust
- How to borrow moved value in Rust
- How borrow instead of move in Rust
More of Rust
- How to clear a Rust HashMap?
- How to swap elements in a Rust slice?
- Bitwise negation (NOT) usage in Rust
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to use regex captures in Rust?
- How to convert a Rust HashMap to JSON?
- How do I identify unused variables in Rust?
- How to replace all matches using Rust regex?
See more codes...