rust - How do I return a Vector created using a for loop? -


this question has answer here:

i wanted create data using loop. used following that.

struct message<'a> {     msg: &'a str }  fn loop_function<'a>() -> vec<message<'a>> {     let mut result = vec![];     x in 0..10 {         result.push(message { msg: format!("{}", x).trim() });     }     result }  fn main() {     loop_function(); } 

but when try compile following error related lifetime of x.

src/main.rs:8:33: 8:49 error: borrowed value not live long enough src/main.rs:8       result.push(message { msg: format!("{}", x).trim() });                                                ^~~~~~~~~~~~~~~~ src/main.rs:5:44: 11:2 note: reference must valid lifetime 'a defined on block @ 5:43... src/main.rs:5 fn loop_function<'a>() -> vec<message<'a>> { src/main.rs:6     let mut result = vec![]; src/main.rs:7     x in 0..10 { src/main.rs:8       result.push(message { msg: format!("{}", x).trim() }); src/main.rs:9   } src/main.rs:10     result                ... src/main.rs:8:6: 8:60 note: ...but borrowed value valid statement @ 8:5 src/main.rs:8       result.push(message { msg: format!("{}", x).trim() });                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src/main.rs:8:6: 8:60 help: consider using `let` binding increase lifetime src/main.rs:8       result.push(message { msg: format!("{}", x).trim() });                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due previous error 

is there way extend lifetime x can return vector?

i asked same question recently. can't done. answer in link has excellent explanation. solution return string:

struct message {     msg: string }  fn loop_function() -> vec<message> {     let mut result = vec![];     x in 0..10 {         result.push(message { msg: format!("{}", x).trim().to_string() });     }     result }  fn main() {     loop_function(); } 

Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -