Cannot return value referencing local data

Hi, I am new to Rust and couldn't resolve this issue the way that I wanted. Would you please Assis?

fn execute_os_command(command: &str) -> &str {
let cmd_output = Command::new("sh")
.arg("-c")
.arg(command)// command
.output()
.expect("Failed to Execute OS Command");

let result = std::str::from_utf8(&cmd_output.stdout).unwrap();
return result;

}

Use String::from_utf8() instead of std::str::from_utf8():

fn execute_os_command(command: &str) -> String {
    let cmd_output = Command::new("sh")
        .arg("-c")
        .arg(command)// command
        .output()
        .expect("Failed to Execute OS Command");

    let result = String::from_utf8(cmd_output.stdout).unwrap();
    result
}
1 Like

@chrefr Thanks for your answer. I thought about that, and the only reason that I wanted to return a reference instead of the whole value(copy) is that the string that I am returning could be really really long. any advice on that?

String is internally a pointer to a buffer. The buffer will not be copied when you return it, just the pointer.

1 Like

Ok, I didn't know. Thanks for clarifying that.

Do note however that during the check whether the string is valid UTF-8, it'll perform a pass over the string. That's correct for std::str::from_utf8() too, however (in fact, String::from_utf8() delegates the check to std::str::from_utf8()).

If you're sure the text is valid UTF-8, and you want to save the check, you can fall to using the unsafe String::from_utf8_unchecked(). Don't do that unless profiling reveals performance problems, however.

1 Like

Also, going by the topic name (Cannot return value referencing local data), you were trying to do something that is fundamentally unsound. Values defined on the stack will cease to exist when the function returns and the stack frame is dropped. So, you can never return a reference to a local variable, safely.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.