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 results , options. 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(&current_line) {          let new_flag = &flag_re.captures(&current_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

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -