str is a string, it may live somewhere in memory.
&str is a reference to a
str that lives somewhere in memory,
&str could be in other “scopes” than the original
String is what you would typically associate in other programming languages a string with. If you know C++, you could compare it with
std::string. It is a structure on stack that keeps a pointer to a buffer on the heap, that buffer contains a
Rust by default moves values(if the “variables” do not implement the
func2 -> String(which returns a String). What happens is that
String is moved from the stack of
func2 into the stack of
func1. And by moving I mean: it makes a copy of that struct that is on the
func2 stack, but not of what is on the heap, so that big
str is not copied, it stays there like nothing happened. So that pointer to the buffer is copied into
func1 stack and now
func1 is the owner of that
String that was returned.
&str doesn’t work is because when
func2 finishes, it pops its stack, so every temporary variable that was on its stack will be dropped. If it would of worked to return a reference to one of those temporaries, you would of hit a bug where you application could of tried to access or do something with that block of memory that doesn’t exist any more.
When you try to access that memory that doesn’t exist any more, this is called undefined behavior. There might be some other data there, you could try to overwrite it, and change the behavior of the application, or there might be nothing there and the application to just crash, many bad things can happen.
Rust saves you from these kind of mistakes.