User provided numeric constant in a library

I have a library crate with a constant. I would like dependent crates be able to optionally provide a different value for the constant during compilation.

Is a build script the only way to achieve this, or is there another way?

A build script cannot do this — it runs before dependents get to choose anything. You would have to make extensive use of const generics (struct MyLibraryType<const N: usize> {}).

1 Like

I was afraid that might be the case. I considered this possibility and discarded it. I'm not thrilled with the changes it would require. This constant belongs to a struct that is nested several levels down within other structs, meaning I'd have to make them generic as well. That seems a bridge too far for something that is really a private implementation detail of this one struct.

You can use option_env in std - Rust if passing env var at comptime is acceptable.

1 Like

I think I'll probably do this.

Edit:

Ah, an extra wrinkle - this crate is no_std. This is a compile time constant, so std should really only be a dev dependency. Is that do-able?

That macro is also in core: option_env in core - Rust

2 Likes

Does it need to be a const? You could make it a static variable that downstream crates can set on startup.

1 Like

Looking at option_env made me realize that it produces a &'static str, but parse is not a const function so producing a const integer from it does not seem possible. I guess I could write my own parsing function which is const.

I'd like my value to be const. It's used as the size of arrays, so I'd have to switch to a Vec if it wasn't const. Vec doesn't really fit the usage in the library - i.e. a fixed-size mutable buffer which is always fully populated. While a Vec can work, it just seems weird to switch to it solely to allow a compile time size to be chosen when the natural data structure here is obviously an array.

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.