How Rust compiler generates error messages?

fn main() {
    let string_parse = "54".parse().expect("u32 expected!");
    println!("{}", string_number);
}

If I compile and run the above code, get the below error:

image

But, if I omit the print line (as below):

fn main() {
    let string_parse = "54".parse().expect("u32 expected!");
    //println!("{}", string_number);
}

get the below error:

image

Now, my question is, what error generation principle is being followed by Rustc here?

Though the underlying error is error[E0282]: type annotations needed, with addition of print line the error is being thrown is error[E0425]: cannot find value string_number in this scope

Or, am I thinking in wrong way?

  • Supratik
1 Like

In the first line you have string_parse but in the second you have string_number.

Since the latter does not exist, the compiler is throwing an error immediately, and not proceeding to type checking, which is where the second error is coming up.

1 Like

To assign and check types, the compiler needs to see all expressions in a function. To know all the expressions it needs to parse the whole function. To know where the function starts and ends, it needs to read the syntax and expand macros correctly.

So you will get errors about syntax and macros first. Then you will get errors related to expressions that can't be constructed (like reference to undefined variables), and only then you will get errors about types.

But generally nothing about order or specificity of errors is guaranteed, other than invalid code will be rejected in some way or another. How it's communicated depends on implementation details, and changes often.

2 Likes

Good information to know. Thanks!

I just didnt realize that I am using two different variable names and confused myself. Thanks! You answered my question; rather caught my mistake! :smiley:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.