Crate constructor [] [src]

Registers a function to be called before main (if an executable) or when loaded (if a dynamic library). Using this is a bad idea. You can do this in a way that isn't abysmally fragile.


pub static mut X: usize = 0;
extern fn init() {
    unsafe { X = 5; }
constructor! { init }
fn main() {
   assert_eq!(unsafe { X }, 5);


This isn't exactly portable, though the implementation is quite simple.

Doing anything particularly complicated, such IO or loading libraries, may cause problems on Windows. (?)

Every parent module must be public. If it is not, then it will be stripped out by --release. At least the compiler gives a helpful warning.

Beware, for some say that these techniques can unleash a terrible evil. lazy_static may be a more appropriate tool.