我编写了以下工作代码:

#[derive(Debug, PartialEq, Serialize)]
struct Grid64Row {
    ...
    cell: String, 
    ...
}
...
    let mut rows_by_cell: HashMap::<String, Vec<Grid64Row>> = HashMap::new();
    for row in rows {
        match rows_by_cell.entry(row.cell.clone()) {
            Entry::Vacant(e) => { e.insert(vec![row]); },
            Entry::Occupied(mut e) => { e.get_mut().push(row); }
        }
    }

据我所知,我需要row.cell-Stringclone()次.编译器同意,如果我删除.clone(),我会得到:

 error[E0382]: use of partially moved value: `row`
  --> foobar/src/main.rs:97:49
   |
96 |         match rows_by_cell.entry(row.cell) {
   |                                  -------- value partially moved here
97 |             Entry::Vacant(e) => { e.insert(vec![row]); },
   |                                                 ^^^ value used here after partial move
   |
   = note: partial move occurs because `row.cell` has type `std::string::String`, which does not implement the `Copy` trait

有没有办法解决这个短命的克隆?(我不明白为什么‘.entry()’需要String分,而不是&str分,但即使这样也会有借款问题.)

推荐答案

问题是,返回的Entry必须能够在HashMap中为Entry::Vacant case 创建一个新条目,因此在没有像CloneToOwned这样的额外约束的情况下,它必须采用拥有的T版本,而不仅仅是引用.

Rust相关问答推荐

如何初始化match声明中的两个变量而不会激怒borrow 判断器?

将JSON密钥转换为Polars DataFrame

为什么我的梅森素数代码的指数越大,速度就越快?

从Type::new()调用函数

如何在 struct 的自定义序列化程序中使用serde序列化_WITH

当T不执行Copy时,如何返回Arc Mutex T后面的值?

对于rustc编译的RISC-V32IM二进制文件,llvm objdump没有输出

为什么HashMap::get和HashMap::entry使用不同类型的密钥?

borrow 是由于对 `std::sync::Mutex>` 的解引用强制而发生的

Rust Axum 框架 - 解包安全吗?

Rust 为什么被视为borrow ?

使用自定义 struct 收集 Vec

n 个范围的笛卡尔积

将 `&T` 转换为新类型 `&N`

Rust 中函数的类型同义词

为什么拥有 i32 所有权的函数需要它是可变的?

为什么 Rust 编译器在移动不可变值时执行复制?

火箭整流罩、tokio-scheduler 和 cron 的生命周期问题

Rust 中的运行时插件

如何迭代调用可能会失败的函数?操作员?