Back to questions
JuniorTheoryCommon
What does the program print?
trait Greet {
fn hi(&self) -> String {
String::from("hello")
}
}
struct En;
impl Greet for En {}
fn main() {
println!("[{}]", En.hi());
}[hello]
- Expecting a compile error because
impl Greet for En {}writes no methods: E0046 is raised only for a trait method with no body, andhihas a default one. - Expecting the empty braces to make
hireturn nothing: a method left out of theimplkeeps the trait's default body, so it returnshello.
- How would
Enoverridehi, and could its version still call the default body? - Which error do you get if the body of
hiis removed from the trait?