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 with lifetime in Rust
- How to borrow a string in Rust
- How to borrow as static in Rust
- When to use borrow in Rust
- How to borrow moved value in Rust
- How to return borrow in Rust
- Rust partial borrow example
- How to borrow in loop in Rust
- How to borrow hashmap in Rust
- How to borrow from vector in Rust
More of Rust
- How to replace a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to get a capture group using Rust regex?
- How to convert the keys of a Rust HashMap to a vector?
- How to convert Rust bytes to hex?
- How to use non-capturing groups in Rust regex?
- How to use regex with bytes in Rust?
- How to get the last element of a Rust slice?
- How to match the end of a line in a Rust regex?
See more codes...