How to return &str?

fn get_str() -> &str {
    let str = fs::read_to_string("file_path").unwrap().as_str();

error: cannot return value referencing temporary value

The answer is to return String instead. Returning a &str needs to borrow it from somewhere, but the contents of that file aren't anywhere that lives after the function returns.

You might be interested this article about String vs &str:


Also, note that the error message includes the following:

help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from

Which might help you find that problem in future.

I also have a bug open that the error message for this should just suggest -> String :slight_smile: Suggest returning an owned type instead of a reference in E0106 · Issue #76007 · rust-lang/rust · GitHub


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.