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
More of Rust
- How to compare with null in Rust
- Hashshet example in Rust
- How to parse JSON string in Rust?
- How to convert Rust bytes to a vector of u8?
- How to use an enum in a Rust HashMap?
- How to check if a Rust slice contains a certain value?
- How to split a Rust slice into chunks?
- How to loop with condition in Rust
- How to concatenate Rust slices?
- How do I get the type of a variable in Rust?
See more codes...