(How) can I define a const in cargo and use it in Rust as a const later

For example I have a trait like this:

trait Foo {
    const ID: usize;
}

impl Foo for i32 {
    const ID: usize = BeginIndex + 1;
}

impl Foo for u32 {
    const ID: usize = BeginIndex + 2;
}

in this case, the BeginIndex is the const which I want to get from the cargo, and let's my crate called my_foo, then the code in cargo.toml may look like this:

my_foo = { version = "0.1.0", begin_index = 256}

I found something called cargo metadata, but it seems that I can only parse it in runtime, and I cannot let a user to define a value, like the example above.

So is there any way I can do this?

In theory, you could use the cargo metadata as you've noted and use a build script to parse it, emitting a file that Rust can then use. Doing this would be extremely odd in my opinion.

3 Likes

I agree with @jhpratt that this feels a bit odd, but something I've done in the past is to compile an environment variable's value into my crate using the env!() (or its fallible cousin, option_env!()).

const VERSION: &str = env!("CARGO_PKG_VERSION");

When writing larger tests I might often want to save test fixtures to disk and use include_str!() to have them compiled into the binary.

#[test]
fn some_test() {
  let input: &str = include_str!("./fixtures/blah.txt");

  ...
}
1 Like

Thank for replying, even I feel it weird, I'm already come up with a new design, but still, ideas about reading metadata in build.rs worth trying.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.