In Rust,trait
A set of methods is defined that can be implemented by one or more types. When you implement a typetrait
When you cantrait
Each method in provides its own concrete implementation. This means that when you implement the same for different typestrait
When these methods can be implemented differently. This can be considered a "rewrite".
In addition, iftrait
A method in this method has a default implementation, so that is implemented for a certain typetrait
When 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,Person
forSayHello
trait provides its ownhello
The implementation of the method, andAnimal
The default implementation is used.
But if you mean, is it possible to be the same on the same typetrait
Provide two different implementations, the answer is not possible. Each type is for the sametrait
There 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!