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 aMyStruct
instance with anint
value of5
let my_int_ref = &my_struct.my_int;
: creates a reference to theint
value ofmy_struct
using the&
operatorprintln!("my_int_ref = {}", my_int_ref);
: prints the value of theint
reference
Helpful links
Related
- How to borrow vector element in Rust
- How to borrow as static in Rust
- How to borrow with lifetime in Rust
- How to borrow hashmap in Rust
- When to use borrow in Rust
- How to borrow struct field in Rust
- How to borrow moved value in Rust
- How to borrow a string in Rust
- Rust partial borrow example
- How to borrow option value in Rust
More of Rust
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to use regex with bytes in Rust?
- How to replace strings using Rust regex?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to get an entry from a HashSet in Rust?
- How to match whitespace with a regex in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to use regex lookahead in Rust?
See more codes...