Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Cow:

use std::borrow::Cow;  // Cow = clone on write
let example = Cow::from("def")

I would like to get the def back out of it, in order to append it to another String:

let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");
// here I would like to do:
alphabet.push_str(example);

This does not work and I don't see the appropriate method in Cow to get the &str or String back out.

like image 929
Zelphir Kaltstahl Avatar asked Nov 07 '17 00:11

Zelphir Kaltstahl


People also ask

Can you increase your own YouTube Views?

If you want to get more views on YouTube, you need to respond to viewer comments, create video playlists, design attention-grabbing thumbnails and more.


2 Answers

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(); 
like image 167
Shepmaster Avatar answered Sep 29 '22 12:09

Shepmaster


Pass a reference to example (i.e. &example) to push_str.

let mut alphabet: String = "ab".to_string();
alphabet.push_str("c");  
alphabet.push_str(&example);

This works because Cow implements Deref.

like image 39
hwiechers Avatar answered Sep 29 '22 12:09

hwiechers