[英]Making a boxed trait with generic functions returns error
I'm trying to abstract reading and writing memory from a process in my Rust program.我正在尝试从我的 Rust 程序中的进程中抽象读写 memory 。 Here is some example code describing the issue:以下是一些描述该问题的示例代码:
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));
}
When compiling, I get the following error:编译时,我收到以下错误:
the trait `ProcessHandle` cannot be made into an object
Is there any way I can have generic functions in a trait without making every struct I use it in generic?有没有什么办法可以让我在一个特征中拥有泛型函数而不使我在泛型中使用它的每个结构?
You cannot make a trait object out of ProcessHandle
because it's not safe , quoting from the book:您不能从ProcessHandle
中制作特征 object 因为它不安全,引用书中的内容:
A trait is object safe if all the methods defined in the trait have the following > properties:如果特征中定义的所有方法都具有以下 > 属性,则该特征是 object 安全的:
- The return type isn't
Self
.返回类型不是Self
。- There are no generic type parameters.没有泛型类型参数。
Your write_memory
method has generic type parameters您的write_memory
方法具有泛型类型参数
I found a workaround by creating non generic functions in my ProcessHandle trait and adding the generic functions using impl ProcessHandle
我通过在我的 ProcessHandle 特征中创建非泛型函数并使用impl ProcessHandle
添加泛型函数找到了一种解决方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.