lnc*_*ncr 5 macros struct field traits rust
我正在使用宏来实现特征作为我的库的一部分。此实现要求结构至少有一个附加字段。
pub trait Trait {
fn access_var(&mut self, var: bool);
}
macro_rules! impl_trait {
(for $struct:ident) => {
impl Trait for $struct {
pub fn access_var(&mut self, var: bool) {
self.var = var; // requires self to have a field 'var'
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想防止用户每次都必须添加这些附加字段。由于 Rust 编译器不允许在字段定义中使用宏(我没有这方面的来源,所以如果我错了,请纠正我),这样的事情是行不通的。
macro_rules! variables_for_trait {
() => {
var: bool,
}
};
struct Foo {
variables_for_trait!(); // error: expected ':' found '!'
additional_var: i64,
}
Run Code Online (Sandbox Code Playgroud)
我想我可以创建一个宏来启用这样的功能
bar!(Foo with additional_var: i64, other_var: u64);
Run Code Online (Sandbox Code Playgroud)
解决宏后看起来像这样:
pub struct Foo {
var: bool,
additional_var: i64,
other_var: u64,
}
impl Trait for Foo {
pub fn access_var(&mut self, var: bool) {
self.var = var;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来解决这个问题,如果没有,你能给我一个示例语法bar!吗?
PS:像这样的东西的好名字是什么bar!?
我最终用两个不同的宏解决了这个问题:
// I simply copied it from my project and changed some names,
// But due to the fact that I couldn't think of better names for my macros,
// I just ended up using the original names, even though they don't quite fit
macro_rules! new_object_type {
($struct:ident {$( $field:ident:$type:ty ),*}) =>{
pub struct $struct {
var: bool,
$(
$field: $type,
)*
}
impl Trait for $struct {
pub fn access_var(&mut self, var: bool) {
self.var = var;
}
}
};
}
macro_rules! construct_object {
($struct:ident {$( $field:ident:$value:expr ),*}) => {
$struct {
var: false,
$(
$field: $value,
)*
}
};
}
Run Code Online (Sandbox Code Playgroud)
要创建一个新的结构来实现Trait您现在编写的内容:
new_object_type!(Foo {
additional_var: i64,
other_var: u64,
});
Run Code Online (Sandbox Code Playgroud)
要创建一个新实例,请Foo编写:
construct_object!(Foo {
additional_var: 42,
other_var: 82000,
})
Run Code Online (Sandbox Code Playgroud)
Trait现在无需与 交互即可使用var。
它并不像我希望的那样干净,如果没有适当的文档,它很难使用,特别是如果用户对 Rust 相当陌生。
拥有两个相同的字段可能会出现一些问题,因为用户看不到所有已实现的变量(这可以通过将 var 的名称更改为类似的名称来解决T7dkD3S3O8,这肯定会使这种情况不太可能发生)
由于结构体的定义和构造都在宏内部,因此错误消息可能更难以理解
| 归档时间: |
|
| 查看次数: |
1840 次 |
| 最近记录: |