作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这个问题在这里已经有了答案:
How can I swap in a new value for a field in a mutable reference to a structure?
(2 个回答)
Cannot move out of borrowed content when trying to transfer ownership
(1 个回答)
Temporarily move out of borrowed content
(3 个回答)
How to write a trait bound for adding two references of a generic type?
(1 个回答)
1年前关闭。
有没有不需要 AddAssign
的方法来编写这个函数?或 Clone
在 T
?
use std::ops::Add;
fn increment<T: Add<isize, Output = T>>(x: &mut T) {
*x = *x + 1;
}
如所写,我收到错误:
error[E0507]: cannot move out of `*x` which is behind a mutable reference
--> src/lib.rs:4:10
|
4 | *x = *x + 1;
| ^^ move occurs because `*x` has type `T`, which does not implement the `Copy` trait
最佳答案
根据@Shepmaster 在评论中的回复,我认为如果不更改函数签名,这是不可能的,因为正在应用的函数可能会 panic 离开 x
。如果从 panic 中恢复,则处于内存不安全状态。
但是,通过添加 Default
使用 mem::replace
约束成为可能.
use std::mem;
use std::ops::Add;
fn increment<T: Default + Add<isize, Output = T>>(x: &mut T) {
let y = mem::replace(x, Default::default());
*x = y + 1;
}
现在如果
add
panic ,
x
将有默认
T
.
关于rust - 如何将任意就地操作应用于 &mut 引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64863591/
我是一名优秀的程序员,十分优秀!