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 to borrow struct field in Rust
- How borrow instead of move in Rust
- When to use borrow in Rust
- How to borrow vector element in Rust
- How to return borrow in Rust
- How to borrow moved value in Rust
- How to borrow hashmap in Rust
- How to borrow with lifetime in Rust
- Rust partial borrow example
- Example of borrow_mut in Rust
More of Rust
- How to replace strings using Rust regex?
- How to match whitespace with a regex in Rust?
- Regex example to match multiline string in Rust?
- How to use non-capturing groups in Rust regex?
- How to use regex to match a double quote in Rust?
- How to use 'or' in Rust regex?
- How to use regex lookbehind in Rust?
- How to use Unicode in a regex in Rust?
- How to replace all matches using Rust regex?
- How to use negation in Rust regex?
See more codes...