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());
Some(value)
}
}
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!