1

What's the difference between str and String::from in this example

use std::borrow::Cow;


fn main() {

    let s = "Hello world!";
    
    let cow: Cow<str> = Cow::Owned(s);
    // type mismatch resolving `<str as std::borrow::ToOwned>::Owned == &str`
    //expected struct `std::string::String`, found `&str`
    
    // ok
    let cow: Cow<str> = Cow::Owned(String::from(s)); 
    
}
hewc
  • 119
  • 6

1 Answers1

5

Cow::Owned takes as input the associated type Owned of the generic parameter (which must implement ToOwned). For str, this is String. Therefore, s itself cannot be used in Cow::Owned(s).

Emoun
  • 2,297
  • 1
  • 13
  • 20