一 变量
- 变量默认是不可变的,声明一个变量后不可以在改变这个变量的值
- 使用
mut
关键字声明一个变量是可变的。 - 可变性是一种权衡。
二 常量
- 使用
const
关键字,而非let
声明一个常量 - 常量声明必须指定类型:
1
const MAX_POINTS: u32 = 100_000;
rust常量命名规范是:全字母大写, 单词间以下划线分隔,rust的数字为了方便阅读也可以使用下划线分割。
- 将一个在整个程序中使用的值设为常量,有利于传递该值的含义给未来的代码维护人员。
- 常量便于修改,只需修改一个常量,便可更新程序中所有使用该常量的值
三 变量与常量的异同
相同点:都不可变
不同点:
- 常量不是默认不可变,而是一直不会改变。声明方式不一样,变量使用
let
常量使用const
且必须指定常量的类型。 - 常量可以在任意作用域里声明
- 常量只能设置为常量表达式,而不能设置为函数调用的结果或只能在运行时计算的任何其他值。
四 覆盖 shadowing
-
变量的覆盖不同于将变量设为可变变量。 如果不使用
let
为变量重新赋值,会得到编译错误,但是使用let
为同一变量重新赋值可是覆盖之前的该变量的值。覆盖特性让变量可以改变 -
覆盖的好处是可以让我们避免于起不同的变量名,可以直接复用之前的变量名,同时不必关心变量类型的更改。另外复用变量名也更高效和便于理解。
五 words, statements and translation
-
This is one of many nudges Rust gives you to write your code in a way that takes advantage of the safety and easy concurrency that Rust offers.
这是Rust为您提供的许多建议之一,使您能够以一种利用Rust提供的安全性和轻松并发性的方式编写代码。
1 2
nudges 推动,说服 concurrency 并发
-
so lower performance might be a worthwhile penalty for gaining that clarity.
因此,更低的性能可能是为了获得这种清晰度而付出的代价。
1 2
performance 性能 penalty
-
Naming hardcoded values used throughout your program as constants is useful in conveying the meaning of that value to future maintainers of the code
将整个程序中使用的硬编码值命名为常量,有助于向代码的未来维护者传达该值的含义
-
shallowing 浅 shadowing 阴影
-
By using let, we can perform a few transformations on a value but have the variable be immutable after those transformations have been completed.
通过使用let,我们可以对一个值执行一些转换,但在这些转换完成后,变量是不可变的
1 2
perform 执行 transformation 转换
-
spare … from …. 使…免于…
-
constants may be set only to a constant expression, not to the result of a function call or any other value that could only be computed at runtime.
常量只能设置为常量表达式,而不能设置为函数调用的结果或只能在运行时计算的任何其他值