我正在尝试编写阶乘函数,但是出现了可怕的语法错误。我将问题简化为几行代码。我曾尝试将值分配更改为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
答案 0 :(得分:2)
如果要更改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)));
}