When I want to return an object, I just specify it, but what do I do when the created object is based on a reference of a string? My example:
fn init_keychain() -> keyring::Keyring<'a> {
// Gets the username of the current user to save it in the right keychain
let mut username = Command::new("whoami")
.output()
.expect("Failed to get current user");
// Check for newline sequence in Command Output and strip it
if username.stdout[username.stdout.len()-1] == 10 {
username.stdout.pop();
}
let user = String::from_utf8_lossy(&username.stdout);
// Create a new Keychain attribute to save the passord to
keyring::Keyring::new("Service", &user.into_owned())
}
Which raises the error:
error: borrowed value does not live long enough
--> controller.rs:44:44
|
44 | keyring::Keyring::new("Service", &user.into_owned())
| ^^^^^^^^^^^^^^^ does
not live long enough
...
49 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the lifetime 'a as defined on
the body at 30:29...
I understand why the error occurs - the reference &user
gets out of scope as soon as init_keychain()
ends.
How do I create an object where I need a &str
and then return it? Is there some Rusty magic I completely missed? I tried with into_owned()
and clone()
, but that doesn't change anything about the lifetime of user. So that's where my knowledge ends.
I am confused with Rust's ownership concept, and I can't find information in the docs, Google, or Stack Overflow. But maybe I'm just really bad at figuring this out.