Programming a Guessing Game
General
By default, Rust has a set of items defined in the standard library that it brings into the scope of every program. This set is called the prelude.
If a type we want to use is not in the prelude, we have to bring that type into scope explicitly with a
usecommand
- variable is immutable by default
- To be able to make a variable mutable, we add
mutkeyword before the variable name String::new(), for example is a usage of associated function.newis an associated function ofStringtype
Reference
- The
&indicates that this argument is a reference, which gives you a way to let multiple parts of code access one piece of data without needing to copy that data into memory multiple times. - Reference, like variable is also immutable by default
Enum
Resultis anenum. A type that can be in one of multiple possible states. Each possible state is called variantOkError
Crate
- Crate is a collection of Rust source code files
- Cargo's coordination of external crates is where Cargo really shines
- Use
cargo add <crate name>to import an external crate as a dependency Cargo.lockfile guarantees the dependency version is locked to the specified SemVer- To understand how to use a crate, issuing the command
cargo doc --openwill generate documentations of all the defined dependencies of the current project
Shadowing
let mut guess: String = String::new();
let mut guess: u32 = guess.trim().parse().expect("...");
- This feature is often used when you want to convert a value from one type to another type