我正在尝试编写一个阶乘函数,但出现了可怕的语法错误。我已将我的问题归结为几行代码。我曾尝试将值赋值更改为 let value =
但我最终陷入了无限循环。
extern crate num; // 0.2.0
use num::{bigint::BigUint, One};
fn decrease(mut value: &BigUint) {
while value != &BigUint::one() {
value = &(value - BigUint::one());
println!("new value {}", value);
}
}
error[E0597]: borrowed value does not live long enough
--> src/lib.rs:7:18
|
7 | value = &(value - BigUint::one());
| ^^^^^^^^^^^^^^^^^^^^^^^^- temporary value only lives until here
| |
| temporary value does not live long enough
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the function body at 5:1...
--> src/lib.rs:5:1
|
5 | / fn decrease(mut value: &BigUint) {
6 | | while value != &BigUint::one() {
7 | | value = &(value - BigUint::one());
8 | | println!("new value {}", value);
9 | | }
10| | }
| |_^
= note: consider using a `let` binding to increase its lifetime
最佳答案
如果你想改变value
...的值,你必须把它当作&mut
。把它当作 mut &
没有多大意义。在你可以使用 -=
之后。
extern crate num; // 0.2.0
use num::{BigUint, One};
fn decrease(value: &mut BigUint) {
while value != &BigUint::one() {
*value -= BigUint::one();
println!("new value {}", value);
}
}
fn main() {
decrease(&mut BigUint::new(vec!(42)));
}
关于rust - 无法在循环中递减 &BigUint,因为临时值的生命周期不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52824931/