Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `impl ... for` mean?

Tags:

rust

I see the following pattern coming up a lot in Rust codebases, but I can't find an explanation why this is used.

For what end does one use the impl ... for construction?

Pseudocode:

impl Handler {
    pub fn method1() -> () {
    }
}
impl Dummy for Handler {
    pub fn method2() -> () {
    }
}
like image 803
Gaston Lagaffe Avatar asked Jan 31 '21 08:01

Gaston Lagaffe


1 Answers

impl Struct ... adds some methods to Struct. These methods aren't available to other types or traits.

impl Trait for Struct .. implements the trait Trait for the struct Struct. This results in the methods of the trait being available for Struct.

So, even though these two syntaxes look similar, they do 2 completely different things. impl Struct ... adds new (not previously defined) methods to the type, while the other adds previously defined methods (from the trait) to the type.

like image 199
Emoun Avatar answered Oct 11 '22 09:10

Emoun