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
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:
&'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.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.
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
.
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.
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:
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.