rust - "struct field is never used",但 RAII 需要

标签 rust raii

我正在尝试通过以某种 RAII 样式组合 os::MemoryMapfs::File 来实现内存映射文件。考虑以下示例:

#![feature(fs, os, io, path, std_misc, core)]

use std::{io, os, mem, raw};
use std::io::{Seek};
use std::fs::{File};
use std::path::{Path};
use std::os::{MemoryMap};
use std::borrow::{Cow};
use std::error::{FromError};
use std::os::unix::{AsRawFd};

struct Mmapped {
    file: File,
    map: MemoryMap,
    map_len: usize,
}

#[derive(Debug)]
enum Error {
    IoError(io::Error),
    MmapError(os::MapError),
}

impl FromError<io::Error> for Error { 
    fn from_error(err: io::Error) -> Error { Error::IoError(err) }
}

impl FromError<os::MapError> for Error { 
    fn from_error(err: os::MapError) -> Error { Error::MmapError(err) }
}

impl Mmapped {
    fn new(filename: &str) -> Result<Mmapped, Error> {
        let mut file = try!(File::open(Path::new(filename)));
        let map_len = try!(file.seek(io::SeekFrom::End(0))) as usize;
        let map = try!(MemoryMap::new(map_len, &[os::MapOption::MapReadable, os::MapOption::MapFd(file.as_raw_fd())]));
        Ok(Mmapped { file: file, map: map, map_len: map_len })
    }

    unsafe fn as_string<'a>(&self) -> Cow<'a, String, str> {
        String::from_utf8_lossy(mem::transmute(raw::Slice { data: self.map.data() as *const u8, 
                                                            len: self.map_len }))
    }
}

fn main() {
    let m = Mmapped::new("test.txt").unwrap();
    println!("File contents: {:?}", unsafe { m.as_string() });
}

playpen

它有效,但编译器将 Mmapped 对象中的 file 字段视为死代码:

<anon>:13:5: 13:15 warning: struct field is never used: `file`, #[warn(dead_code)] on by default
<anon>:13     file: File,
              ^~~~~~~~~~

我能确定它不会优化它,并且文件会在 方法中关闭吗?是否有任何标准方法来标记我的字段“未死”代码?

最佳答案

我认为惯用的方法是在字段名称前加上 _ 前缀,这也会消除警告:

struct Mmapped {
    _file: File,
    map: MemoryMap,
    map_len: usize,
}

我确实在标准库代码中注意到了这种模式。

关于rust - "struct field is never used",但 RAII 需要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28530779/

相关文章:

rust - 期望 () 但找到了一个结构

rust - 有没有办法检查应用程序运行的操作系统是 32 位还是 64 位?

c++ - 私有(private)新运营商是否有任何意想不到的副作用?

c++ - ScopeGuard 在一个函数中使用多个资源分配和退出点

rust - 为什么我会收到错误 E0277 : the size for values of type `[{integer}]` cannot be known at compilation time?

linux - 错误 "/lib/x86_64-linux-gnu/libc.so.6: version ` GLIBC_2.3 3' not found"

rust - 运行当前目录之外的 Rust 程序

c++ - 在析构函数中检测事件异常

C++:对象的引用计数器

c++ - std::exit 会泄漏内存吗?