Khi xác định triển khai trong macro, có thể hữu ích khi truy cập loại cấu trúc thành viên để tránh phải chuyển nó thành đối số bổ sung. (xem this question)Có thể truy cập loại thành viên cấu trúc cho chữ ký chức năng hoặc khai báo không?
impl PartialEq<u32> for MyStruct { ... }
Có cách nào để truy cập loại cấu kiện mà không biết trước loại đó?
impl PartialEq<typeof(MyStruct.member)> for MyStruct { ... }
Trong trường hợp đó là hữu ích, đây là một ví dụ viết tắt của lý do tại sao tôi quan tâm để làm điều này:
struct_bitflag_impl!(
pub struct MyFlag(u8);,
MyFlag, u8);
// ^^ how to avoid having this extra arg?
// (Used by ``impl PartialEq<$t_internal> for $p``)
// couldn't it be discovered from `MyFlag.0` ?
// the macro
macro_rules! struct_bitflag_impl {
($struct_p_def: item, $p:ident, $t_internal:ty) => {
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
$struct_p_def
impl ::std::ops::BitAnd for $p {
type Output = $p;
fn bitand(self, _rhs: $p) -> $p { $p(self.0 & _rhs.0) }
}
impl ::std::ops::BitOr for $p {
type Output = $p;
fn bitor(self, _rhs: $p) -> $p { $p(self.0 | _rhs.0) }
}
impl ::std::ops::BitXor for $p {
type Output = $p;
fn bitxor(self, _rhs: $p) -> $p { $p(self.0^_rhs.0) }
}
impl ::std::ops::Not for $p {
type Output = $p;
fn not(self) -> $p { $p(!self.0) }
}
// support comparison with the base-type.
impl PartialEq<$t_internal> for $p {
fn eq(&self, other: &t_internal) -> bool {
self.0 == *other
}
}
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// How to avoid using 't_internal' here?
}
}
Nhận xét từ @keepr, điều này có thể được xử lý bởi 'custom_derive' xem: https://docs.rs/custom_derive/*/custom_derive/index.html – ideasman42