Can the default method be overridden?

It can.

The code for this section is in 09/override_default_method.

Let's start the code off by defining a trait. This has a default method for is_not_done. We will still need to implement is_done though, which we do for the UseFirstTime struct:

struct UseFirstTime; 
impl MyTrait for UseFirstTime
{
fn is_done(&self) -> bool
{
println!("UseFirstTime.is_done");
true
}
}

We next want to override the default method for is_not_done. Again, we create an empty struct and write both the implementations for is_done and is_not_done. When we call is_not_done from the second struct, the println! from the second struct is shown and not the first:

struct OverrideFirstTime;
impl MyTrait for OverrideFirstTime
{
fn is_done(&self) -> bool
{
println!("OverrideFirstTime.is_done");
true
}
fn is_not_done(&self) -> bool
{
println!("OverrideFirstTime.is_not_done");
true
}
}

When compiled, we get the following output:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset