Cannot assign to `cigar_str` because it is borrowed

use once_cell::sync::Lazy;
use regex::Regex;

pub static BEGIN_NUMBER_D: Lazy<Regex> = Lazy::new(|| Regex::new(r"^(\d+)D").unwrap());

pub static END_NUMBER_D: Lazy<Regex> = Lazy::new(|| Regex::new(r"(\d+)D$").unwrap());

pub struct ModifiedCigar {
    pub position: i64,
    pub cigar: String,
    pub query_sequence: String,
    pub query_quality: String,

pub(crate) struct CigarModifier {
impl CigarModifier {
    pub(crate) fn modify_cigar(&mut self) -> ModifiedCigar {
        // self.cigar_str() returns &str
        let mut cigar_str:Cow<'_, str> = Cow::from(self.cigar_str());

        if let Some(caps) = BEGIN_NUMBER_D.captures(cigar_str.borrow()) {
            cigar_str = BEGIN_NUMBER_D.replace(cigar_str.borrow(), "");

        if let Some(caps) = END_NUMBER_D.captures(cigar_str.borrow()) {
            cigar_str = END_NUMBER_D.replace(cigar_str.borrow(), "");

error[E0506]: cannot assign to `cigar_str` because it is borrowed
  --> src/modules/
69 |             cigar_str = BEGIN_NUMBER_D.replace(&cigar_str.borrow(), "");
   |             ^^^^^^^^^                           --------- `cigar_str` is borrowed here
   |             |
   |             `cigar_str` is assigned to here but it was already borrowed
   |             borrow later used here

I want to keep modifying input string with replace() method and track it in cigar_str variable.

My first trial is the above, but failed to compile it.

How could I fix this?

Any help would be appreciated.

Can you provide a full working example? It's a bit hard to figure it out without knowing what ModifiedCigar and BEGIN_NUMBER_D are

1 Like

I agree it would be easier to help you if you provided more information. I gave it a shot based on my best guess anyway.

You can use shadowing instead of mutability.

You can stick with &strs instead of Cows.

Same thing but without the unused (in the example given) captures.

Incidentally I suggest just using &*cow instead of (what I presume is) the Borrow trait and cow.borrow().

1 Like

Oops, sorry. edited it.

I've found a post comparing shadowing vs mutable in terms of performance:

If you care about performance on this level, I'd suggest some other way to trim your prefixes and suffixes. Replacing regexen are a relatively heavy wait approach to trimming.

If you don't have any particular reason to care about performance yet, I wouldn't worry about it at all.

1 Like