How to call methods that use custom implementation trait?

Consider this example:

use std::collections::BTreeMap;
trait Map<K, V> {
    fn insert(&mut self, key: K, value: V) -> Option<V>;
impl<K: ToString, V> Map<K, V> for BTreeMap<K, V> {
    fn insert(&mut self, key: K, value: V) -> Option<V> {
        println!("{}", key.to_string());
fn main() {
    let mut map = BTreeMap::new();
    let output = map.insert("key", "value");
    // expected output: `Some("value")`
    println!("{:?}", output); // But Got: `None`

As you can see I am trying to call a method in Map<K, V> trait, that has a method called insert(..),

Why rust didn't called that method (insert) from Map<K, V> trait, Why It didn't work?

But, If I rename this method in different name, let say set(..), It worked!

Inherent methods, in this case BTreeMap::insert, always take precedence over trait methods of the same name. You can call it like this¹ to explicitly use the trait method:

let output = Map::<_,_>::insert(&mut map, "key", "value");

¹ The turbofish ::<_,_> might be optional in this case; I'm not sure.

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.