gpt4 book ai didi

rust - 重写函数以使用特征时借用内容时出错

转载 作者:行者123 更新时间:2023-11-29 08:30:54 25 4
gpt4 key购买 nike

我是 Rust 的新手,对这门语言有点兴趣。我写了两个简单的函数来递增和递减 Rc<RefCell<..>> 中的值.由于此功能对任何数字类型都有意义,因此我尝试将它们变成通用函数:

use num::Integer;

// This works fine
pub fn increment_counter(c: &Rc<RefCell<u32>>) {
let new_c = *c.borrow() + 1;
c.replace(new_c);
}

// This does not compile
pub fn decrement_counter<T>(c: &Rc<RefCell<T>>)
where
T: Integer,
{
let new_c = *c.borrow() - T::one();
c.replace(new_c);
}

我突然收到这个错误:

55 |     let new_c = *c.borrow() - T::one();
| ^^^^^^^^^^^ cannot move out of borrowed content

我不明白为什么此更改会导致此类错误。

最佳答案

据我所知,u32 案例之所以有效,是因为 u32 实现了 Copy,允许毫无问题地“移出借用的上下文” . IE。 Copy 表示可以通过简单地复制位来移动类型。因此,为该类型移出一个借用值是没有问题的。

因此,如果您需要Copy 用于一般情况,它也应该有效。

pub fn decrement_counter<T>(c: &Rc<RefCell<T>>)
where
T: Integer + Copy, // <- "Copy"
{
let new_c = *c.borrow();
c.replace(new_c);
}

关于rust - 重写函数以使用特征时借用内容时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58150558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com