0
0
Rustprogramming~20 mins

Type inference in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust Type Inference Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2: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);
}
A15
B15.0
C15.00
DCompilation error
Attempts:
2 left
๐Ÿ’ก Hint
Remember that Rust infers types and you can cast integers to floats.
โ“ Predict Output
intermediate
2: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());
}
ACompilation error due to ambiguous type
BVec<u32>
CVec<f64>
DVec<i32>
Attempts:
2 left
๐Ÿ’ก Hint
Integer literals default to i32 unless specified otherwise.
๐Ÿ”ง Debug
advanced
2: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);
}
ACannot add &str to &str directly; no implementation of `Add` for &str
Bprintln! macro syntax error
CVariable y is not mutable
DMissing semicolon after let x declaration
Attempts:
2 left
๐Ÿ’ก Hint
In Rust, string slices (&str) cannot be added with + operator directly.
โ“ Predict Output
advanced
2: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);
}
ACompilation error due to mismatched types
B6.0
C6
DRuntime panic
Attempts:
2 left
๐Ÿ’ก Hint
Rust does not automatically convert integer to float in arithmetic.
๐Ÿง  Conceptual
expert
2: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);
}
ACompilation error due to ambiguous type
BT is inferred as u32
CT is inferred as i32
DT is inferred as f64
Attempts:
2 left
๐Ÿ’ก Hint
Integer literals default to i32 unless specified otherwise.