How can I statically register structures at compile time?

后端 未结 3 1461
后悔当初
后悔当初 2020-12-02 03:06

I\'m looking for the right method to statically register structures at compile time.

The origin of this requirement is to have a bunch of applets with dedic

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 03:42

    You can't.

    One of the conscious design choices with Rust is "no code before main", thus there is no support for this sort of thing. Fundamentally, you need to have code somewhere that you explicitly call that registers the applets.

    Rust programs that need to do something like this will just list all the possible implementations explicitly and construct a single, static array of them. Something like this:

    pub const APPLETS: &'static [Applet] = [
        Applet { name: "foo", call: ::applets::foo::foo_call },
        Applet { name: "bar", call: ::applets::bar::bar_call },
    ];
    

    (Sometimes, the repetitive elements can be simplified with macros, i.e. in this example, you could change it so that the name is only mentioned once.)

    Theoretically, you could do it by doing what languages like D do behind the scenes, but would be platform-specific and probably require messing with linker scripts and/or modifying the compiler.

    Aside: What about #[test]? #[test] is magic and handled by the compiler. The short version is: it does the job of finding all the tests in a crate and building said giant list, which is then used by the test runner which effectively replaces your main function. No, there's no way you can do anything similar.

提交回复
热议问题