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
More of Rust
- How to use captures_iter with regex in Rust?
- How to use regex to match a double quote in Rust?
- Bitwise operator example in Rust
- How to insert an element into a Rust HashMap if it does not already exist?
- How to replace strings using Rust regex?
- How to get the last element of a slice in Rust?
- How to match whitespace with a regex in Rust?
- How to use regex lookbehind in Rust?
- How to replace a capture group using Rust regex?
- Regex example to match multiline string in Rust?
See more codes...