You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-06-18 07:07:35 +02:00
Add a slide about writing unsafe functions.
This commit is contained in:
@ -164,7 +164,8 @@
|
|||||||
- [Dereferencing Raw Pointers](unsafe/raw-pointers.md)
|
- [Dereferencing Raw Pointers](unsafe/raw-pointers.md)
|
||||||
- [Mutable Static Variables](unsafe/mutable-static-variables.md)
|
- [Mutable Static Variables](unsafe/mutable-static-variables.md)
|
||||||
- [Unions](unsafe/unions.md)
|
- [Unions](unsafe/unions.md)
|
||||||
- [Calling Unsafe Functions](unsafe/unsafe-functions.md)
|
- [Calling Unsafe Functions](unsafe/calling-unsafe-functions.md)
|
||||||
|
- [Writing Unsafe Functions](unsafe/writing-unsafe-functions.md)
|
||||||
- [Extern Functions](unsafe/extern-functions.md)
|
- [Extern Functions](unsafe/extern-functions.md)
|
||||||
- [Implementing Unsafe Traits](unsafe/unsafe-traits.md)
|
- [Implementing Unsafe Traits](unsafe/unsafe-traits.md)
|
||||||
- [Exercises](exercises/day-3/afternoon.md)
|
- [Exercises](exercises/day-3/afternoon.md)
|
||||||
|
38
src/unsafe/writing-unsafe-functions.md
Normal file
38
src/unsafe/writing-unsafe-functions.md
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
# Writing Unsafe Functions
|
||||||
|
|
||||||
|
You can mark your own functions as `unsafe` if they require particular conditions to avoid undefined
|
||||||
|
behaviour.
|
||||||
|
|
||||||
|
```rust,editable
|
||||||
|
/// Swaps the values pointed to by the given pointers.
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
///
|
||||||
|
/// The pointers must be valid and properly aligned.
|
||||||
|
unsafe fn swap(a: *mut u8, b: *mut u8) {
|
||||||
|
let temp = *a;
|
||||||
|
*a = *b;
|
||||||
|
*b = temp;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let mut a = 42;
|
||||||
|
let mut b = 66;
|
||||||
|
|
||||||
|
// Safe because ...
|
||||||
|
unsafe {
|
||||||
|
swap(&mut a, &mut b);
|
||||||
|
}
|
||||||
|
|
||||||
|
println!("a = {}, b = {}", a, b);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
<details>
|
||||||
|
|
||||||
|
We wouldn't actually use pointers for this because it can be done safely with references.
|
||||||
|
|
||||||
|
Note that unsafe code is allowed within an unsafe function without an `unsafe` block. We can
|
||||||
|
prohibit this with `#[deny(unsafe_op_in_unsafe_fn)]`. Try adding it and see what happens.
|
||||||
|
|
||||||
|
</details>
|
Reference in New Issue
Block a user