How to run cleaning code in the Rust library?

I am making a cross-platform terminal library. Since my library changes the state of the terminal, I need to return all the changes that are made to the terminal when the process is completed. Now I implement this function and think about ways to restore the initial state of the terminal at the end.

I thought that the static variable is initialized when the program starts, and that when the program ends, this static variable will be destroyed. Since my static variable is a structure that implements the trait Drop, it will be deleted at the end of the program, but this is not because the drop called line is never printed:

static mut SOME_STATIC_VARIABLE: SomeStruct = SomeStruct { some_value: None };

struct SomeStruct {
    pub some_value: Option<i32>,
}

impl Drop for SomeStruct {
    fn drop(&mut self) {
        println!("drop called");
    }
}

Why is it drop()not called when the program ends? My thoughts are wrong, and should I do it differently?

+4
source share
2 answers

One of the ways to ensure initialization and clearing of code in the library is to enter a type Contextthat can only be created using a public function new()and implementing a feature Drop. Each library function that requires initialization can take an argument Contextas an argument, so the user must create it before calling these functions. Any cleanup code can be included in Context::drop().

pub struct Context {
    // private field to enforce use of Context::new()
    some_value: Option<i32>,
}

impl Context {
    pub fn new() -> Context {
        // Add initialization code here.
        Context { some_value: Some(42) }
    }
}

impl Drop for Context {
    fn drop(&mut self) {
        // Add cleanup code here
        println!("Context dropped");
    }
}

// The type system will statically enforce that the initialization
// code in Context::new() is called before this function, and the
// cleanup code in drop() when the context goes out of scope.
pub fn some_function(_ctx: &Context, some_arg: i32) {
    println!("some_function called with argument {}", some_arg);
}
+4
source

One of the principles of Rust is no life before the core , which means no life after the core.

main. ++ , , , ( ) .

Rust, 'static: . .

, 'static / , 'static main...


/ ?

/ main. , , main, , .

main

main, .

+6

Source: https://habr.com/ru/post/1693485/


All Articles