🎓 A1Learner
🔍

Rust Editor Setup

rust-analyzer is a helper that checks Rust code inside an editor while the code is typed. A set-up editor underlines mistakes at once.

Install the helper

One command adds rust-analyzer to an existing Rust install. In VS Code you can instead install the rust-analyzer extension, which does the same job:

# in your terminal:
# $ rustup component add rust-analyzer

It shows the type Rust guessed

Hold the mouse over a name and the editor shows its type. This code writes no types at all, yet the editor can name every one:

let price = 19.99;
let count = 3;
let label = "apples";

Grey hints sit inside the code

Editors can also paint small grey hints next to a name — the type Rust worked out. The hints guide your eye. They are not real code, and they are never saved:

let price = 19.99;
let total = price * 2.0;

It finishes the name for you

Start typing and the editor lists the real methods that fit, with what each one needs:

let name = "Ferris";
println!("{} has {} letters", name, name.len());

Format on save

rustfmt is Rust's built-in formatter. Turn on format on save in your editor, and the layout tidies itself every time you save:

fn main() {
    let x = 1 + 2;
    println!("x = {x}");
}

Example

fn main() {
    let price = 2.5;
    let count = 4.0;
    let label = "apples";
    let total = price * count;
    println!("label = {}", label);
    println!("total = {}", total);
}

Key points

  • rust-analyzer is Rust's official language server — a helper program.
  • It reads your whole project.
  • It feeds answers to your editor while you type.
  • A red underline means the code would not compile — the same check rustc does, shown before you build
  • rust-analyzer reads Cargo.toml, so it knows your extra libraries and can complete their names too
  • A plain editor leaves checking until the build.
  • The editor only shows its best reading of the code early.

In this example, no variable names its type. Hover over price in a set-up editor and it shows f64, the decimal-number type, which is what 2.5 is. count is a decimal too, so price times count works, and total comes out as 10. label holds text. Those hover answers are the same guesses the compiler itself makes — the editor is simply showing them to you early.

Note

Your editor never changes the rules.

rustc makes the final call when you build.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does a red underline from rust-analyzer mean?