Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Reference

    Compiler errors explained

    The Rust compiler errors you'll meet most often, what each one means in plain words, and the usual fix, with a real compiler message for every example.

    Rust checks ownership, borrows, types and traits before your program runs, so a lot of mistakes that would be run-time bugs in TypeScriptC# show up as compiler errors instead. This page covers the 18 you’ll meet most, roughly in the order you’ll meet them: ownership and borrowing first, then types and names. Each one has the code that triggers it with the real compiler message underneath, and the fixed code after it. The index at the end lists them all on one screen.

    How to read a compiler error

    Every message below has the same parts:

    1. The code and summary. error[E0382]: borrow of moved value: ... gives the error code and one line saying what’s wrong. Run rustc --explain E0382 for a longer explanation with examples.
    2. The location. The --> line gives the file, line and column of the problem, and the source is printed under it with line numbers.
    3. The labels. ^^^ marks the place where the rule was broken. --- marks the places that explain why: where a value was moved, where a borrow started, where a borrow is used later. Read the labels top to bottom and they usually tell the whole story.
    4. The notes and help. note: lines add context, such as a type that doesn’t implement a trait. A help: line usually suggests the fix, often as a small diff. Your editor offers the same suggestions as quick fixes.

    Fix the first error first: one mistake can cause several messages. And don’t be surprised if fixing a type error reveals a borrowing error: the compiler checks borrows only once the types are right.

    E0382: use of moved value

    You used a variable after its value moved somewhere else: to another variable, into a function, or into a for loop. After a move, the old name can’t be used.

    Coming from TypeScriptC#: In TypeScript, passing a string or an array to a function copies a reference, and the caller keeps using it. The garbage collector frees the object once nothing points at it.In C#, passing a class instance to a method copies a reference, and the caller keeps using it. The garbage collector frees the object once nothing points at it. Rust has no garbage collector. Every value has one owner, and passing a String, a Vec or your own struct to a function makes the function the new owner.

    fn shout(text: String) -> String {
        text.to_uppercase()
    }
    
    fn main() {
        let name = String::from("Ada");
        let loud = shout(name);
        println!("{name} {loud}");
    }

    Rust doesn't compile this: error E0382

    error[E0382]: borrow of moved value: `name`
     --> main.rs:8:16
      |
    6 |     let name = String::from("Ada");
      |         ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
    7 |     let loud = shout(name);
      |                      ---- value moved here
    8 |     println!("{name} {loud}");
      |                ^^^^ value borrowed here after move
      |
    note: consider changing this parameter type in function `shout` to borrow instead if owning the value isn't necessary
     --> main.rs:1:16
      |
    1 | fn shout(text: String) -> String {
      |    -----       ^^^^^^ this parameter takes ownership of the value
      |    |
      |    in this function
      = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
    help: consider cloning the value if the performance cost is acceptable
      |
    7 |     let loud = shout(name.clone());
      |                          ++++++++

    Fix: if the function only reads the value, let it borrow instead of taking ownership. Call .clone() only when you really need two independent copies.

    fn shout(text: &str) -> String {
        text.to_uppercase()
    }
    
    fn main() {
        let name = String::from("Ada");
        let loud = shout(&name);
        println!("{name} {loud}");
    }

    Output

    Ada ADA

    Learn more: Ownership and move semantics

    E0502: cannot borrow as mutable because it is also borrowed as immutable

    You tried to change a value while a shared borrow (&) of it is still in use. Rust allows many readers or one writer at a time, never both.

    Coming from TypeScriptC#: In TypeScript, nothing stops code from changing an array while other code reads it: a loop over an array you push to just keeps going.In C#, changing a list while a foreach reads it throws “Collection was modified” at run time. In Rust, &scores[0] is a pointer into the vector’s buffer, and push may move that buffer to a bigger allocation. The compiler won’t let a write happen while a borrow that could be left pointing at freed memory is still used.

    let mut scores = vec![10, 20, 30];
    let first = &scores[0];
    scores.push(40);
    println!("{first}");

    Rust doesn't compile this: error E0502

    error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
     --> main.rs:3:1
      |
    2 | let first = &scores[0];
      |              ------ immutable borrow occurs here
    3 | scores.push(40);
      | ^^^^^^^^^^^^^^^ mutable borrow occurs here
    4 | println!("{first}");
      |            ----- immutable borrow later used here

    Fix: a borrow lasts until its last use, so finish reading before you write, or copy the value out. An i32 is Copy, so scores[0] without & copies it and borrows nothing.

    let mut scores = vec![10, 20, 30];
    let first = scores[0]; // a copy of the number, not a borrow
    scores.push(40);
    println!("{first} {}", scores.len());

    Output

    10 4

    Learn more: References: &T and &mut T

    E0499: cannot borrow as mutable more than once at a time

    Two &mut borrows of the same value are in use at the same time. Only one part of the code may change a value at once.

    Coming from TypeScriptC#: In TypeScript, any number of variables can change the same object at the same time.In C#, two ref locals can point at the same variable, and both can change it. Rust allows one writer, so the compiler can assume nothing else changes a value behind a &mut. Indexing borrows the whole collection: the compiler sees names[0] and names[1] as two borrows of all of names, even though the elements are different.

    let mut names = vec![String::from("Ada"), String::from("Grace")];
    let first = &mut names[0];
    let second = &mut names[1];
    first.push('!');
    second.push('?');

    Rust doesn't compile this: error E0499

    error[E0499]: cannot borrow `names` as mutable more than once at a time
     --> main.rs:3:19
      |
    2 | let first = &mut names[0];
      |                  ----- first mutable borrow occurs here
    3 | let second = &mut names[1];
      |                   ^^^^^ second mutable borrow occurs here
    4 | first.push('!');
      | ----- first borrow later used here
      |
      = help: use `.split_at_mut(position)` to obtain two mutable non-overlapping sub-slices

    Fix: finish with one &mut before taking the next, or use a method that hands out non-overlapping parts, such as split_at_mut or iter_mut.

    let mut names = vec![String::from("Ada"), String::from("Grace")];
    let (left, right) = names.split_at_mut(1);
    left[0].push('!');
    right[0].push('?');
    println!("{names:?}");

    Output

    ["Ada!", "Grace?"]

    Learn more: References: &T and &mut T

    E0596: cannot borrow as mutable

    You tried to change a value through a variable that isn’t declared mut, or through a & reference instead of a &mut one. With a parameter, the message says the value is “behind a & reference”.

    Coming from TypeScriptC#: TypeScript’s const only stops you pointing the name at something else; you can still push to a const array.C#‘s readonly only stops you reassigning the field; you can still add to a readonly list. Rust’s let covers the whole value, contents included. If the variable isn’t mut, nothing can change through it.

    let names = vec![String::from("Ada")];
    names.push(String::from("Grace"));

    Rust doesn't compile this: error E0596

    error[E0596]: cannot borrow `names` as mutable, as it is not declared as mutable
     --> main.rs:2:1
      |
    2 | names.push(String::from("Grace"));
      | ^^^^^ cannot borrow as mutable
      |
    help: consider changing this to be mutable
      |
    1 | let mut names = vec![String::from("Ada")];
      |     +++

    Fix: declare the variable with let mut. For a parameter, take &mut Vec<String> and pass &mut names.

    let mut names = vec![String::from("Ada")];
    names.push(String::from("Grace"));
    println!("{}", names.len());

    Output

    2

    Learn more: Variables and mutability

    E0384: cannot assign twice to immutable variable

    You assigned a new value to a variable declared without mut.

    Coming from TypeScriptC#: Rust’s let is TypeScript’s const, and Rust’s let mut is TypeScript’s let.Rust’s let mut is C#‘s var. Plain let is a local you can never reassign, which C# has no keyword for. Variables are fixed unless you say otherwise, so mut marks the few that change.

    let total = 0;
    for price in [3, 4] {
        total += price;
    }
    println!("{total}");

    Rust doesn't compile this: error E0384

    error[E0384]: cannot assign twice to immutable variable `total`
     --> main.rs:3:5
      |
    1 | let total = 0;
      |     ----- first assignment to `total`
    2 | for price in [3, 4] {
    3 |     total += price;
      |     ^^^^^^^^^^^^^^ cannot assign twice to immutable variable
      |
    help: consider making this binding mutable
      |
    1 | let mut total = 0;
      |     +++

    Fix: add mut. If you’re turning a value into a new form step by step, you can also declare a new variable with the same name (shadowing): let total = total * 2;.

    let mut total = 0;
    for price in [3, 4] {
        total += price;
    }
    println!("{total}");

    Output

    7

    Learn more: Variables and mutability

    E0505: cannot move out because it is borrowed

    You moved a value (into another variable, a function, a collection or drop) while a borrow of it is still in use.

    Coming from TypeScriptC#: In TypeScript, putting a string into an array doesn’t affect other variables that point at it: the garbage collector keeps it alive as long as anything does.In C#, adding a string to a list doesn’t affect other variables that point at it: the garbage collector keeps it alive as long as anything does. In Rust, after a move the new owner decides when the value is freed, and it could free it straight away. So a borrow taken before the move can’t be used after it.

    let name = String::from("Ada");
    let initial = &name[..1];
    let owner = name;
    println!("{initial} {owner}");

    Rust doesn't compile this: error E0505

    error[E0505]: cannot move out of `name` because it is borrowed
     --> main.rs:3:13
      |
    1 | let name = String::from("Ada");
      |     ---- binding `name` declared here
    2 | let initial = &name[..1];
      |                ---- borrow of `name` occurs here
    3 | let owner = name;
      |             ^^^^ move out of `name` occurs here
    4 | println!("{initial} {owner}");
      |            ------- borrow later used here
      |
    help: consider cloning the value if the performance cost is acceptable
      |
    2 | let initial = &name.clone()[..1];
      |                    ++++++++

    Fix: finish using the borrow before the move, or borrow again from the new owner after it.

    let name = String::from("Ada");
    let owner = name;
    let initial = &owner[..1];
    println!("{initial} {owner}");

    Output

    A Ada

    Learn more: Lifetimes

    E0506: cannot assign because it is borrowed

    You assigned a new value to a variable while a borrow of it is still in use.

    Coming from TypeScriptC#: In TypeScript, const previous = current; current = "final"; leaves previous holding the old string.In C#, var previous = current; current = "final"; leaves previous holding the old string. A Rust &current doesn’t hold the old value; it borrows the variable. Assigning to current frees the old String, so the borrow would point at freed memory.

    let mut current = String::from("draft");
    let previous = &current;
    current = String::from("final");
    println!("{previous} -> {current}");

    Rust doesn't compile this: error E0506

    error[E0506]: cannot assign to `current` because it is borrowed
     --> main.rs:3:1
      |
    2 | let previous = &current;
      |                -------- `current` is borrowed here
    3 | current = String::from("final");
      | ^^^^^^^ `current` is assigned to here but it was already borrowed
    4 | println!("{previous} -> {current}");
      |            -------- borrow later used here

    Fix: if you need the old value, move it out first: a moved-from variable can be assigned again. Or keep a copy with .clone().

    let mut current = String::from("draft");
    let previous = current; // move the old value out
    current = String::from("final");
    println!("{previous} -> {current}");

    Output

    draft -> final

    Learn more: References: &T and &mut T. Closures shows the same error with a loop counter.

    E0597: borrowed value does not live long enough

    A reference is still in use after the value it points at went out of scope and was freed.

    Coming from TypeScriptC#: In TypeScript, an object lives as long as anything points at it, so a reference can’t outlive its object.In C#, an object lives as long as anything points at it, so a reference can’t outlive its object. Rust frees a value at the end of its owner’s scope, whatever still points at it, so the compiler checks that no borrow is used after that.

    let longest;
    {
        let name = String::from("Grace");
        longest = &name;
    }
    println!("{longest}");

    Rust doesn't compile this: error E0597

    error[E0597]: `name` does not live long enough
     --> main.rs:4:15
      |
    3 |     let name = String::from("Grace");
      |         ---- binding `name` declared here
    4 |     longest = &name;
      |               ^^^^^ borrowed value does not live long enough
    5 | }
      | - `name` dropped here while still borrowed
    6 | println!("{longest}");
      |            ------- borrow later used here

    Fix: keep the owner alive as long as the borrow (declare it in the outer scope), or move the value out instead of borrowing it. When the error mentions 'static, as with thread::spawn, pass owned data with a move closure.

    let longest;
    {
        let name = String::from("Grace");
        longest = name; // move the String out of the block
    }
    println!("{longest}");

    Output

    Grace

    Learn more: References: &T and &mut T and Lifetimes

    E0515: cannot return reference to local variable

    A function returns a reference to a value it created, and that value is freed when the function returns.

    Coming from TypeScriptC#: In TypeScript, returning an object you built inside a function is normal: the garbage collector keeps it alive for the caller.In C#, returning an object you built inside a method is normal: the garbage collector keeps it alive for the caller. In Rust, locals are dropped when the function returns, so a reference to one would dangle. No lifetime annotation can change that.

    fn greeting(name: &str) -> &str {
        let text = format!("Hello, {name}!");
        &text
    }

    Rust doesn't compile this: error E0515

    error[E0515]: cannot return reference to local variable `text`
     --> main.rs:3:5
      |
    3 |     &text
      |     ^^^^^ returns a reference to data owned by the current function

    Fix: return the owned value. Moving a String out of a function copies three numbers, not the text.

    fn greeting(name: &str) -> String {
        format!("Hello, {name}!")
    }
    
    fn main() {
        println!("{}", greeting("Ada"));
    }

    Output

    Hello, Ada!

    Learn more: Choosing parameter types

    E0106: missing lifetime specifier

    A function returns a reference, or a struct holds one, and the compiler can’t tell what it borrows from. With one reference parameter it assumes the result borrows from that; with two or more, you have to say.

    Coming from TypeScriptC#: TypeScript references have no lifetimes to write down: the garbage collector keeps whatever they point at alive.C# references have no lifetimes to write down: the garbage collector keeps whatever they point at alive. In Rust, the caller has to keep the borrowed input alive while it uses the result, so the signature must say which input that is. A lifetime like 'a is a name for “as long as this borrow”, not a duration.

    fn longer(a: &str, b: &str) -> &str {
        if a.len() >= b.len() { a } else { b }
    }

    Rust doesn't compile this: error E0106

    error[E0106]: missing lifetime specifier
     --> main.rs:1:32
      |
    1 | fn longer(a: &str, b: &str) -> &str {
      |              ----     ----     ^ expected named lifetime parameter
      |
      = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
    help: consider introducing a named lifetime parameter
      |
    1 | fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
      |          ++++     ++          ++          ++

    Fix: name a lifetime and put it on the result and on the parameters it can borrow from. Don’t reach for 'static: it moves the error to every caller. For a struct field, prefer an owned type such as String over a reference.

    fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
        if a.len() >= b.len() { a } else { b }
    }
    
    fn main() {
        println!("{}", longer("Grace", "Ada"));
    }

    Output

    Grace

    Learn more: Lifetimes

    E0716: temporary value dropped while borrowed

    You borrowed from a temporary, a value that isn’t stored in a variable, and kept the borrow. A temporary is dropped at the end of the statement.

    Coming from TypeScriptC#: In TypeScript, chaining input.trim().toUpperCase() and keeping the result is fine: every intermediate string lives as long as something points at it.In C#, chaining input.Trim().ToUpper() and keeping the result is fine: every intermediate string lives as long as something points at it. In Rust, to_uppercase() returns a new String that nothing owns, so it’s dropped at the semicolon, and .as_str() would point into freed memory.

    let input = " ada ";
    let name = input.trim().to_uppercase().as_str();
    println!("{name}");

    Rust doesn't compile this: error E0716

    error[E0716]: temporary value dropped while borrowed
     --> main.rs:2:12
      |
    2 | let name = input.trim().to_uppercase().as_str();
      |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^         - temporary value is freed at the end of this statement
      |            |
      |            creates a temporary value which is freed while still in use
    3 | println!("{name}");
      |            ---- borrow later used here
      |
    help: consider using a `let` binding to create a longer lived value
      |
    2 ~ let binding = input.trim().to_uppercase();
    3 ~ let name = binding.as_str();
      |

    Fix: store the owned value in a variable first, then borrow from it, or keep using the String itself.

    let input = " ada ";
    let upper = input.trim().to_uppercase();
    let name = upper.as_str();
    println!("{name}");

    Output

    ADA

    Learn more: Lifetimes

    E0308: mismatched types

    A value has a different type from the one the code expects. The two classic causes are a semicolon after a function’s last line, and a number of the wrong type.

    Coming from TypeScriptC#: In TypeScript, a function returns a value only with return.In C#, a method returns a value only with return. In Rust, a function returns its last expression, if there’s no semicolon after it. A semicolon turns the expression into a statement, and the function then returns (), the empty value, so the compiler says “expected u32, found ()” and suggests removing the semicolon.

    fn area(width: u32, height: u32) -> u32 {
        width * height;
    }

    Rust doesn't compile this: error E0308

    error[E0308]: mismatched types
     --> main.rs:1:37
      |
    1 | fn area(width: u32, height: u32) -> u32 {
      |    ----                             ^^^ expected `u32`, found `()`
      |    |
      |    implicitly returns `()` as its body has no tail or `return` expression
    2 |     width * height;
      |                   - help: remove this semicolon to return this value

    Fix: remove the semicolon from the last line.

    fn area(width: u32, height: u32) -> u32 {
        width * height
    }
    
    fn main() {
        println!("{}", area(3, 4));
    }

    Output

    12

    Numbers cause the other half. TypeScript has one number type. Rust has many integer and float types, and never converts between them for you, not even to a bigger type.C# widens an int to a long for you. Rust never converts between number types silently, not even to a bigger type.

    let count: u32 = 3;
    let total: u64 = count;

    Rust doesn't compile this: error E0308

    error[E0308]: mismatched types
     --> main.rs:2:18
      |
    2 | let total: u64 = count;
      |            ---   ^^^^^ expected `u64`, found `u32`
      |            |
      |            expected due to this
      |
    help: you can convert a `u32` to a `u64`
      |
    2 | let total: u64 = count.into();
      |                       +++++++

    Fix: convert explicitly. u64::from(count) (or count.into()) exists only when no value can be lost; use u8::try_from(n) to go smaller.

    let count: u32 = 3;
    let total: u64 = u64::from(count);
    println!("{total}");

    Output

    3

    Learn more: Functions and expressions and Primitive and compound types

    E0277: trait bound not satisfied

    A type doesn’t implement a trait the code needs. The message names both: “Point doesn’t implement std::fmt::Display”, for example. Printing, comparing, sorting, ? and sending values to threads all work through traits, so this one has many faces.

    Coming from TypeScriptC#: In TypeScript, every object can be put in a template string; you just get [object Object] if you didn’t write a toString().In C#, every object has ToString(); you just get the type’s name if you didn’t override it. Rust has no default text for your types. Printing with {} needs the Display trait, which you write yourself, and printing with {:?} needs Debug, which you can derive.

    struct Point {
        x: i32,
        y: i32,
    }
    
    let point = Point { x: 1, y: 2 };
    println!("{point}");

    Rust doesn't compile this: error E0277

    error[E0277]: `Point` doesn't implement `std::fmt::Display`
     --> main.rs:7:11
      |
    7 | println!("{point}");
      |           ^^^^^^^ `Point` cannot be formatted with the default formatter
      |
    help: the trait `std::fmt::Display` is not implemented for `Point`
     --> main.rs:1:1
      |
    1 | struct Point {
      | ^^^^^^^^^^^^
      = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
      = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)

    Fix: derive Debug and print with {:?} while developing, or implement Display for text users will read.

    #[derive(Debug)]
    struct Point {
        x: i32,
        y: i32,
    }
    
    let point = Point { x: 1, y: 2 };
    println!("{point:?}");

    Output

    Point { x: 1, y: 2 }

    Other common forms of the same error:

    • ? can’t convert the error, or ? in a function that returns (): the function’s return type must be a Result whose error type the ? can convert into. See Result and the ? operator.
    • “cannot be sent between threads safely”: a value that isn’t Send, such as an Rc, was moved into thread::spawn. Use Arc. See Send and Sync.
    • “the trait bound {float}: Ord is not satisfied” (or f64: Ord): .sort() needs a total order, which floats don’t have. Use sort_by(f64::total_cmp).
    • “the type str cannot be indexed by {integer}”: strings can’t be indexed by position. Use .chars() or a byte range. See Strings and UTF-8.

    Learn more: Standard traits

    E0599: no method found

    The type has no method with that name. Either the method lives on a different type, or it comes from a trait that isn’t imported.

    Coming from TypeScriptC#: In TypeScript, map and filter are methods of arrays.In C#, LINQ’s Select and Where work on any list through extension methods. In Rust, map, filter and friends are methods of iterators, not of Vec or slices. Call .iter() first, and .collect() at the end to build a collection again.

    fn double(prices: &[i32]) -> Vec<i32> {
        prices.map(|price| price * 2).collect()
    }

    Rust doesn't compile this: error E0599

    error[E0599]: no method named `map` found for reference `&[i32]` in the current scope
     --> main.rs:2:12
      |
    2 |     prices.map(|price| price * 2).collect()
      |            ^^^ `&[i32]` is not an iterator
      |
    help: call `.into_iter()` first
      |
    2 |     prices.into_iter().map(|price| price * 2).collect()
      |            ++++++++++++

    Fix: turn the slice into an iterator first. On a slice, .iter() and the .into_iter() the help: line suggests do the same thing: both yield references to the elements.

    fn double(prices: &[i32]) -> Vec<i32> {
        prices.iter().map(|price| price * 2).collect()
    }
    
    fn main() {
        println!("{:?}", double(&[3, 4, 5]));
    }

    Output

    [6, 8, 10]

    The other cause: a trait’s methods work only where the trait is in scope. TypeScript has no equivalent, because a method is just a property of the object.It’s the same rule as C# extension methods, which need their namespace’s using. Here flush comes from the Write trait, which isn’t imported:

    let mut out = std::io::stdout();
    out.flush().unwrap();

    Rust doesn't compile this: error E0599

    error[E0599]: no method named `flush` found for struct `Stdout` in the current scope
     --> main.rs:2:5
      |
    2 | out.flush().unwrap();
      |     ^^^^^ method not found in `Stdout`
      |
      |
      = note: the method is available for `Stdout` here
      |
      = help: items from traits can only be used if the trait is in scope
    help: trait `Write` which provides `flush` is implemented but not in scope; perhaps you want to import it
      |
      + use std::io::Write;
      |

    Fix: import the trait. The help: line names it.

    use std::io::Write;
    
    fn main() {
        let mut out = std::io::stdout();
        writeln!(out, "Saved").unwrap();
        out.flush().unwrap();
    }

    Output

    Saved

    Learn more: Lazy iterators and Traits

    E0425: cannot find value in this scope

    A name doesn’t refer to anything here: a typo, a variable declared inside a block you’ve left, or a field used without self..

    Coming from TypeScriptC#: TypeScript makes you write this.count inside a method, and Rust is just as strict: a field is always self.count.C# lets you write count inside a method and means this.count. Rust never adds self for you, so a bare count is looked up as a local variable.

    struct Counter {
        count: u32,
    }
    
    impl Counter {
        fn increment(&mut self) -> u32 {
            count += 1;
            count
        }
    }

    Rust doesn't compile this: error E0425

    error[E0425]: cannot find value `count` in this scope
     --> main.rs:7:9
      |
    7 |         count += 1;
      |         ^^^^^
      |
    help: you might have meant to use the available field
      |
    7 |         self.count += 1;
      |         +++++
    
    error[E0425]: cannot find value `count` in this scope
     --> main.rs:8:9
      |
    8 |         count
      |         ^^^^^
      |
    help: you might have meant to use the available field
      |
    8 |         self.count
      |         +++++

    Fix: write self. before every field. For a typo, the help: line usually suggests the name you meant.

    struct Counter {
        count: u32,
    }
    
    impl Counter {
        fn increment(&mut self) -> u32 {
            self.count += 1;
            self.count
        }
    }
    
    let mut counter = Counter { count: 0 };
    counter.increment();
    println!("{}", counter.increment());

    Output

    2

    Learn more: Structs and impl

    E0433: failed to resolve

    The first part of a path (Name::something) isn’t a type, module or crate the compiler can see here. Usually it’s a missing use.

    Coming from TypeScriptC#: In TypeScript, Map and Set are global, so you never import them.In C#, new projects import System.Collections.Generic for you, so Dictionary just works. Rust imports a small set of names into every file, the prelude: Vec, String, Option, Result, Box and a few traits. HashMap, HashSet and everything else need a use.

    let mut ages = HashMap::new();
    ages.insert("Ada", 36);

    Rust doesn't compile this: error E0433

    error[E0433]: failed to resolve: use of undeclared type `HashMap`
     --> main.rs:1:16
      |
    1 | let mut ages = HashMap::new();
      |                ^^^^^^^ use of undeclared type `HashMap`
      |
    help: consider importing this struct
      |
      + use std::collections::HashMap;
      |

    Fix: import the type. The help: line shows the use to add. For a crate, also check it’s listed in Cargo.toml.

    use std::collections::HashMap;
    
    fn main() {
        let mut ages = HashMap::new();
        ages.insert("Ada", 36);
        println!("{ages:?}");
    }

    Output

    {"Ada": 36}

    Learn more: Modules and visibility

    E0369: binary operation cannot be applied

    An operator such as ==, < or + isn’t defined for this type. Operators are traits in Rust, and your own types don’t implement them until you ask.

    Coming from TypeScriptC#: In TypeScript, === works on any two objects, but compares references: two objects with the same fields aren’t equal.In C#, == works on any two class instances, but compares references unless the class overloads it (records do). In Rust, == doesn’t exist for a struct until you derive PartialEq, and then it compares the fields.

    struct Point {
        x: i32,
        y: i32,
    }
    
    let point = Point { x: 1, y: 2 };
    println!("{}", point == Point { x: 1, y: 2 });

    Rust doesn't compile this: error E0369

    error[E0369]: binary operation `==` cannot be applied to type `Point`
     --> main.rs:7:22
      |
    7 | println!("{}", point == Point { x: 1, y: 2 });
      |                ----- ^^ -------------------- Point
      |                |
      |                Point
      |
    note: an implementation of `PartialEq` might be missing for `Point`
     --> main.rs:1:1
      |
    1 | struct Point {
      | ^^^^^^^^^^^^ must implement `PartialEq`
    help: consider annotating `Point` with `#[derive(PartialEq)]`
      |
    1 + #[derive(PartialEq)]
    2 | struct Point {
      |

    Fix: derive the trait behind the operator: PartialEq for ==, PartialOrd for < and >.

    #[derive(PartialEq)]
    struct Point {
        x: i32,
        y: i32,
    }
    
    let point = Point { x: 1, y: 2 };
    println!("{}", point == Point { x: 1, y: 2 });

    Output

    true

    The same error appears when you add two string literals ("a" + "b": use format!, see Strings and UTF-8) and when you compare values of a generic type T without a bound (add T: PartialOrd, see Generics and bounds).

    Learn more: Standard traits

    E0004: non-exhaustive patterns

    A match doesn’t handle every possible value. The message names the cases you missed.

    Coming from TypeScriptC#: A TypeScript switch checks its cases only when something forces it, such as a declared return type or a never check in the default case.A C# switch expression that misses a case only warns, and throws SwitchExpressionException at run time if that case arrives. A Rust match must cover every value, so adding a variant to an enum shows you every match that needs updating.

    enum Status {
        Active,
        Paused,
        Closed,
    }
    
    let status = Status::Closed;
    let label = match status {
        Status::Active => "active",
        Status::Paused => "paused",
    };

    Rust doesn't compile this: error E0004

    error[E0004]: non-exhaustive patterns: `Status::Closed` not covered
     --> main.rs:8:19
      |
    8 | let label = match status {
      |                   ^^^^^^ pattern `Status::Closed` not covered
      |
    note: `Status` defined here
     --> main.rs:1:6
      |
    1 | enum Status {
      |      ^^^^^^
    ...
    4 |     Closed,
      |     ------ not covered
      = note: the matched value is of type `Status`
    help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
      |
    11~         Status::Paused => "paused",
    12~         Status::Closed => todo!(),
      |

    Fix: add the missing arms. For numbers and strings, which can’t be listed in full, end with a _ arm.

    enum Status {
        Active,
        Paused,
        Closed,
    }
    
    let status = Status::Closed;
    let label = match status {
        Status::Active => "active",
        Status::Paused => "paused",
        Status::Closed => "closed",
    };
    println!("{label}");

    Output

    closed

    Learn more: match and destructuring

    Index

    ErrorPlain meaningUsual fix
    E0382Used a value after it movedBorrow with & instead of moving, or .clone()
    E0502Changed a value while it’s borrowed for readingFinish using the & borrow first, or copy the value out
    E0499Two &mut borrows at onceUse one at a time, or split_at_mut / iter_mut
    E0596Changed something that isn’t mutlet mut, or take &mut T
    E0384Reassigned a variable that isn’t mutlet mut, or shadow with a new let
    E0505Moved a value while it’s borrowedUse the borrow before the move, or borrow from the new owner
    E0506Assigned to a variable while it’s borrowedMove or clone the old value out first
    E0597A borrow outlives its valueKeep the owner alive longer, or move the value out
    E0515Returned a reference to a localReturn the owned value (String, Vec<T>)
    E0106Can’t tell what a returned reference borrows fromAdd <'a> to the result and its source; owned struct fields
    E0716Borrowed from a value that’s dropped at the semicolonStore the value in a variable first
    E0308Wrong type, often from a trailing semicolonRemove the last semicolon; convert numbers with from
    E0277A type lacks a trait the code needsDerive or implement the trait, or pick a type that has it
    E0599No such method on this type.iter() before map; use the trait
    E0425Unknown nameFix the typo or scope; write self.field
    E0433Unknown type or module in a pathAdd the use
    E0369Operator not defined for this typeDerive PartialEq / PartialOrd; use format! for strings
    E0004A match misses some casesAdd the missing arms, or a _ arm