57·Unsafe Rust高级

unsafe trait 与实现

unsafe trait 与实现

学习目标

  1. 理解 unsafe trait 的含义
  2. 掌握标记 trait 的设计

核心概念

定义 unsafe trait

/// 实现者必须保证特定的内存安全约束
unsafe trait Traversable {
    fn traverse(&self);
}

struct SafeType {
    data: Vec<i32>,
}

unsafe impl Traversable for SafeType {
    fn traverse(&self) {
        for item in &self.data {
            println!("{}", item);
        }
    }
}

标准库中的 unsafe trait

// Send 和 Sync 就是 unsafe trait
// 大部分类型自动实现,手动实现需要 unsafe

struct MyType {
    // ...
}

// 如果你确定类型是线程安全的:
unsafe impl Send for MyType {}
unsafe impl Sync for MyType {}

GlobalAlloc

use std::alloc::{GlobalAlloc, Layout};

struct MyAllocator;

unsafe impl GlobalAlloc for MyAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        std::alloc::System.alloc(layout)
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        std::alloc::System.dealloc(ptr, layout);
    }
}

小结

概念说明
unsafe trait实现者必须满足特定安全约束
unsafe impl实现时保证满足约束
用途标记 trait、分配器、线程安全

练习编辑器

rust
Loading...