reference - 有没有办法将引用类型克隆到拥有的类型中?

标签 reference rust clone ownership

<分区>

我有一个方法,我想返回一个元素的拥有副本。如果需要,我可以证明为什么我想要这个。

这是一个最小的可重现示例:( 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 似乎有完全相同的问题并给出相同的错误消息。

最佳答案

AsciiDisplayPixel 需要实现 Clone 才能克隆(CopyDebug 等)可能也有道理):

#[derive(Clone)]
struct AsciiDisplayPixel {
    value: char,
    color: u32,
}

(updated playground)

此时实现可以简化为:

pub fn map(&self, index: usize) -> Option<AsciiDisplayPixel> {
    self.map.get(&index).cloned()
}

关于reference - 有没有办法将引用类型克隆到拥有的类型中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57487716/

相关文章:

rust - 除了 Rust 标准库之外,是否还有 Sync 特征的有效实现?

Git - 将另一个项目分支克隆到当前项目

java - 克隆时调用构造函数

vb.net - 从项目引用中获取类型出现在智能感知中的问题

asynchronous - 当内部可变的生命周期较短时,如何通过函数指针传递可变引用?

C# - 获取对对象的引用数

rust - 为什么 'static 函数参数不能使整个程序都活起来?

jquery .clone() 不工作

c++ - c++ 中 typedef 和模板的常量引用

c++ - 通过 const 获取参数并通过 const 返回的函数的生命周期延长