RUST - rFronteddu/general_wiki GitHub Wiki

Rust

FAQ

  • Creating a new project with cargo:
cargo new hello_cargo
cd hello_cargo
  • Building with cargo
cargo build

This command creates an executable file in target/debug/hello_cargo (or target\debug\hello_cargo.exe on Windows) rather than in your current directory. Because the default build is a debug build, Cargo puts the binary in a directory named debug.

Running cargo build for the first time also causes Cargo to create a new file at the top level: Cargo.lock. This file keeps track of the exact versions of dependencies in your project. This project doesn’t have dependencies, so the file is a bit sparse. You won’t ever need to change this file manually; Cargo manages its contents for you.

Use --release to build with optimizations

cargo build --release

This command will create an executable in target/release instead of target/debug. The optimizations make your Rust code run faster, but turning them on lengthens the time it takes for your program to compile.

  • Compile and run in one command
cargo run
  • Check code without building executable
cargo check
  • Mutable/Immutable variables
let apples = 5; // immutable
let mut bananas = 5; // mutable
  • Mutable string
let mut guess = String::new();

The :: syntax in the ::new line indicates that new is an associated function of the String type. An associated function is a function that’s implemented on a type, in this case String. This new function creates a new, empty string. You’ll find a new function on many types because it’s a common name for a function that makes a new value of some kind.

  • Updating TOML
cargo update

When you do want to update a crate, Cargo provides the command update, which will ignore the Cargo.lock file and figure out all the latest versions that fit your specifications in Cargo.toml. Cargo will then write those versions to the Cargo.lock file.