Let's take this example:
fn hello() -> String {
String::from("Hello")
}
An equivalent example in C would be to use malloc, write chars into the memory, and to return the pointer. Why does the Rust code work? Why don't I have to write it like this:
fn hello() -> Box<String> {
Box::from(String::from("Hello"))
}
To create a value inside a function and let that function return it, the value must always be created on the heap and not the stack, that's for sure. Why does Rust use a syntax that indicates on first glance you can return stack variables?
Does Rust automatically wrap all data returned from a function in a Box
? Or is there some other Rust magic?
My guess is that it's syntactic sugar to not to be forced to wrap return values in a Box
.
My question is not limited to strings; it's about returning structures from functions in general. I know that the underlying vector stores its data on the heap. This question is only about the metadata of the struct (i.e. pointers to the data on the heap) and how they are returned (in compiler output) when the function returns.