Variables are immutable by default.
Shadowing
Rust allows us to shadow the previous value of a given variable with a new one, e.g.:
This feature is often used when you want to convert a value from one type to another type.
Constants
The type of the value must be annotated.
May be set only to a constant expression, not the result of a value that could only be computed at runtime.
Constants are valid for the entire time a program runs, within the scope in which they were declared.
Scope
Every variable has its scope where itโs valid.
Clone
We can use a common method called clone
:
Rust has a special annotation called the
Copy
trait that we can place on types that are stored on the stack, as integers are (weโll talk more about traits in Chapter 10). If a type implements theCopy
trait, variables that use it do not move, but rather are trivially copied, making them still valid after assignment to another variable.
Rust wonโt let us annotate a type with
Copy
if the type, or any of its parts, has implemented theDrop
trait. If the type needs something special to happen when the value goes out of scope and we add theCopy
annotation to that type, weโll get a compile-time error.
Rust doesnโt have the null feature that many other languages have. Null is a value that means there is no value there. In languages with null, variables can always be in one of two states: null or not-null. Instead we have Option
enum.