Rust学习二 变量与可变性

rust的变量与其可变性

Posted by rpl on February 7, 2020

通过此链接查看rust学习系列的其他文章

一 变量

  1. 变量默认是不可变的,声明一个变量后不可以在改变这个变量的值
  2. 使用 mut 关键字声明一个变量是可变的。
  3. 可变性是一种权衡。

二 常量

  1. 使用 const 关键字,而非 let 声明一个常量
  2. 常量声明必须指定类型:
    1
    
     const MAX_POINTS: u32 = 100_000;
    

    rust常量命名规范是:全字母大写, 单词间以下划线分隔,rust的数字为了方便阅读也可以使用下划线分割。

  3. 将一个在整个程序中使用的值设为常量,有利于传递该值的含义给未来的代码维护人员。
  4. 常量便于修改,只需修改一个常量,便可更新程序中所有使用该常量的值

三 变量与常量的异同

相同点:都不可变

不同点:

  1. 常量不是默认不可变,而是一直不会改变。声明方式不一样,变量使用let 常量使用const且必须指定常量的类型。
  2. 常量可以在任意作用域里声明
  3. 常量只能设置为常量表达式,而不能设置为函数调用的结果或只能在运行时计算的任何其他值。

四 覆盖 shadowing

  1. 变量的覆盖不同于将变量设为可变变量。 如果不使用let为变量重新赋值,会得到编译错误,但是使用let为同一变量重新赋值可是覆盖之前的该变量的值。覆盖特性让变量可以改变

  2. 覆盖的好处是可以让我们避免于起不同的变量名,可以直接复用之前的变量名,同时不必关心变量类型的更改。另外复用变量名也更高效和便于理解。

五 words, statements and translation

  1. 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 并发
    
  2. so lower performance might be a worthwhile penalty for gaining that clarity.

    因此,更低的性能可能是为了获得这种清晰度而付出的代价。

    1
    2
    
    performance 性能
    penalty
    
  3. Naming hardcoded values used throughout your program as constants is useful in conveying the meaning of that value to future maintainers of the code

    将整个程序中使用的硬编码值命名为常量,有助于向代码的未来维护者传达该值的含义

  4. shallowing 浅 shadowing 阴影

  5. 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 转换
    
  6. spare … from …. 使…免于…

  7. 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.

    常量只能设置为常量表达式,而不能设置为函数调用的结果或只能在运行时计算的任何其他值