如何解决借用价值的"预期结构,找到的参考"?

  • 本文关键字:结构 参考 何解决 解决 rust
  • 更新时间 :
  • 英文 :


我在引用装箱值时出错:

error[E0308]: mismatched types
--> src/interpreter.rs:284:37
|
284 |             table[index].function = method;
|                                     ^^^^^^ expected struct `Box`, found `&Box<MethodType>`
|
= note: expected struct `Box<MethodType>`
found reference `&Box<MethodType>`

如果我通过说*method来取消引用它,我会得到一个错误,因为MethodType没有实现Copy(这会很痛苦,因为它包括几个Vec,而且复制成本很高(。也许我可以用ManuallyDrop来修复它,但这似乎不太习惯,今天下午我花了一些时间来处理ManuallyDrop

也许我不应该通过引用传递它(对addMethodToTable的仅有两个调用在下面的方法addMethodToDispatch中,但它们处于循环中,因为我需要尝试多次分配(。也许它应该是Rc。这是很多代码的一部分,所以我希望这个狙击足以表明我做错了什么:

#[derive(Clone)]
enum MethodType {
Function(Function),
Method(Method),
NoType,
}
#[derive(Clone)]
struct MethodMatch {
selector: usize,
function: Box<MethodType>,
}
pub struct Dispatch {
class: Object,
table: Box<[MethodMatch]>,
}
fn addMethodToTable(table:&mut Vec<MethodMatch>,selector:usize,method:&Box<MethodType>) -> bool {
let len = table.capacity();
let hash = selector%(len-DISPATCH_OVERFLOW);
for index in hash..hash+DISPATCH_OVERFLOW {
if let SelectorMatch::Other = table[index].selector_match(selector) {
// slot taken
} else {
table[index].selector = selector;
table[index].function = method;
return true
}
}
false
}
fn addMethodToDispatch(class:ClassIndex,selector:Object,method:Box<MethodType>) {
let selector = selector.raw()>>3;
while ... {
table = Vec::with_capacity(count+DISPATCH_OVERFLOW);
addMethodToTable(&mut table,selector,&method);
for mm in disp.table.iter() {
if addMethodToTable(&mut table,mm.selector,&mm.function) {unfinished = true;break}
}
}
table.resize(table.capacity(),Default::default());
disp.table=table.into_boxed_slice()
},
index => {
disp.table[index].selector = selector;
disp.table[index].function = method
},

我度过了如此富有成效的一天,直到我遇到了这个。。。以为我终于";得到";锈

您的结构需要拥有的类型-function必须是Box:

#[derive(Clone)]
struct MethodMatch {
selector: usize,
function: Box<MethodType>,
}

但在您的另一种方法中,参数method是对Box的引用,这是两种非常不同的类型:

`fn addMethodToTable(....,method: &Box<MethodType>)

有两种方法可以解决这个问题(并非所有方法都适用于您的情况(:

  1. 将引用更改为拥有的类型:method: &Box<MethodType>应变为method: Box<MethodType>

  2. 因为MethodType实现了Clone,所以只需克隆它就可以从引用中获得一个拥有的类型:table[index].function = method.clone();

  3. 如果您可以随意更改结构定义,则可以使用Rc<T>而不是Box<T>。因此,您可以使用Rc::clone(reference),只克隆指针而不是整个结构。

最新更新