代码之家  ›  专栏  ›  技术社区  ›  fadedbee

如何在结构的生命周期内“保管”变量?

  •  0
  • fadedbee  · 技术社区  · 3 年前

    这将编译并通过测试:

    use std::io::Write;
    
    /*
     * This transforms a writer into a writer where every write is prefixed
     * with a timestamp and terminated with a newline.
     */
    
    struct Timestamper<T: Write> {
        writer: T,
    }
    
    impl<T: Write> Timestamper<T> {
        pub fn new(writer: T) -> Timestamper<T> {
            Timestamper { writer }
        }
        pub fn drop(self) -> T {
            self.writer
        }
    }
    
    impl<T: Write> Write for Timestamper<T> {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.writer.write(b"timestamp ")?;
            let expected_size = self.writer.write(buf)?;
            self.writer.write(b"\n")?;
            std::io::Result::Ok(expected_size)
        }
    
        fn flush(&mut self) -> std::io::Result<()> {
            self.writer.flush()
        }
    }
    
    
    #[cfg(test)]
    mod tests {
        use std::io::Write;
        use super::Timestamper;
    
        #[test]
        fn test_timestamper() {
            let buf = Vec::new(); // buffer to write into
            let mut timestamper = Timestamper::new(buf);
            let hello_len = timestamper.write(b"hello").unwrap();
            let world_len = timestamper.write(b"world").unwrap();
            assert_eq!(hello_len, 5);
            assert_eq!(world_len, 5);
            let buf2 = timestamper.drop();
            assert_eq!(buf2.as_slice(), b"timestamp hello\ntimestamp world\n");
        }
    }
    

    正在制作 drop() 方法,该方法返回 writer 对象,在Rust中惯用?

    下降() 最终展开函数的正确名称?

    1 回复  |  直到 3 年前
        1
  •  4
  •   Sven Marnach    3 年前

    这是Rust中的一种常见方法,但您不应该调用 drop() 这个 Drop::drop() mehtod有不同的语义。的通用名称 method returning the wrapped value is into_inner()

    根据您的用例,您还可以将对编写器的可变引用传递到包装器中。对实现的对象的可变引用 Write 也执行 ,所以这将在没有任何进一步代码的情况下工作。借用的好处是,你不需要做任何事情来找回原作者。借用结束后,您可以立即再次使用原始值。不利的一面是,您无法在与创建结构不同的上下文中打开包装的编写器。

    推荐文章