-
|
https://google.github.io/comprehensive-rust/generics/impl-trait.html Does this mean the return type of BTW, I think the code in this page can be more understandable like use std::fmt::Display;
fn get_x(name: impl Display) -> impl Display {
format!("Hello {name}")
}
fn main() {
let x = get_x("foo");
let y = get_x(123);
println!("{x}");
println!("{y}")
}This can better show the idea of
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Hi @Luosuu, Yeah, the instructor should highlight that As for the return type, you're right that it's This is different from the generic in the argument position: the type of Does that help a bit? Generics is a complex topic and I need to expand the slides with significant amounts of speaker notes to fully explain this 😄 |
Beta Was this translation helpful? Give feedback.
Hi @Luosuu,
Yeah, the instructor should highlight that
get_xcan be called on both integers and strings! Let us add that to the speaker notes...As for the return type, you're right that it's
impl Display. The return type is chosen by the person who writesget_x. The caller can only rely onDisplaybeing implemented, nothing more.This is different from the generic in the argument position: the type of
nameis chosen by the caller ofget_x. The person who write the function cannot know anything about the type, except that it implementsDisplay. This allowsnameto be used withformat!as shown in the example.Does that help a bit? Generics is a complex topic and I need to expand the slide…