简体   繁体   English

如何实现许多类似的特质方法?

[英]How to implement many similar methods for trait?

I am implementing the Serde Serializer trait which has a lot of methods. 我正在实现Serde Serializer特性 ,它具有很多方法。 Many of them look quite similar (for example those for integer types just copy bytes to some buffer), so it would be nice to generate them somehow. 它们中的许多看起来非常相似(例如整数类型的那些只是将字节复制到某个缓冲区),因此以某种方式生成它们会很好。 Can I write some generic function or macro to implement many of them with one method (macro)? 我可以用一种方法(宏)编写一些通用函数或宏来实现它们中的许多吗?

I have something like this: 我有这样的事情:

use serde::Serializer;
use byteorder::{WriteBytesExt, LittleEndian};

struct MySerializer {
     ...
}

impl Serializer for MySerializer {
    fn serialize_i32(&mut self, v:i32) -> Result<(), Error> {
        try!(self.buffer.write_i32::<LittleEndian>(v));
    }
    fn serialize_u8(&mut self, v:u8) -> Result<(), Error> {
        try!(self.buffer.write_u8::<LittleEndian>(v));
    }
    // many similar looking functions here
}

I found and example in serde/bench project: 我在serde / bench项目中找到了例子:

macro_rules! impl_nums {
    ($ty:ty, $dser_method:ident, $visitor_method:ident, $reader_method:ident) => {
        #[inline]
        fn $dser_method<V>(&mut self, mut visitor: V) -> Result<V::Value>
            where V: Visitor
        {
            let value = try!(self.reader.$reader_method::<NativeEndian>());
            visitor.$visitor_method(value)
        }
    };
}

impl_nums!(u16, deserialize_u16, visit_u16, read_u16);
impl_nums!(u32, deserialize_u32, visit_u32, read_u32);
....

It looks like for now it is the best possible way to do it - concat_idents! 看起来现在它是最好的方法 - concat_idents! macro is unstable, and is not very useful acording to this github issue . 宏是不稳定的,根据这个github问题并不是很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM