Is there any way to return a reference to a variable created in a function?

后端 未结 4 1955
天涯浪人
天涯浪人 2020-11-21 05:03

I want to write a program that will write a file in 2 steps. It is likely that the file may not exist before the program is run. The filename is fixed.

The problem i

4条回答
  •  死守一世寂寞
    2020-11-21 05:27

    This is an elaboration on snnsnn's answer, which briefly explained the problem without being too specific.

    Rust doesn't allow return a reference to a variable created in a function. Is there a workaround? Yes, simply put that variable in a Box then return it. Example:

    fn run() -> Box {
        let x: u32 = 42;
        return Box::new(x);
    } 
    
    fn main() {
        println!("{}", run());
    }
    

    code in rust playground

    As a rule of thumb, to avoid similar problems in Rust, return an owned object (Box, Vec, String, ...) instead of reference to a variable:

    • Box instead of &T
    • Vec instead of &[T]
    • String instead of &str

    For other types, refer to The Periodic Table of Rust Types to figure out which owned object to use.

    Of course, in this example you can simply return the value (T instead of &T or Box)

    fn run() -> u32 {
        let x: u32 = 42;
        return x;
    } 
    

提交回复
热议问题