rustHow to borrow int in Rust
Rust provides the borrow keyword to borrow an int from a struct or enum. The borrow keyword creates a reference to the int that can be used to access the value without taking ownership.
Example code
struct MyStruct {
my_int: i32,
}
fn main() {
let my_struct = MyStruct { my_int: 5 };
let my_int_ref = &my_struct.my_int;
println!("my_int_ref = {}", my_int_ref);
}
Output example
my_int_ref = 5
Code explanation
let my_struct = MyStruct { my_int: 5 };: creates aMyStructinstance with anintvalue of5let my_int_ref = &my_struct.my_int;: creates a reference to theintvalue ofmy_structusing the&operatorprintln!("my_int_ref = {}", my_int_ref);: prints the value of theintreference
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
- How to borrow from iterator in Rust
- How to borrow struct field in Rust
- How to borrow option value in Rust
More of Rust
- How to replace all matches using Rust regex?
- How to match the end of a line in a Rust regex?
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to use regex captures in Rust?
- How to use binary regex in Rust?
- How to match whitespace with a regex in Rust?
- How to use modifiers in a Rust regex?
- How to use regex to match a group in Rust?
- How to make regex case insensitive in Rust?
See more codes...