Start learning free

LESSON 6 OF 679 · WELCOME TO RUST

Name Errors in Rust

Lesson

TL ; DR:

  • A name error occurs when Rust sees a word it does not recognize. Some examples:

  • Misspelling a function name:

    prntln!("Heyooo!"); // error: cannot find macro `prntln` in this scope
    

  • Misspelling a variable name:

    let animal: &str = "parrot";
    println!("{}", anmal); // error[E0425]: cannot find value `anmal` in this scope
    

  • When Rust encounters a name error, it refuses to compile your code and reports an error instead, so the program never runs.




Full lesson:

Humans are prone to making mistakes. Humans are also typically in charge of creating computer programs. To compensate, programming languages attempt to understand and explain mistakes made in their programs.

Here are two common errors that we encounter while writing Rust code:


The syntax error:

Syntax errors are mistakes in the use of the Rust language, and are analogous to spelling or grammar mistakes in a language like English. For example, the sentence "Would you some tea?" does not make sense – it is missing a verb.

Syntax error means there is something wrong with the way your program is written. Some examples:

1. Misuse of commas when declaring a string:

let greeting: &str = 'Hey there!";

When we compile this code we'll get an error[E0765]: unterminated double quote string.

2. Leaving out an important character:

println "Hey";

When we compile this code we'll get an error: expected one of `!`, `.`, `::`, `;`, `?`, `{`, `}`, or an operator, found `"Hey"`.


The reference error:

A reference error occurs when the Rust compiler sees a word it does not recognize. A common example:

Using a non-existent variable / Misspelling a variable's name:

let animal: &str = "parrot";
println!("{}", aniimal);

When we compile this code we'll get an error[E0425]: cannot find value `aniimal` in this scope.


Assignment
Follow the Coding Tutorial and let's practice with errors!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check