Is it possible in Rust to delete an object before the end of scope?

后端 未结 2 1343
遇见更好的自我
遇见更好的自我 2020-12-06 01:35

From what I understand, the compiler automatically generates code to call the destructor to delete an object when it\'s no longer needed, at the end of scope.

In som

2条回答
  •  一向
    一向 (楼主)
    2020-12-06 01:48

    The official answer is to call mem::drop:

    fn do_the_thing() {
        let s = "Hello, World".to_string();
        println!("{}", s);
    
        drop(s);
    
        println!("{}", 3);
    }
    

    However, note that mem::drop is nothing special. Here is the definition in full:

    pub fn drop(_x: T) { }
    

    That's all.

    Any function taking ownership of a parameter will cause this parameter to be dropped at the end of said function. From the point of view of the caller, it's an early drop :)

提交回复
热议问题