In Rust Book Brown University Chapter 10.2 2nd Quiz Question 1 states:
Determine whether the program will pass the compiler. If it passes, write the expected output of the program if it were executed.
use std::fmt::Display;
fn displayable<T: Display>(t: T) -> impl Display { t }
fn main() {
let s = String::from("hello");
let mut s2 = displayable(s);
s2.push_str(" world");
println!("{s2}");
}
Spoler alert, it doesn’t compile.
It’s explained that it could compile if the return type was changed to T
instead of impl Display
.
This left me curious, I’m thinking the compiler will always be able to infer the type. The reason being that the return type of a function cannot be conditional (also stated in ch. 10.2) and thus the return type is either
-
- Constant, always the same independent of any of the argument types
-
- Same as one of the arguments
I am wrong or are you simply forced to be explicit about the return type event though it could be inferred?