SoFunction
Updated on 2025-03-10

Can a method in Rust language trait be rewritten?

In Rust,traitA set of methods is defined that can be implemented by one or more types. When you implement a typetraitWhen you cantraitEach method in provides its own concrete implementation. This means that when you implement the same for different typestraitWhen these methods can be implemented differently. This can be considered a "rewrite".

In addition, iftraitA method in this method has a default implementation, so that is implemented for a certain typetraitWhen you choose to override this default implementation.

Here is a simple example to illustrate this concept:

trait SayHello {
    fn hello(&self) {
        println!("Hello from the default implementation!");
    }
}
struct Person;
impl SayHello for Person {
    fn hello(&self) {
        println!("Hello from the Person's implementation!");
    }
}
struct Animal;
impl SayHello for Animal {}  // Use the default implementationfn main() {
    let p = Person;
    ();  // Print "Hello from the Person's implementation!"    let a = Animal;
    ();  // Print "Hello from the default implementation!"}

In the above example,PersonforSayHellotrait provides its ownhelloThe implementation of the method, andAnimalThe default implementation is used.

But if you mean, is it possible to be the same on the same typetraitProvide two different implementations, the answer is not possible. Each type is for the sametraitThere can only be one implementation.

This is the end of this article about whether a method in Rust language can be rewritten. For more related Rust Rust rewrite content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!