Rust学习笔记(1)

内容整理自:https://doc.rust-lang.org/book/title-page.html
Chapter 1

  • check rust version
rust —version

  • How to run a rust program
fn main() { println!("hello world"); }

  • main function is the entry to run in every app
  • ! means it runs a macro instead of a function
  • 2 steps to run: compile and run
    • pros: run everywhere even without rust installed
    • cons: 2 steps
    • just a design tradeoff
Cargo
  • What is cargo
    • build system
    • package manager
  • already installed with rust
  • check cargo version
    cargo —version
  • Creating a project with Cargo
    cargo new hello_cargo
  • packages of code are referred to as crates
  • build with cargo
    cargo build
  • run
    ./target/build/hello_cargo
    Or
    cargo run
  • check package doc
    cargo doc --open
  • quickly checks your code to make sure it compiles but doesn’t produce an executable
    cargo check
    Faster than cargo build, can be used as check your work
  • release
    cargo build --release
    Build with optimizations, in target/release
Chapter 2 guessing game
  • variables
let foo = 5; // immutable let mut bar = 5; // mutable

  • storing variables
io::stdin().read_line(&mut guess) .expect("Failed to read line");

【Rust学习笔记(1)】The & indicates that this argument is a reference, which gives you a way to let multiple parts of your code access one piece of data without needing to copy that data into memory multiple times.
  • Handling Potential Failure with the Result Type
    io::stdin().read_line(&mut guess).expect("Failed to read line");
    The Result types are enumerations, often referred to as enums. An enumeration is a type that can have a fixed set of values, and those values are called the enum’s variants
  • print values
    println!("You guessed: {}", guess);
    {} is a placeholder

    推荐阅读