I want to return the reference type, but the first make_debug
function implementation does not compile. What is the difference between using T
or impl std::fmt::Debug
for the return type of this function signature?
fn test() -> impl std::fmt::Debug + 'static {
let value = "v".to_string();
make_debug(&value)
}
// This function not work
// fn make_debug<'a, T: std::fmt::Debug>(_: &'a T) -> T {
// 42u8
// }
// This one works well
fn make_debug<'a, T: std::fmt::Debug>(_: &'a T) -> impl std::fmt::Debug {
42u8
}
Using -> impl std::fmt::Debug
means "Hey, I'm gonna return you something of a type that implements Debug, but i don't know what that type is".
while using -> T
means "Hey, I'm gonna return something of the T type, which happens to implement Debug"
So the difference is, in the first case you can return a different type than the input and it will work as long as it implements the Debug trait. While the second case you MUST return something of the same type as the Input.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments