// plain
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);
}
borrowed_x: 0
&
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
group: rust-borrow