What If Traits Carried Values
⭐⭐⭐⭐ (4星)
核心思想
将trait bounds从"类型约束"扩展为"可携带运行时值的能力",让隐式参数更加强大。
Contexts and Capabilities
基于Tyler Mandry的提议,包含三个组件:
- 声明能力:
capability my_capability; - 隐式传值: 在where bound中使用
my_capability: Type,编译器自动传递 - 作用域控制:
with my_capability = some_value() { ... }
示例
capability arena;
impl<'a> Deserialize for &'a Foo
where
arena: &'a BasicArena,
{ ... }
fn main() -> Result<()> {
let bytes = read_some_bytes()?;
with arena = &arena::BasicArena::new() {
let foos: Vec<&Foo> = deserialize(bytes)?;
}
}
四种所有权语义
字典携带值后,需要区分所有权模式(类似closure traits):
- : const - 无隐式值,完全编译时已知
- : Copy - &Context语义,可复制
- : Reborrow - &mut Context语义,新值与旧值borrowck关联
- Owned - Box语义,可包含任意值
方法变成闭包
根据字典的ownership,方法的闭包类型对应:
- const → fn指针
- Copy → Fn
- Reborrow → FnMut
- Owned → FnOnce
Scoped Impls
trait实现在不同scope下可以有不同行为:
capability pointer_target;
impl<'a> Deref for MagicPointer<'a>
where
pointer_target: impl Sized + 'a
{
type Target = type_of!(pointer_target);
fn deref(&self) -> &Self::Target { &pointer_target }
}
同一个类型根据scope实现不同的trait,这是全新的表达力维度。
与现有特性对比
- Swift property wrappers - 类似但更受限
- GAT (Generic Associated Types) - 更激进的扩展
- Dictionary Passing Style - 理论基础
核心结论
"trait bounds携带运行时值"与语言其他部分自然交互,为trait系统开启全新的表达空间。