Getting started with Rust

January 27, 2024

Syntax:

  • main function is special, first code that runs in every rust executable
  • curly braces for functions
  • semi-colons for expressions
  • rustfmt included as part of the installation
  • ! used for macros

Compilation:

  • uses rustc
    • compiler for the Rust programming language, provided by the project itself, which takes your source code and produces binary code, either as a library or executable
    • we only ever pass rustc the crate root, not every file we wish to compile

Packages and crates:

  • a crate is a compilation unit in Rust (synonymous with packages from other languages)
    • it is a library or executable program
    • can contain modules, which may be defined in other files
    • crates are shipped with Cargo, package management tool
    • implicit root module, from which compilation starts
    • modules allow you to partition your code within the crate itself
  • binary crates
    • programs that can be compiled to executables and run, including a main function
  • library crates
    • programs that don't compile to executablesm, don't define a main function, define functionality intended to be run by multiple projects
  • a package is a bundle of one or more crates
    • contains a Cargo.toml file that describes how to build those crates
    • manifest file, which contains all the metadata needed to compile package
  • publishing crates to crates.io - https://crates.io/

Creating a new project:

Commands:

cargo new hello-world --bin
cargo new my-lib --lib  // different directory structure with test case to run
cargo test -- --nocapture
cargo build  // target/debug
cargo run
cargo build --release  // target/release
cargo update  // regenerates Cargo.lock
cargo doc --open

Scope:

Mutability:

let apples = 5; // immutable
let mut bananas = 5; // mutable

Configuration:

 
// to prevent SSL errors
 
// C:\Users\lmiloszewski\.cargo\config.toml
[http]
check-revoke = false