rustRust unsafe borrow example
An example of an unsafe borrow in Rust is when a reference to a value is used after that value has been dropped. This can lead to a segmentation fault or other undefined behavior.
let mut x = 5;
let y = &mut x;
drop(x);
println!("{}", y);
Output example
thread 'main' panicked at 'already borrowed: BorrowMutError', src/libcore/result.rs:1165:5
Code explanation
let mut x = 5;
: Declares a mutable variablex
with the value5
.let y = &mut x;
: Creates a mutable referencey
tox
.drop(x);
: Drops the value ofx
.println!("{}", y);
: Attempts to print the value ofy
, which is a reference tox
that has already been dropped.
Helpful links
Related
- How to borrow with lifetime in Rust
- How to borrow as static in Rust
- How to borrow a string in Rust
- When to use borrow in Rust
- How to return borrow in Rust
- Rust partial borrow example
- How to borrow moved value in Rust
- How to borrow option value in Rust
- How to borrow in loop in Rust
- How to borrow box in Rust
More of Rust
- How to use regex with bytes in Rust?
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to implement PartialEq for a Rust HashMap?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
- How to calculate the inverse of a matrix in Rust?
- How to match a string with regex in Rust?
- How to use look behind in regex in Rust?
- How to parse JSON string in Rust?
See more codes...