Type of a variable

Please take a look at the following expression:

If the type of a variable or an expression hasn’t yet been determined at all, and such variable or expression is used in an expression or in a declaration that can be valid only with a specific type, then that type is determined in this way for such variable or expression. Such determination may be of a constrained kind, or it may be of an unconstrained kind. A constrained type is a specific type, like i8 or u64, while an unconstrained type is a category of types, like {integer}.

Does this phrase mean that if the type of the variable is not defined, then the compiler can determine the type of the variable based on the value that is put into that variable. Am I right?

Thank you.

Yes, that's one of the implications. More generally it can often (but not always) determine the type of an expression based on its context.

It's called "type inference".

fn takes_a_string_ref(_: &String) {}

fn print_type_name_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>());

fn main() {
    // Could be any type that implements `Default` based on this line alone
    let variable = Default::default();
    // From this line, the compiler figures out that `variable: String`

Aside: When you quote some other source, it's usually a good idea to let readers know where it comes from, ideally with a link to an online version— Sometimes the context around the quoted material is important to its meaning (not so much in this case).


Thank you so much for your reply.
I copied that text from Beginning Rust: Get Started with Rust 2021 Edition 2nd ed. Edition by Carlo Milanesi book.

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.