Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Rust 如何通过副作用实现可变增量?_Rust_Side Effects - Fatal编程技术网

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