• rust drop


    Drop

    Drop trait 只有一个方法:drop,当一个对象离开作用域时会自动调用该方法。Drop trait 的主要作用是释放实现者实例拥有的资源。

    BoxVecStringFile,以及 Process 是一些实现了 Drop trait 来释放资源的类型的例子。Drop trait 也可以针对任意自定义数据类型手动实现。

    下面示例给 drop 函数增加了打印到控制台的功能,用于宣布它在什么时候被调用。(原文:The following example adds a print to console to the drop function to announce when it is called.)

    struct Droppable {
        name: &'static str,
    }
    
    // 这个简单的 `drop` 实现添加了打印到控制台的功能。
    impl Drop for Droppable {
        fn drop(&mut self) {
            println!("> Dropping {}", self.name);
        }
    }
    
    fn main() {
        let _a = Droppable { name: "a" };
    
        // 代码块 A
        {
            let _b = Droppable { name: "b" };
    
            // 代码块 B
            {
                let _c = Droppable { name: "c" };
                let _d = Droppable { name: "d" };
    
                println!("Exiting block B");
            }
            println!("Just exited block B");
    
            println!("Exiting block A");
        }
        println!("Just exited block A");
    
        // 变量可以手动使用 `drop` 函数来销毁。
        drop(_a);
        // 试一试 ^ 将此行注释掉。
    
        println!("end of the main function");
    
        // `_a` **不会**在这里再次销毁,因为它已经被(手动)销毁。
    }
    [root@bogon drop]# 
    [root@bogon drop]# cargo build
       Compiling own v0.1.0 (/data2/rust/drop)
        Finished dev [unoptimized + debuginfo] target(s) in 0.37s
    [root@bogon drop]# cargo run
        Finished dev [unoptimized + debuginfo] target(s) in 0.01s
         Running `target/debug/own`
    Exiting block B
    > Dropping d
    > Dropping c
    Just exited block B
    Exiting block A
    > Dropping b
    Just exited block A
    > Dropping a
    end of the main function
  • 相关阅读:
    反射
    注解
    file
    exception(异常)
    MySQL问题
    maven 中 遇到的问题
    Java读取文本数字
    人民币-欧元预测(ARIMA算法)代码
    云平台项目--学习经验--jsrender前端渲染模板
    云平台项目--学习经验--BootstrapValidate表单验证插件
  • 原文地址:https://www.cnblogs.com/dream397/p/14185119.html
Copyright © 2020-2023  润新知