I am creating a library crate and I would like to define a const of a type imported from an external crate:
use external_crate::ExternalStruct;
// Error: field `field` of struct `ExternalStruct` is private
const THE_VALUE: ExternalStruct = ExternalStruct{field: 43};
The problem is ExternalStruct has private fields so I can't construct it directly like this. It also doesn't have any const fn constructors. Is it possible for my crate to define a const of type ExternalStruct?
This is not possible. Instead you can do one of these things:
Modify the library to add a const fn constructor. Many developers aren't necessarily thinking about const usage, so a const fn construction might be a welcome patch to add overlooked functionality.
If you can use a static instead of a const item, then once_cell::sync::Lazy will allow you to construct the value at run time, but only once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With