<分区>
我有一个方法,我想返回一个元素的拥有副本。如果需要,我可以证明为什么我想要这个。
这是一个最小的可重现示例:( playground )
use std::collections::HashMap;
struct AsciiDisplayPixel {
value: char,
color: u32,
}
struct PieceToPixelMapper {
map: HashMap<usize, AsciiDisplayPixel>,
}
impl PieceToPixelMapper {
pub fn map(&self, index: usize) -> Option<AsciiDisplayPixel> {
let pixel = self.map.get(&index);
let pixel = match pixel {
None => return None,
Some(x) => x,
};
return Some(pixel.clone());
}
}
fn main() {
println!("Hello World");
}
编译失败
error[E0308]: mismatched types
--> src/main.rs:20:21
|
20 | return Some(pixel.clone());
| ^^^^^^^^^^^^^ expected struct `AsciiDisplayPixel`, found reference
|
= note: expected type `AsciiDisplayPixel`
found type `&AsciiDisplayPixel`
我不确定为什么会这样。根据documentation on clone ,它看起来像 clone
的结果类型是父级的任何类型,所以如果你克隆一个引用,你仍然会得到一个引用,我想如果没问题,但我不知道我是如何克隆的到拥有的数据。 to_owned
似乎有完全相同的问题并给出相同的错误消息。