Tec*_*Sam 2 clone reference ownership rust
我有一个方法,我想返回一个元素的拥有副本。如果需要的话,我可以证明为什么我想要这个。
这是一个最小的可重现示例:(游乐场)
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");
}
Run Code Online (Sandbox Code Playgroud)
这无法编译
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");
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么会这样。根据clone的文档clone,它看起来像是父级的结果类型,所以如果你克隆一个引用,你仍然会得到一个引用,我想这很好,但我不知道如何克隆到拥有数据。to_owned似乎有完全相同的问题并给出相同的错误消息。
AsciiDisplayPixel需要实现Clone才能克隆(Copy、Debug和其他可能也有意义):
#[derive(Clone)]
struct AsciiDisplayPixel {
value: char,
color: u32,
}
Run Code Online (Sandbox Code Playgroud)
此时实现可以简化为:
pub fn map(&self, index: usize) -> Option<AsciiDisplayPixel> {
self.map.get(&index).cloned()
}
Run Code Online (Sandbox Code Playgroud)