rust - What is the best pattern for working with regex results? -
i javascript dev looking game rust. i've read the rust programming language, completed tutorials, , added rust node project using ffi. speed parser wrote think i'm missing fundamental ownership concept.
the current challenge simple: evaluate regex named capture , change value of variable new captured value.
i've tried fifteen ways using unwrap
or nesting result
s , option
s. comes down 'does not live long enough' error.
my recent code looks this:
let flag_re = compile_re(r"(?:\s*)([~])(?:\s*)(?p<flag>.)"); let mut flag : &str = "v"; line in file.lines() { let mut current_line : string = line.unwrap(); if flag_re.is_match(¤t_line) { let new_flag = &flag_re.captures(¤t_line).unwrap().name("flag").unwrap().clone(); println!("old flag: {} new flag: {}",flag,new_flag); flag = new_flag; }
this works great if comment out flag = new_flag
line. once try assign value flag
'does not live long enough' on current_line
variable. current_line
short lived i've tried clone
, to_owned
no luck , leading me i've got misunderstanding of concepts.
i've tried recreate in rust playground code:
fn main() { let mut a: &str; { let b: &str = "b"; = b; } println!("a: {} ",a); }
but (wouldn't know) works? please gentle on javascript guy.
the problem new_flag
borrowed line
. is, new_flag
can only exist long line
continues exist. once fall out of loop, line
destroyed.
the simplest way handle switch borrowed string (&str
) owned string (string
). is, want value owns contents there no borrowing in play. appropriate changes be:
let mut flag = string::from("v"); // 1 way of constructing string &str ... flag = new_flag.into(); // way, using inference
a slightly more efficient alternative use std::borrow::cow
, that's unnecessary in context.
Comments
Post a Comment