Traits Cookbook
This subsection of the guide is a focused, example-driven reference for
Nitpick's trait / impl / dyn surface as it stands at the close of the
v0.31.1.x phase (Phase 2 of the v0.31.x cycle).
Traits in Nitpick are a static abstraction over behaviour: a trait
declares a set of method signatures, an impl T:for:U block supplies
those signatures for a concrete type U, and call sites dispatch in two
modes — static (the type is known at compile time and the method is
resolved directly) and dynamic (the value is held behind a dyn T
fat pointer and the method is resolved through a vtable at run time).
Chapters
- Basics — declaring a
trait, writing animpl T:for:U, and calling methods via UFCS (x.foo()). - Dyn surface —
dyn Tas a local variable, struct field, and function parameter; how concrete →dyncoercion works. - Borrow rules —
$$i dyn Tand$$m dyn Tborrows, the source-side conflict rules, and the call-site interaction. - Return-borrow methods —
$$i/$$mreturn types, thefrom <ident>source-binding clause, the multi-borrow defaults (TRAIT-RET-DEC-002/005), and whydyndispatch is rejected for return-borrow methods (ARIA-053). New in v0.31.8.x.
Each chapter is short and self-contained.
Conventions used in these chapters
- Examples are minimal
func:mainprograms that compile and run withnpkc. - "concrete type" means a named struct or primitive that satisfies a trait.
- "dyn T" means the trait-object form: a
{data, vtable}fat pointer. - Diagnostics are quoted as the compiler emits them, with the
ARIA-NNNcode. - Where bug regressions are referenced, the fixture number is given in parentheses, e.g. (bug374).
Validation status (v0.31.1.10)
- Compiler CTest: 107/107 (modulo 2 known pre-existing flakes).
- K core tests: 151/151.
- K proofs: 11/11.
- Trait/dyn-related bug regressions: bug363 ... bug378.
Scope and non-scope
In scope for Phase 2 / v0.31.1.x:
traitdeclaration with method signatures.impl T:for:Uwith one method per signature.- UFCS dispatch on concrete values (
c.bump()). dyn Tas a local variable, struct field, and function parameter.- Concrete →
dyn Tcoercion at assignment and call sites. $$i dyn Tand$$m dyn Tborrows with source-side conflict checking (ARIA-019 / ARIA-023 / ARIA-026).
Not yet in scope (deferred to later v0.31.x phases or v0.32.x+):
- Trait inheritance / super-traits.
- Associated types and associated constants.
- Generic trait bounds (
func:f = T($$i T:x) where T: Trait). derivefor arbitrary traits (onlyderive(Display)exists today — see comptime cookbook).obj(the "owned trait object" form discussed in PLAN.md D-9 follow-on).