The correct way to return a new line in Rust

I just spent a week reading Rust's book, and now I'm working on my first program, which returns the path to the system file:

pub fn get_wallpaper() -> &str {
    let output = Command::new("gsettings");
    // irrelevant code
    if let Ok(message) = String::from_utf8(output.stdout) {
        return message;
    } else {
        return "";
    }
}

I get an error expected lifetime parameter on &str, and I know that Rust wants to enter &str, which will be returned as output, because any &strthat I create inside the function will be cleared right after the function finishes.

I know that I can get around the problem by returning Stringinstead &str, and many answers to similar questions said the same. But I can do it too:

fn main() {
    println!("message: {}", hello_string(""));
}

fn hello_string(x: &str) -> &str {
    return "hello world";
}

to get &strout of my function. Can someone explain to me why this is bad and why I should never do this? Or maybe it's not bad and good in certain situations?

+6
1

&str, String . , , . : String.

String .

String , . String, , .

, , , .

. . , , . , , .

:

fn hello_string(x: &str) -> &str {
    return "hello world";
}

&str . - , , ? , , ?

, , . "hello world" &'static str, , . , , , main.

fn hello_string(x: &str) -> &str fn hello_string<'a>(x: &'a str) -> &'a str. , , . , .

, :

fn long_string(x: &str) -> &str {
    if x.len() > 10 {
        "too long"
    } else {
        x
    }
}

String. String, :

fn hello_string(x: &str) -> &str {
    &String::from("hello world")
}

: " ". , , , . "" (, , ).

+10

Source: https://habr.com/ru/post/1016122/


All Articles