Versions Compared

Key

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

...

  1. Consider two traits

    1. From<String>

    2. From<&str>

  2. The enum Cow<str> implements both traits

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

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

  3. Consider another trait

    1. 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<str>> trait

    Code Block
    languagerust
    impl<'a> Into<Cow<'a, str>> for String {
      fn into(self) -> Cow<'a, str> {
        ...
      }
    }
  6. 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> {
        ...
      }
    }
  7. In the first four arms of the match expression, there are string literals upon which the method into() is called. We know these method calls must return a Cow<'static, str>

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

  9. A string literal has a static lifetime.

  10. Therefore the result of calling the into() method on a string literal is a Cow<'static, str>

  11. So, we see now how the first four arms of the match expression work.

  12. In the last arm of the match expression, there is a String upon which the method into() is called. This method call must return a Cow<'static, str>

  13. We can call the into() method on a String to get a Cow<str> without any lifetime limitations between the String and the Cow<str>

  14. So the returned Cow<str> can be annotated with a static lifetime, without requiring that the String had to have one, too.

  15. So, we see now how the fifth arm of the match expression works.