我感兴趣的是在Rust中有一些功能类似于关键字参数的东西,它们目前不受支持.
对于提供关键字参数的语言,类似这样的情况很常见:
panel.button(label="Some Button")
panel.button(label="Test", align=Center, icon=CIRCLE)
我见过使用builder模式处理这个问题,例如:
ui::Button::new().label("Some Button").build(panel)
ui::Button::new().label("Test").align(Center).icon(CIRCLE).build(panel)
这很好,但与Python中的关键字参数相比,有时有点尴尬.
然而,在Rust中使用impl Default
和Option<..>
个成员的 struct 初始化可以得到非常接近于编写关键字参数的东西,例如:
ui::button(ButtonArgs { label: "Some Button".to_string(), .. Default::default() } );
ui::button(ButtonArgs {
label: "Test".to_string(),
align: Some(Center),
icon: Some(Circle),
.. Default::default()
});
这是可行的,但在try 用作关键字args的上下文中有一些缺点:
- 必须在参数前面加上
struct
的名称
(also needing to explicitly include it in the namespace adds some overhead). - 在每个可选参数周围加
Some(..)
是烦人的/冗长的. - 每次用完
.. Default::default()
美元都有点乏味.
有没有办法减少其中的一些问题,让它更容易地取代关键字访问?