与Rust借用检查员战斗

时间:2015-09-07 17:38:14

标签: rust borrow-checker

这段代码看起来对我来说很好用,但生锈的借用检查器并不喜欢它:

string str = "empty";

protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    str = "I am here";
    ViewState["str"] = str;
    Debug.Write("VALUE: " + str + "\r\n");
  }
  else
  {
    str = (string)ViewState["str"];
    Debug.Write("VALUE: " + str + "\r\n");
  }
}

我想我不能使用单独的函数,而是使用两个for循环部分,但这不是惯用的Rust,也不是良好的编码实践。事实上,我已经尝试过了,但它只是告诉我,我使用的是移动值。以下是我遇到的一些错误:

extern crate rustbox;

use std::error::Error;
use std::default::Default;

use rustbox::{Color, RustBox};
use rustbox::Key;

use std::fs::File;
use std::env;
use std::io::BufReader;
use std::io::BufRead;

fn display_screenful(rb: &RustBox, fr: BufReader<&'static File>, offset: usize) {
    for (rline, idx) in fr.lines().zip(0..).skip(offset).take(rb.height()) {
        match rline {
            Ok(line) => (*rb).print(0, idx, rustbox::RB_NORMAL, Color::White, Color::Black, &line),
            Err(_)   => (*rb).print(0, idx, rustbox::RB_NORMAL, Color::White, Color::Black, "")
        }
    }
}

fn main() {
    let rustbox = match RustBox::init(Default::default()) {
        Ok(v) => v,
        Err(e) => panic!(e),
    };

    let path = env::args().nth(1).unwrap();
    let file = match File::open(&path) {
        Ok(file) => file,
        Err(e)   => panic!(e)
    };
    let file_reader = BufReader::new(&file);

    display_screenful(&rustbox, file_reader, 0);
    rustbox.present();

    loop {
        match rustbox.poll_event(false) {
            Ok(rustbox::Event::KeyEvent(key)) => {
                match key {
                    Some(Key::Char('q')) => { break; }
                    Some(Key::Char(' ')) => {
                        display_screenful(&rustbox, file_reader, rustbox.height());
                        rustbox.present();
                    }
                    _ => { }
                }
            },
            Err(e) => panic!("{}", e.description()),
            _ => { }
        }
    }
}

1 个答案:

答案 0 :(得分:4)

首先,你不应该要求BufReader<&'static File>。你不能提供一个。请求代替BufReader<&'a File>一生'a

fn display_screenful<'a>(rb: &RustBox, fr: BufReader<&'a File>, offset: usize)

或者,简而言之,

fn display_screenful(rb: &RustBox, fr: BufReader<&File>, offset: usize)

这还不够 - 然后你最终将file_reader移到了函数中。你应该借用:

fn display_screenful(rb: &RustBox, fr: &mut BufReader<&File>, offset: usize)

然后编译。