Returning a reference to the stack

202307251510
Status: #idea
Tags: Rust

Returning a reference to the stack

fn return_a_string() -> &String {
	let s = String::from("Hello world");
	&s
}

Move ownership outside the function

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

Return a static string literal

fn return_a_string() -> &'static str {
	"Hello world"
}

Defer borrow-checking to runtime by using garbage collection

For example, we can use a [reference-counted pointer](Rc, the Reference Counted Smart Pointer)
use std::rc::Rc;
fn return_a_string() -> Rc<String> {
	let s = Rc::newfrom("Hello world");
	Rc::clone(&s)
}

Caller provides a slot for returning the string

fn return_a_string(output: &mut String) {
	output.replace_range(.., "Hello world");
}

References

  1. https://rust-book.cs.brown.edu/ch04-03-fixing-ownership-errors.html#fixing-an-unsafe-program-returning-a-reference-to-the-stack
  2. Fixing Ownership Errors