Cows for "Strings that might change"?

I have a lot of String data to process. Luckily, the vast majority of the fields are parsed into my types and then rewritten out in a way that never requires full ownership (i.e. their elevation to a String). When ran, this turns out to be much faster than I ever though it could be, and Rust really impressed me.

My types look something like this:

struct Foo<'a> {
    a: &'a str,
    b: &'a str,
    c: &'a str,
    // ... etc. 
}

In a few rare cases, one of these fields needs to be tweaked before writing. The tweak unfortunately needs to be persisted, I can't immediately write it. So, String has to come into play somewhere.

This seems to me a place to use Cow. "Keep it as an unmodified reference in most cases, but use a copied String in the few cases where necessary". Is that right? Or is there a better way to represent what I'm attempting? (re: Tricky Cow Ownership)

Please and thanks.

Cow is the right type for this. If you create a new string arbitrarily, it will have to be freed, and something has to store a boolean saying so.

5 Likes