首页 > 解决方案 > 为什么“结果”不需要是 mut ?

问题描述

我正要通过 rust 书学习 rust。我的理解是,我不能分配给未声明为 mut 的变量。所以我想知道,为什么这段代码有效:

extern crate num_bigint;
use num_bigint::BigUint;

fn main() {
    let n = 10_000;
    println!("{}! = {};", n, factorial_recursive(n));
}

fn factorial_recursive(n: usize) -> BigUint {
    let result: BigUint;
    if n == 0 { result = BigUint::new(vec![1]); }
    else { result = factorial_recursive(n-1) * n; }
    result
}

一开始,我已经声明了结果 mut,但是我得到了一个编译器警告,mut 不是必需的。所以我删除了它,很惊讶它仍然有效。为什么呢?

PS:我知道,我可以直接从 if/else 分支返回。我一开始就有这个,但想在返回之前打印出结果,所以我改成了这个,编译器警告说 mut 没有必要。现在我想明白这一点。

标签: rust

解决方案


推荐阅读