簡體   English   中英

使用泛型函數制作盒裝特征會返回錯誤

[英]Making a boxed trait with generic functions returns error

我正在嘗試從我的 Rust 程序中的進程中抽象讀寫 memory 。 以下是一些描述該問題的示例代碼:

trait ProcessHandle {
    // Create a new process handle from pid
    fn new(pid: u32) -> Box<dyn ProcessHandle>;
    // Read value from process of type T from the process
    // (type T has an implicit Sized trait so we know how
    // large the value that we're reading is)
    fn read_memory<T>(&self, address: u64) -> T;
    // Write value of type T to process
    fn write_memory<T>(&self, address: u64, value: T);
}

struct ExampleProcessHandle {
    pid: u32
}

impl ProcessHandle for ExampleProcessHandle {
    fn new(pid: u32) -> Box<dyn ProcessHandle> {
        Box::new(Self{pid})
    }

    fn read_memory<T>(&self, address: u64) -> T {
        // read memory from process at `address`
        unsafe { std::mem::zeroed::<T>() }
    }

    fn write_memory<T>(&self, address: u64, value: T) {
        // write to process
        return
    }
}

fn main() {
    let handle = ExampleProcessHandle::new(10);
    // Should print 0
    println!("{:x}", handle.read_memory::<u32>(0x111111));
}

編譯時,我收到以下錯誤:

the trait `ProcessHandle` cannot be made into an object

有沒有什么辦法可以讓我在一個特征中擁有泛型函數而不使我在泛型中使用它的每個結構?

您不能從ProcessHandle中制作特征 object 因為它不安全,引用書中的內容:

如果特征中定義的所有方法都具有以下 > 屬性,則該特征是 object 安全的:

  1. 返回類型不是Self
  2. 沒有泛型類型參數。

您的write_memory方法具有泛型類型參數

我通過在我的 ProcessHandle 特征中創建非泛型函數並使用impl ProcessHandle添加泛型函數找到了一種解決方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM