Yinon Burgansky
Yinon Burgansky
MModular
Created by Yinon Burgansky on 3/29/2024 in #questions
Returning a reference from a factory
I know that reference and lifetimes are still being worked on, but I was wondering if it will be possible to return a reference from a factory function, e.g.:
fn some_factory() -> Reference[String]:
var build_string = "Hello" # initially lifetime is bounded to the local variable in the function scope
return Reference(build_string) # extend the lifetime since the string reference is returned outside the function scope

fn main():
var x = some_factory() # lifetime of the string is now bounded to lifetime of x
print(x) # prints "Hello"
# x containing the string is freed here
fn some_factory() -> Reference[String]:
var build_string = "Hello" # initially lifetime is bounded to the local variable in the function scope
return Reference(build_string) # extend the lifetime since the string reference is returned outside the function scope

fn main():
var x = some_factory() # lifetime of the string is now bounded to lifetime of x
print(x) # prints "Hello"
# x containing the string is freed here
I think that it's not possible in Rust, it would be nice to know if something like this will be possible in Mojo.
10 replies