Skip to main content

Field access

Reading one field of a context by its type-level name, from code that cannot name the context.

Overview​

In Context-Generic Programming (CGP), an implementation most often reads a value out of its context, the type the method runs on, which supplies the values it needs as its fields, without naming that type. It reads the field by keying on the field's name as a type, so any context with a matching field satisfies the bound. These traits are the foundation the ergonomic surface stands on: an #[implicit] argument, a #[cgp_auto_getter] method, and a UseField wiring entry all generate a bound on the traits here.

The traits divide on two axes: read versus write, and consumer-side versus provider-side.

The consumer traits are what an implementation bounds against on its own context. HasField reads a field, and HasFieldMut adds mutable access.

The provider-side mirrors are what a getter component is wired through, by way of WithProvider, so that a context chooses by wiring which field answers a getter. FieldGetter is the read side and MutFieldGetter the write side.

OptionAsRef borrows the value inside an Option as a &T, which is the bound an Option<&str> implicit argument generates so the field may be a String, a Cow<str>, or a Box<str>.

The read-through forms let generic code and getter providers read a field of a field without a lifetime bound on the intermediate type. MapField is the consumer side and FieldMapper the provider side, and ChainGetters composes them to descend into a nested context.

The ideas behind them​


An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.