How to return a simple str (Unsized UTF-8 sequence of Unicode string slices) from a function

how to return a static str from a function
i tried

fn main()
{
    let input = string();
 
}

fn string()-> &'static str
{
    let a = String::from("Hello world");
    let b = a.as_str();
    b
}

but output error

&str acquired from String without explicit memory leaking is not static by definition.

what is your use case for this?

the trivial example you posted can be done like this:

if the string is dynamically generated, you have two options:

  • (usually preferred) return a normal String, and convert it to a reference when using it
  • (usually not recommended) create a String, turn it into a boxed &str and leak the memory so you will in fact get a &'static str, which will never be removed until the end of the program because nobody owns it. if you do this over and over, RAM will fill up with garbage strings.
1 Like

in rust we accept user input as string. i my case i need a function that convert this string input to str and return the value, is it possible
or just return string and convert to str in main function.

You should do this instead:

fn string() -> String {
    let a = String::from("Hello world");
    a
}

The only way to create a &'static str is to permanently leak memory.

2 Likes

yes, this is the better approach.

ok thank you helping me to make a choose
but one more thing can any one explain why str cause memory leak in detail ?

Using str does not cause a memory leak; using Box::leak does. You can use Box::leak to turn a String into a &'static str because leaked memory can last forever so it is no problem to make it 'static.

1 Like

Using the &str type is a way to tell the compiler that you are not giving away ownership, which means that your memory must be owned by something else than the slice. The 'static in &'static str tells the compiler that the owner of the string slice will never be destroyed, which is only possible for compile time constants or leaked memory.

When you are returning a new string, you pretty much always want to give ownership away together with the string, which you do by using the String type.

5 Likes

Adapting a response of mine from another thread (the quote below is edited for context within this topic)

And in a followup, I suggested watching this talk, which describes the motivation behind ownership and borrowing:

2 Likes

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.