Rust Book Day 1 Flashcards
Learning Rust
How to quickly verify if compiling is good?
cargo check
how to compile it with optimizations?
cargo build –release
what is part of the cargo.toml
[package]
name = “hello_project”
version = “0.1.0”
edition = “2020”
Comment
[dependencies]
list your crates here
Print hello world
fn main() {
println!(“hello world”);
}
how to compile and run straight away?
cargo run
how to build and then execute separately?
cargo build
then execute
./target/debug/project_name
How to ask for command line input (like a guess)
io::stdin()
.read_line(&mut guess)
.expect(“Failed to read line”);
How to import standard input library for terminal inputs?
use stdin::io;
How to create a variable whcih is a mutable string
let mut my_variable = String::new();
when using read_line(&mut guess) we are passing the variable guess. why must it be mutable?
Because we are appending stuff to the string as we are writing it seems, growing the string
what does the & in &mut guess indicate?
that this argument is a reference, no need to copy the data into memory multiple times
references are also immutable by default, so you need to write &mut here
read_line() returns a Result which is an …
enum
it is a type that can be in one of multipel possible states (each possibile state is called a variant)
what is Rng in use rand::Rng;
a trait
it defines methods, so the trait must be in scope for us to use those methods
turn string into integer
let guess: u32 = guess.trim().parse().expect(“should be a number”);