Skip to content

Add very limited support for #[builder(const)]#279

Merged
Veetaha merged 19 commits intomasterfrom
feat/const
Apr 13, 2025
Merged

Add very limited support for #[builder(const)]#279
Veetaha merged 19 commits intomasterfrom
feat/const

Conversation

@Veetaha
Copy link
Copy Markdown
Collaborator

@Veetaha Veetaha commented Apr 12, 2025

Closes #169

The current implementation is very, very limited. It basically allows only members of primitive types only. You can't use String, Vec or other types with non-trivial Drop implementations.

What works is this:

use crate::prelude::*;

#[test]
const fn smoke_struct() {
    #[derive(Builder)]
    #[builder(const)]
    struct Sut {
        x1: u32,

        x2: Option<u32>,

        #[builder(default = x1 + 99)]
        x3: u32,

        #[builder(skip = 4)]
        x4: u32,

        #[builder(with = |a: u32, b: u32| a + b)]
        x5: u32,

        #[builder(with = |a: u32, b: u32| -> Result<_, ()> { Ok(a + b) })]
        _x6: Option<u32>,
        //
        // This doesn't work because Rust complains about this in setters that
        // consume `self` and return a new instance of the builder:
        // ```
        // destructor of `builder::attr_const::smoke_struct::SutBuilder<S>`
        // cannot be evaluated at compile-time
        // ```
        // x7: Vec<String>,
        // x8: String,
    }

    const ACTUAL: Sut = Sut::builder().x1(2).x2(2).x5(3, 4).build();

    #[allow(clippy::assertions_on_constants)]
    {
        assert!(ACTUAL.x1 == 2);
        assert!(ACTUAL.x2.unwrap() == 2);
        assert!(ACTUAL.x3 == 101);
        assert!(ACTUAL.x4 == 4);
        assert!(ACTUAL.x5 == 7);
    }
}

@Veetaha Veetaha marked this pull request as draft April 12, 2025 18:53
@Veetaha Veetaha mentioned this pull request Apr 12, 2025
@Veetaha Veetaha marked this pull request as ready for review April 13, 2025 16:12
@Veetaha Veetaha merged commit dc3de5a into master Apr 13, 2025
36 checks passed
@Veetaha Veetaha deleted the feat/const branch April 13, 2025 16:29
@github-actions github-actions Bot mentioned this pull request Apr 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support const evaluation

2 participants