Relative Content

Tag Archive for rustlifetimeownership

Rust Lifetime Error: Cannot Return Value Referencing Local Variable

I am working on a Rust project using rusb to interact with USB devices. I’m facing a lifetime management issue where I cannot return a struct containing a reference due to it referencing a local variable within a nested loop. Here’s the simplified code that leads to the issue:

Error in this code. I know this can be solved with a “named lifetime parameter”, but I wanna know why exactly this specific code throws error at all?

fn main() { let strings = vec![String::from(“hello”)]; let default = String::from(“default”); let s = first_or(&strings, &default); println!(“{}”, s); } fn first_or(strings: &Vec<String>, default: &String) -> &String { if strings.len() > 0 { &strings[0] } else { default } } I tried to just either return &string[0] or default, but the error persisted. I dont want […]