|
| 1 | +use core::fmt::Display; |
| 2 | + |
| 3 | +use cgp::prelude::*; // Import all CGP constructs |
| 4 | + |
| 5 | +// Derive CGP provider traits and blanket implementations |
| 6 | +#[cgp_component { |
| 7 | + name: GreeterComponent, // Name of the CGP component |
| 8 | + provider: Greeter, // Name of the provider trait |
| 9 | +}] |
| 10 | +pub trait CanGreet // Name of the consumer trait |
| 11 | +{ |
| 12 | + fn greet(&self); |
| 13 | +} |
| 14 | + |
| 15 | +// Declare a CGP abstract type `Name` |
| 16 | +cgp_type!(Name); |
| 17 | + |
| 18 | +// A getter trait representing a dependency for `name` value |
| 19 | +#[cgp_auto_getter] // Derive blanket implementation |
| 20 | +pub trait HasName: HasNameType { |
| 21 | + fn name(&self) -> &Self::Name; |
| 22 | +} |
| 23 | + |
| 24 | +// A provider that implements `Greeter` |
| 25 | +pub struct GreetHello; |
| 26 | + |
| 27 | +// Implement `Greeter` that is generic over `Context` |
| 28 | +impl<Context> Greeter<Context> for GreetHello |
| 29 | +where |
| 30 | + Context: HasName, // Inject the `name` dependency from `Context` |
| 31 | + Context::Name: Display, |
| 32 | +{ |
| 33 | + fn greet(context: &Context) { |
| 34 | + // `self` is replaced by `context` inside providers |
| 35 | + println!("Hello, {}!", context.name()); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +// A concrete context that uses CGP components |
| 40 | +#[derive(HasField)] // Deriving `HasField` automatically implements `HasName` |
| 41 | +pub struct Person { |
| 42 | + pub name: String, |
| 43 | +} |
| 44 | + |
| 45 | +// The CGP components mapping for `Person` |
| 46 | +pub struct PersonComponents; |
| 47 | + |
| 48 | +// Set CGP components used by `Person` to be `PersonComponents` |
| 49 | +impl HasComponents for Person { |
| 50 | + type Components = PersonComponents; |
| 51 | +} |
| 52 | + |
| 53 | +// Compile-time wiring of CGP components |
| 54 | +delegate_components! { |
| 55 | + PersonComponents { |
| 56 | + NameTypeComponent: UseType<String>, |
| 57 | + GreeterComponent: GreetHello, // Use `GreetHello` to provide `Greeter` |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +fn main() { |
| 62 | + let person = Person { |
| 63 | + name: "Alice".into(), |
| 64 | + }; |
| 65 | + |
| 66 | + // `CanGreet` is automatically implemented for `Person` |
| 67 | + person.greet(); |
| 68 | +} |
0 commit comments