Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a constant of a type with private fields from an external crate?

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?

like image 612
RBF06 Avatar asked Dec 16 '25 12:12

RBF06


1 Answers

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.

like image 140
Kevin Reid Avatar answered Dec 19 '25 06:12

Kevin Reid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!