Rust allow same name procedure

Can someone explain this to me.
why same procedure name allowed, if we put on trait implementation.


struct Example {
    test: i32
}

trait ExampleExt {
    fn set_inner(&mut self, value: i32);
}

impl Example {
    fn new() -> Self {
        Example{
            test: 20,
        }
    }

    fn set_inner(&mut self, value: i32) {
        self.test = value;
    }

    fn get_inner(&self) -> i32 {
        self.test
    }
}


impl ExampleExt for Example {
    // why this proc name allowed.
    fn set_inner(&mut self, value: i32) {
        self.test = value;
    }
}

fn main() {
    let mut example = Example::new();
    assert_eq!(example.get_inner(), 20);

    example.set_inner(40);
    assert_eq!(example.get_inner(), 40);
}

Because otherwise struct definition would be able to break already-existing trait implementations with otherwise non-breaking change.

1 Like

So which one when we call same name procedure will executed.

When it's ambiguous between traits you have to be specific by using qualified paths.

2 Likes

this is rust normal condition when we have same name in trait?.

Yes, the compiler will choose the implicit inherent implementation over trait implementations (because you can only have one implicit inherent implementation), but refuses to choose between the same procedure name between trait implementations (as you could have any number of those). So if you have a conflict and want a (specific) trait procedure, you have to be explicit using the qualified path.

2 Likes

Could you explain a little, why this implementation is "implicit"?

2 Likes

Sorry, I meant inherent. (Edited the post.)

somehow, i found this when put some code for refactoring.

yes i know, usually trait separated. implicit when we not use "for" keyword in trait.
just curious.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.