rust - 为什么“结果”不需要是 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 没有必要。现在我想明白这一点。
解决方案
推荐阅读
- ssl - Azure IoT 中心 MQTT 失败
- assembly - 在汇编中使用 ds 和 [ ] 进行 jmp
- java - Eclipse 说“您的 sql 语法有错误”,但相同的查询在工作台中有效。问题出在哪里?
- php - 如何使用在 localhost 上运行的 docker 在 PHP 代码中模拟 console.log
- .net - 用户控件的子控件属性不是持久的
- haskell - 我们如何将 Haskell 数据结构序列化和反序列化为字节串?
- reactjs - 将 ChartJS 与 React 一起使用时出现错误消息
- java - java - 如何从数组列表中对java中的存储过程调用进行多线程调用?
- r - install.packages() 与 setwd() 有问题
- kotlin - Dagger2 - 如何使用 @Named 和 @BindsInstance