Rust 如何通过副作用实现可变增量?
出于学习目的,我尝试了此解决方案,但:Rust 如何通过副作用实现可变增量?,rust,side-effects,Rust,Side Effects,出于学习目的,我尝试了此解决方案,但: 使用std::ops::Add; fn公司(x:&mut T){ *x+=1; } fn main(){ 设mut x:i32=10; 设mut y:u8=1; 公司(mut x),; 股份有限公司; println!(“{}{}”,x,y); } 错误消息: <anon>:4:5: 4:7 error: binary assignment operation `+=` cannot be applied to types `T` and `
使用std::ops::Add;
fn公司(x:&mut T){
*x+=1;
}
fn main(){
设mut x:i32=10;
设mut y:u8=1;
公司(mut x),;
股份有限公司;
println!(“{}{}”,x,y);
}
错误消息:
<anon>:4:5: 4:7 error: binary assignment operation `+=` cannot be applied to types `T` and `_` [E0368]
<anon>:4 *x += 1;
^~
<anon>:4:5: 4:7 help: see the detailed explanation for E0368
error: aborting due to previous error
:4:5:4:7错误:二进制赋值操作“+=”不能应用于类型“T”和“\\\[E0368]
:4*x+=1;
^~
:4:5:4:7帮助:请参阅E0368的详细说明
错误:由于上一个错误而中止
正确的方法是什么?目前,
+=
仅在基本整数类型上定义;一般来说,您需要将其扩展到*x=*x+1代码>取而代之。这就暴露了更多的问题:
,并且在crates.io中的num
板条箱中有一个稳定的,num::one
。使用前者需要每晚除锈,使用后者需要删除std::
,添加外部板条箱编号
并将num
添加到Cargo.toml依赖项部分
我们还需要一个副本
绑定,以允许*x+1
的*x
工作
#![特征(0_-1)]
使用std::ops::Add;
使用std::num::One;
fn公司(x:&mut T){
*x=*x+T::one();
}
fn main(){
设mut x:i32=10;
设mut y:u8=1;
公司(mut x),;
股份有限公司;
println!(“{}{}”,x,y);
}
我的答案中唯一没有多余的部分是指向的链接。感谢您的详细解释!《稳定锈》中缺少详细说明,但《夜间频道》提供了详细说明:
<anon>:4:5: 4:7 error: binary assignment operation `+=` cannot be applied to types `T` and `_` [E0368]
<anon>:4 *x += 1;
^~
<anon>:4:5: 4:7 help: see the detailed explanation for E0368
error: aborting due to previous error