HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMinor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfromstrstdcowstringborrowget

Problem

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.

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#47147844, score: 18

Revisions (0)

No revisions yet.