无法在循环中递减 &BigUint,因为临时值的生存时间不够长

  • 本文关键字:不够 时间 因为 循环 BigUint rust
  • 更新时间 :
  • 英文 :


我正在尝试编写一个阶乘函数,但我遇到了可怕的语法错误。我已经将我的问题归结为几行代码。我尝试将值赋值更改为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)));
}

最新更新