const
​
Applies to: structs functions methods
Marks all generated builder functions and methods as const fn
. See the limitations of this feature.
Examples ​
rust
use bon::Builder;
#[derive(Builder)]
#[builder(const)]
struct Example {
x1: u32,
// Must specify the default value explicitly because `Default::default()`
// is not callable in `const` context
#[builder(default = 0)]
x2: u32
}
const {
Example::builder()
.x1(32)
.build();
}
rust
use bon::builder;
#[builder(const)]
const fn example(
x1: u32,
// Must specify the default value explicitly because `Default::default()`
// is not callable in `const` context
#[builder(default = 0)]
x2: u32
) {}
const {
example()
.x1(32)
.call();
}
rust
use bon::bon;
struct Example;
#[bon]
impl Example {
#[builder(const)]
const fn example(
x1: u32,
// Must specify the default value explicitly because `Default::default()`
// is not callable in `const` context
#[builder(default = 0)]
x2: u32
) {}
}
const {
Example::example()
.x1(32)
.call();
}
Limitations ​
Limitation | Reason |
---|---|
const must be the first attribute parameter: #[builder(const, ...other params)] | syn::Meta limitation |
No member types with non-trivial Drop implementations such as String , Vec , Box | Requires const_precise_live_drops |
No bare default and skip | Default::default() can't be called in const context. Specify the value explicitly via default/skip = ... |
Only simple expressions are allowed in default , skip , with | Full support requires const_closures. In the meantime move your expression into a separate function if bon rejects it |
No attributes requiring non-const functions (into , with = <_>::from_iter , getter(clone) , etc.) | Non-const functions and trait methods can't be called in const context |
1.61.0 MSRV | Requires const_fn_trait_bound stabilized in 1.61.0 |