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 vector element in Rust
- When to use borrow in Rust
- How to borrow with lifetime in Rust
- How to borrow hashmap in Rust
- How to borrow struct field in Rust
- How to return borrow in Rust
- Rust partial borrow example
- How to borrow int in Rust
- How to borrow iterator in Rust
- Example of borrow_mut in Rust
More of Rust
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to split a string with Rust regex?
- How to iterate over a Rust slice with an index?
- How to use negation in Rust regex?
- How to use regex captures in Rust?
- Regex example to match multiline string in Rust?
- How to get a capture group using Rust regex?
- How to use modifiers in a Rust regex?
- How to create a HashMap of structs in Rust?
See more codes...