Rust 设计模式 Marker Trait + Blanket Implementation

如果一个 Trait 要被多种 struct 实现,其中某几个或某一类 struct 对这个 trait 的实现方式一样,就可以用到 Marker Trait 这种设计模式。开源的做虚拟机模块化的 vm-memory 仓库就用到了这种技巧。

rust 复制代码
/// 普通的实现方式
struct MyRegion { /* ... */ }

// 😭 必须手动实现所有 Bytes 的方法
impl Bytes<MemoryRegionAddress> for MyRegion {
    fn write(&self, buf: &[u8], addr: MemoryRegionAddress) -> Result<usize> {
        let maddr = addr.raw_value() as usize;
        self.as_volatile_slice()?.write(buf, maddr).map_err(Into::into)
    }
    
    fn read(&self, buf: &mut [u8], addr: MemoryRegionAddress) -> Result<usize> {
        let maddr = addr.raw_value() as usize;
        self.as_volatile_slice()?.read(buf, maddr).map_err(Into::into)
    }
    
    fn write_slice(&self, ...) { /* ... */ }
    fn read_slice(&self, ...) { /* ... */ }
    fn read_volatile_from(&self, ...) { /* ... */ }
    // ... 还有 4-5 个方法要写
}

/// 😁 用上 Marker Trait
pub trait MemoryRegionBytes {}

impl<R: MemoryRegionBytes> Bytes<MemoryRegionAddress> for R {
    // ← 为所有实现了 GuestMemoryRegionBytes 的类型
    //   自动提供 Bytes 的默认实现!
    
    fn write(&self, buf: &[u8], addr: MemoryRegionAddress) -> Result<usize> {
        let maddr = addr.raw_value() as usize;
        self.as_volatile_slice()?    // ← 调用 GuestMemoryRegion 的方法
            .write(buf, maddr)
            .map_err(Into::into)
    }
    
    fn read(&self, buf: &mut [u8], addr: MemoryRegionAddress) -> Result<usize> {
        let maddr = addr.raw_value() as usize;
        self.as_volatile_slice()?
            .read(buf, maddr)
            .map_err(Into::into)
    }
    
    // ... 其他 6-7 个方法都自动实现了
}

impl MemoryRegionBytes for MyRegion {}
相关推荐
蚂蚁背大象10 小时前
Rust 所有权系统是为了解决什么问题
后端·rust
布列瑟农的星空10 小时前
前端都能看懂的rust入门教程(五)—— 所有权
rust
七月丶11 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞12 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼12 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟1 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder1 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
Java水解1 天前
Rust嵌入式开发实战——从ARM裸机编程到RTOS应用
后端·rust
Pomelo_刘金1 天前
Rust:所有权系统
rust
阿星AI工作室2 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式