How do I get a &str or String from std::borrow::Cow?

How do I get a &str

  1. Use Borrow:

    use std::borrow::Borrow;
    alphabet.push_str(example.borrow());
    
  2. Use AsRef:

    alphabet.push_str(example.as_ref());
    
  3. Use Deref explicitly:

    use std::ops::Deref;
    alphabet.push_str(example.deref());
    
  4. Use Deref implicitly through a coercion:

    alphabet.push_str(&example);
    

How do I get a String

  1. Use ToString:

    example.to_string();
    
  2. Use Cow::into_owned:

    example.into_owned();
    
  3. Use any method to get a reference and then call to_owned:

    example.as_ref().to_owned();
    

Leave a Comment