0

I have a struct with one member:

pub struct Term<'a>(pub &'a str);

I also have a Vec<Term> and I want to convert the Vec to Iterator and then lowercase the &str, like:

pub fn add_vec(document: Vec<Term<'a>>) {
    let m_term = document.into_iter().map(
        |dx| Term(dx.0.to_lowercase().as_str())
    ).collect::<Vec<_>>();
}

but I'm seeing this error:

error: borrowed value does not live long enough
  --> src/tfidf.rs:47:23
   |
47 |             |dx| Term(dx.0.to_lowercase().as_str())
   |                       ^^^^^^^^^^^^^^^^^^^         - temporary value only lives until here
   |                       |
   |                       temporary value created here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the block at 44:55...

I think I understand what the problem is, but I don't know how can I convert the String result of to_lowercase() to a &str with lifetime of 'a.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201
  • 2
    You cannot. Since `to_lowercase` returns a `String` and nothing owns that `String`, any references to it will become invalid as soon as the closure ends and the memory is deallocated. That's why you get the error that the `String` doesn't live long enough. If you could, you'd end up triggering memory unsafety. Your only option is to return the `String`, transferring ownership of the allocation. That may involve you changing your `Term` struct likewise. – Shepmaster Mar 29 '17 at 22:48
  • thanks @Shepmaster. What do you mean by returning the `String` and then transferring the ownership? could you please provide a short example? – Afshin Mehrabani Mar 30 '17 at 07:59
  • Even better, there's an [entire chapter of *The Rust Programming Language* dedicated to ownership](https://doc.rust-lang.org/stable/book/ownership.html). – Shepmaster Mar 30 '17 at 12:59

0 Answers0