0
0
Rustprogramming~5 mins

Type inference in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is type inference in Rust?
Type inference is Rust's ability to automatically figure out the type of a variable based on the value assigned to it, so you don't always have to write the type explicitly.
Click to reveal answer
beginner
How does Rust infer the type of <code>let x = 5;</code>?
Rust sees the value 5 is an integer, so it infers that x is of type i32 by default.
Click to reveal answer
intermediate
Can Rust infer types for function return values without explicit annotations?
Yes, Rust can infer the return type if it can figure it out from the function body, but sometimes you need to specify it for clarity or when inference is not possible.
Click to reveal answer
intermediate
What happens if Rust cannot infer a variable's type?
Rust will give a compile-time error asking you to specify the type explicitly because it needs to know the exact type to ensure safety.
Click to reveal answer
beginner
Example: What type does Rust infer for <code>let name = "Alice";</code>?
Rust infers the type as &str, which is a string slice pointing to a string literal.
Click to reveal answer
What type does Rust infer for let num = 10; if no type is specified?
AString
Bf64
Ci32
Dbool
If Rust cannot infer a variable's type, what will happen?
AIt will throw a compile-time error.
BIt will guess the type randomly.
CIt will assign the type as 'any'.
DIt will run the program anyway.
Which of these can Rust infer the type for automatically?
AFunction return type when it is clear.
BType of a variable declared but never assigned.
CType of a variable assigned from user input without parsing.
DType of a variable assigned from a function with multiple return types.
What type does Rust infer for let flag = true;?
Ai32
Bbool
CString
Dchar
Why is type inference helpful in Rust?
AIt removes the need for types completely.
BIt slows down the compiler.
CIt allows variables to change type at runtime.
DIt makes code shorter and easier to read.
Explain what type inference is in Rust and give an example.
Think about how Rust figures out variable types without you writing them.
You got /3 concepts.
    Describe a situation where Rust cannot infer a type and what you should do.
    When Rust is unsure, it asks you to help by writing the type.
    You got /3 concepts.