rust / intermediate
Snippet
Unsafe Rust: Arbeiten mit Raw Pointern
Unsafe Rust gibt dir fünf zusätzliche Superkräfte: Raw Pointer dereferenzieren, unsafe Funktionen aufrufen, unsafe Traits implementieren, statische Variablen verändern und Union-Felder zugreifen. Raw Pointer (`*const T` und `*mut T`) können Rusts Borrow Checker umgehen, erfordern aber manuelle Sicherheitsgarantien vom Programmierer.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
fn main() {// Creating raw pointers is safe, dereferencing is unsafelet mut value = 42;// Create immutable and mutable raw pointerslet ptr1: *const i32 = &value as *const i32;let ptr2: *mut i32 = &mut value as *mut i32;unsafe {// Read through raw pointerprintln!("Value via immutable pointer: {}", *ptr1);// Modify value through mutable raw pointer*ptr2 = 100;println!("Value after modification: {}", *ptr2);// Call unsafe functionunsafe_fn();// Work with foreign raw pointer (from C library simulation)let foreign_data = vec![1i32, 2, 3, 4, 5];let foreign_ptr = foreign_data.as_ptr();println!("Foreign data first element: {}", *foreign_ptr);}// Unsafe function definitionunsafe fn unsafe_fn() {println!("Called from unsafe context");}// Unsafe trait implementationunsafe trait UnsafeTrait {fn required_method(&self);}unsafe impl UnsafeTrait for Circle {fn required_method(&self) {println!("Implementing unsafe trait");}}}
Erklärung
1
let ptr1: *const i32 = &value as *const i32;
Erstellen eines Raw immutable Pointers - sichere Operation
2
*ptr2 = 100;
Dereferenzieren und Schreiben durch mutable raw Pointer - unsafe Operation
3
unsafe fn unsafe_fn()
Als unsafe markierte Funktion - Aufrufer müssen in unsafe Block sein oder Aufruf als unsafe markieren
4
unsafe trait UnsafeTrait
Als unsafe markiertes Trait - Implementierungen müssen als unsafe markiert werden