Versions Compared

Key

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

...

  1. Consider two traits

    1. From<String>

    2. From<&'static str>

  2. The enum Cow<'static, str> Cow<str> implements both traits

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

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

  3. Consider another trait

    1. Into<Cow<'static, str>>Into<Cow<str>>

  4. A From implementation implies that there is a corresponding Into implementation. There is a blanket implementation of Into in the standard library. My guess is that the following code is the blanket implementation

    Code Block
    languagerust
    impl<T,U> Into<U> for T
       where U: From<T> {
       
      fn into(self) -> U {
        U::from(self)
      }  
    }
  5. Therefore String implements the Into<Cow<'static,str>> Into<Cow<str>> trait

    Code Block
    languagerust
    implimpl<'a> Into<Cow<'statica, str>> for String {
      fn into(self) -> Cow<'statica, str> {
        ...
      }
    }

    Consider the additional trait

  6. String automatically implements Into, as does str, given that the From traits are implemented

  7. Both String and str implement Into with a method of the following form

    fn into(self) → Cow<a', str>

    Also &str implements the Into<Cow<str>> trait

    Code Block
    impl<'a> Into<Cow<'a, str>> for &'a str {
      fn into(self) -> Cow<'a, str> {
        ...
      }
    }
  8. In the first four arms of the match expression, there are string literals upon which the method into() is called. We know the methods must have a return type of Cow<'static, str>.

  9. A string literal is of type &str, a shared reference to a string slice

  10. A string literal has a static lifetime.

  11. When applying the method Therefore the result of calling the into(), the method on a string literal is dereferenced into a string slice strThen the method into() can be applied on the str. We have already seen that this method exists.a Cow<'static, str>

  12. Also we can call the into() method on a String to get a Cow<'static, str> without any lifetime limitations on the String