Trait with Default Method
Write a Rust function that defines a trait Greet with a method loud(&self) -> String that has a default implementation, and overrides it for a custom struct. The default implementation converts the string to uppercase and appends "!". An override for a different struct appends "!!!" instead.
Traits in Rust can provide default method implementations. Types that implement the trait can either use the default or override the method with their own implementation. This is similar to abstract base classes in other languages but without inheritance. Default methods are defined with a method body in the trait declaration.
Default trait methods enable the template method pattern and provide sensible defaults while allowing customization. They are widely used in the standard library (e.g., Iterator has many default methods built on top of next()). A default method can call other trait methods, making it a powerful abstraction tool.
Time complexity is O(n) where n is the string length, due to the to_uppercase() call. Space complexity is O(n) for the new String allocation. The method dispatch is static (monomorphized) since the trait is used as a bound on a generic type.
Edge cases include empty strings (uppercase of empty is empty), strings with special characters or Unicode (to_uppercase handles Unicode correctly), and ensuring the default implementation uses self.to_uppercase() for the conversion.
Example Input & Output
Default for rust
Override for rust
Default: uppercased with !
Default for short string
Override: three ! instead of one
Algorithm Flow

Solution Approach
Best Answers
trait Greet {
fn loud(&self) -> String;
}
impl Greet for String {
fn loud(&self) -> String {
format!("{}!", self.to_uppercase())
}
}
struct Exclaim(String);
impl Greet for Exclaim {
fn loud(&self) -> String {
format!("{}!!!", self.0.to_uppercase())
}
}
fn solution(s: String, mode: String) -> String {
if mode == "extra" {
Exclaim(s).loud()
} else {
s.loud()
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
