// Make the code compile by completing the function signature of `print_message`.
trait Message {
fn message(&self) -> String {
"How are you?".to_string()
}
}
trait Printer {
fn print(&self, printable: &impl Message) {
println!("Message is: {}", printable.message());
}
}
struct M;
struct P;
impl Message for M {}
impl Printer for P {}
fn print_message<T, U>(msg, printer)
where
{
printer.print(msg);
}
fn main() {
let m = M;
let p = P;
print_message(&m, &p);
}
Solution
trait Message {
fn message(&self) -> String {
"How are you?".to_string()
}
}
trait Printer {
fn print(&self, printable: &impl Message) {
println!("Message is: {}", printable.message());
}
}
struct M;
struct P;
impl Message for M {}
impl Printer for P {}
fn print_message<T, U>(msg: &T, printer: &U)
where T: Message,
U: Printer,
{
printer.print(msg);
}
fn main() {
let m = M;
let p = P;
print_message(&m, &p);
}
// Complete function signature of `get_bigger`.
// Only Addable trait's functions should be callable on its return value.
trait Addable {
fn add_one(&self) -> Self;
fn are_equal(a: &Self, b: &Self) -> bool;
}
impl Addable for u8 {
fn add_one(&self) -> Self {
if *self == u8::MAX {
*self
} else {
self + 1
}
}
fn are_equal(a: &Self, b: &Self) -> bool {
a == b
}
}
fn get_bigger(a: u8, b: u8) -> {
if a > b {
a
} else {
b
}
}
fn main() {
let (num1, num2) = (125, 220);
let bigger = get_bigger(num1, num2);
if Addable::are_equal(&bigger, &bigger.add_one()) {
println!("Bigger number has max value")
} else {
println!("Both numbers are smaller than max value");
}
}
Solution
trait Addable {
fn add_one(&self) -> Self;
fn are_equal(a: &Self, b: &Self) -> bool;
}
impl Addable for u8 {
fn add_one(&self) -> Self {
if *self == u8::MAX {
*self
} else {
self + 1
}
}
fn are_equal(a: &Self, b: &Self) -> bool {
a == b
}
}
fn get_bigger(a: u8, b: u8) -> impl Addable {
if a > b {
a
} else {
b
}
}
fn main() {
let (num1, num2) = (125, 220);
let bigger = get_bigger(num1, num2);
if Addable::are_equal(&bigger, &bigger.add_one()) {
println!("Bigger number has max value")
} else {
println!("Both numbers are smaller than max value");
}
}