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

后端 未结 4 2049
天涯浪人
天涯浪人 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:19

    References are pointers. Once functions are executed, they are popped off the execution stack and resources are de-allocated.

    For the following example, x is dropped at the end of the block. After that point, the reference &x will be pointing to some garbage data. Basically it is a dangling pointer. The Rust compiler does not permit such a thing since it is not safe.

    fn run() -> &u32 {
        let x: u32 = 42;
    
        return &x;
    } // x is dropped here
    
    fn main() {
        let x = run();
    }
    

提交回复
热议问题