1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-12-07 10:39:26 +02:00

Publish Comprehensive Rust 🦀

This commit is contained in:
Martin Geisler
2022-12-21 16:36:30 +01:00
commit c212a473ba
252 changed files with 8047 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
# Calling External Code
Functions from other languages might violate the guarantees of Rust. Calling
them is thus unsafe:
```rust,editable
extern "C" {
fn abs(input: i32) -> i32;
}
fn main() {
unsafe {
// Undefined behavior if abs misbehaves.
println!("Absolute value of -3 according to C: {}", abs(-3));
}
}
```

View File

@@ -0,0 +1,28 @@
# Mutable Static Variables
It is safe to read an immutable static variable:
```rust,editable
static HELLO_WORLD: &str = "Hello, world!";
fn main() {
println!("name is: {}", HELLO_WORLD);
}
```
However, since data races can occur, it is unsafe to read and write mutable
static variables:
```rust,editable
static mut COUNTER: u32 = 0;
fn add_to_counter(inc: u32) {
unsafe { COUNTER += inc; } // Potential data race!
}
fn main() {
add_to_counter(42);
unsafe { println!("COUNTER: {}", COUNTER); } // Potential data race!
}
```

View File

@@ -0,0 +1,18 @@
# Dereferencing Raw Pointers
Creating pointers is safe, but dereferencing them requires `unsafe`:
```rust,editable
fn main() {
let mut num = 5;
let r1 = &mut num as *mut i32;
let r2 = &num as *const i32;
unsafe {
println!("r1 is: {}", *r1);
*r1 = 10; // Data race if r1 is being written concurrently!
println!("r2 is: {}", *r2);
}
}
```

17
src/unsafe/unions.md Normal file
View File

@@ -0,0 +1,17 @@
# Unions
Unions are like enums, but you need to track the active field yourself:
```rust,editable
#[repr(C)]
union MyUnion {
i: u8,
b: bool,
}
fn main() {
let u = MyUnion { i: 42 };
println!("int: {}", unsafe { u.i });
println!("bool: {}", unsafe { u.b }); // Undefined behavior!
}
```

View File

@@ -0,0 +1,16 @@
# Calling Unsafe Functions
A function or method can be marked `unsafe` if it has extra preconditions you
must uphold:
```rust,editable
fn main() {
let emojis = "🗻∈🌏";
unsafe {
// Undefined behavior if indices do not lie on UTF-8 sequence boundaries.
println!("{}", emojis.get_unchecked(0..4));
println!("{}", emojis.get_unchecked(4..7));
println!("{}", emojis.get_unchecked(7..11));
}
}
```