Challenge - 5 Problems
Rust Type Inference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ Predict Output
intermediate2:00remaining
What is the output of this Rust code using type inference?
Consider the following Rust code snippet. What will it print when run?
Rust
fn main() {
let x = 5;
let y = 10.0;
let z = x as f64 + y;
println!("{}", z);
}Attempts:
2 left
๐ก Hint
Remember that Rust infers types and you can cast integers to floats.
โ Incorrect
The integer x is cast to f64, then added to y which is f64. The result is printed as 15.0 by println! macro.
โ Predict Output
intermediate2:00remaining
What type does Rust infer for this variable?
Look at this Rust code. What type does Rust infer for variable `v`?
Rust
fn main() {
let v = vec![1, 2, 3];
println!("{}", v.len());
}Attempts:
2 left
๐ก Hint
Integer literals default to i32 unless specified otherwise.
โ Incorrect
Rust infers the vector type as Vec because the integer literals are i32 by default.
๐ง Debug
advanced2:00remaining
Why does this Rust code fail to compile?
This Rust code does not compile. What is the cause of the error?
Rust
fn main() {
let x = "hello";
let y = x + " world";
println!("{}", y);
}Attempts:
2 left
๐ก Hint
In Rust, string slices (&str) cannot be added with + operator directly.
โ Incorrect
Rust does not implement the + operator for &str and &str. You must convert to String or use format! macro.
โ Predict Output
advanced2:00remaining
What is the output of this Rust code with type inference and shadowing?
Analyze this Rust code. What will it print?
Rust
fn main() {
let x = 5;
let x = x + 1.0;
println!("{}", x);
}Attempts:
2 left
๐ก Hint
Rust does not automatically convert integer to float in arithmetic.
โ Incorrect
The first x is i32, the second x tries to add i32 + f64 which is a type mismatch causing a compile error.
๐ง Conceptual
expert2:00remaining
How does Rust's type inference handle generic functions?
Given this generic function, what type does Rust infer for `T` when calling `identity(42)`?
Rust
fn identity<T>(x: T) -> T {
x
}
fn main() {
let a = identity(42);
println!("{}", a);
}Attempts:
2 left
๐ก Hint
Integer literals default to i32 unless specified otherwise.
โ Incorrect
Rust infers T as i32 because 42 is an integer literal defaulting to i32.