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
- When to use borrow in Rust
- How to borrow as static in Rust
- How to borrow vector element in Rust
- How to borrow struct field in Rust
- How to borrow box in Rust
- How to return borrow in Rust
- How to borrow from iterator in Rust
- How to borrow as mutable in Rust
- Rust partial borrow example
More of Rust
- How to replace a capture group using Rust regex?
- How to use regex captures in Rust?
- How to use named capture groups in Rust regex?
- How to use regex with bytes in Rust?
- How to use regex to match a double quote in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to match the end of a line in a Rust regex?
- How to parse JSON string in Rust?
- How to convert a Rust slice to a fixed array?
- How to calculate the inverse of a matrix in Rust?
See more codes...