Created
July 20, 2025 03:39
-
-
Save soareschen/59f2ced05837019339b47fe883c0a58a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // This is an example use of the extensible builder pattern in Context-Generic Programming (CGP) | |
| // to progressively build a struct with missing fields filled with default values. | |
| // | |
| // This is in response to the question at https://www.reddit.com/r/rust/comments/1m4d8a8/how_to_handle_default_values_for_parameters/. | |
| // More info at https://contextgeneric.dev/blog/extensible-datatypes-part-1/ | |
| use cgp::core::field::CanFinalizeWithDefault; | |
| use cgp::prelude::*; | |
| #[derive(Default)] | |
| pub struct Uuid; | |
| #[derive(Default)] | |
| pub struct ItemType; | |
| #[derive(Default)] | |
| pub struct EquipmentType; | |
| #[derive(Default)] | |
| pub struct ItemQuantity(u64); | |
| #[derive(BuildField)] | |
| pub struct Item { | |
| pub id: Uuid, | |
| pub name: String, | |
| pub item_type: ItemType, | |
| pub equipment_type: EquipmentType, | |
| pub maximum_quantity: ItemQuantity, | |
| } | |
| #[test] | |
| fn test_default_construction() { | |
| let _item = Item::builder() | |
| .build_field(PhantomData::<symbol!("name")>, "my-item".to_owned()) | |
| .build_field( | |
| PhantomData::<symbol!("maximum_quantity")>, | |
| ItemQuantity(100), | |
| ) | |
| .finalize_with_default(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment