Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Part A - We can implement methods directly on shared references reference types themselves. There is no dereferencing then deref coercion then when called on a shared reference that is of that shared reference type (playground)

In a sense then the method implemented, when called on a shared reference, takes ownership of the shared reference, per se, not the value the shared reference points to.

Code Block
languagerust
use std::borrow::Cow;

trait CustomInto<T> {
    fn custom_into(self) -> T;
}

impl<'a> CustomInto<Cow<'a, str>> for &'a str {
    fn custom_into(self) -> Cow<'a, str> {
        Cow::Borrowed(self)
    }
}

fn main(){
    let _cow = "hello there".custom_into();    
}

In this code, the implementation is for the ref string slice type, not the primitive string slice type.

Part B -

  1. Consider two traits

    1. From<String>

    2. From<&'a str>

  2. Cow<'a, str> implements both traits

    1. Cow has the associated function
      fn from(s: String) → Cow<'a, str>

    2. Cow has another associated function
      fn from(s: &'a str) → Cow<'a, str>

  3. Therefore String implements<

...