Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

rust - How can I statically register structures at compile time?

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 dedicated tasks so that if I run myprog foo, it will call the foo applet.

So I started by defining an Applet structure:

struct Applet {
    name: &str,
    call: fn(),
}

Then I can define my foo applet this way:

fn foo_call() {
    println!("Foo");
}
let foo_applet = Applet { name: "foo", call: foo_call };

Now I would like to register this applet so that my main function can call it if available:

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();

    match AppletRegistry.get(args[1]) {
        Some(x) => x.call(),
        _ => (),
    }
}

The whole deal is about how AppletRegistry should be implemented so that I can list all the available applets preferably at compile time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...