简体   繁体   English

为什么 Rust 在循环后重置一些变量?

[英]Why Rust reset some variables after a loop?

I finished reading The Rust Programming Languange some time ago and I'm creating a simple http-server for the sake of teaching myself Rust.我前段时间读完了 Rust Programming Languange,为了自学 Rust,我正在创建一个简单的 http 服务器。

In a function meant to parse a &[u8] and create a HttpRequest object, I noticed that a loop that should be parsing the headers is actually not updating some variables used to track the state of parsing:在旨在解析&[u8]并创建HttpRequest object 的 function 中,我注意到应该解析标头的循环实际上没有更新一些用于跟踪解析的 state 的变量:

pub fn parse_request(buffer: &[u8]) -> Result<HttpRequest, &'static str> {
    let (mut line, mut curr_req_reader_pos) = next_req_line(buffer, 0);

    let (method, path, version) = parse_method_path_and_version(&line)?;

    let (line, curr_req_reader_pos) = next_req_line(buffer, curr_req_reader_pos);
    //eprintln!("--- got next line: {}, {} ---", curr_req_reader_pos, String::from_utf8_lossy(line));
    let mut headers = vec![];
    let mut lel = 0;
    while line.len() > 0 {
        //eprintln!("LOOP");
        let header = parse_header(&line);
        eprintln!("--- parsed header: {} ---", String::from_utf8_lossy(line));
        headers.push(header);
        let (line, curr_req_reader_pos) = next_req_line(buffer, curr_req_reader_pos);
        //eprintln!("--- got next line: {}, {} ---", curr_req_reader_pos, String::from_utf8_lossy(line));
        let (line, curr_req_reader_pos) = next_req_line(buffer, curr_req_reader_pos);
        //eprintln!("--- got next line: {}, {} ---", curr_req_reader_pos, String::from_utf8_lossy(line));
        //eprintln!("LOOP");
        lel += 10;
        //break;
    }

    let (line, curr_req_reader_pos) = next_req_line(buffer, curr_req_reader_pos);
    //eprintln!("--- got next line: {}, {} ---", curr_req_reader_pos, String::from_utf8_lossy(line));
    //eprintln!("{}", lel);

    let has_body;
    match method.as_ref() {
        "POST" | "PUT" | "PATCH" => has_body = true,
        _ => has_body = true
    };

    let body;
    if has_body {
        let (line, curr_req_reader_pos) = next_req_line(buffer, curr_req_reader_pos);
        body = String::from_utf8_lossy(line).to_string();
    } else  {
        body = String::new();
    }

    Ok(HttpRequest {
        method,
        path,
        version,
        headers,
        has_body,
        body
    })
}

There's also tests for each method:还有针对每种方法的测试:

#[test]
fn test_next_req_line() {
    let req = "GET / HTTP/1.1\r\nContent-Length: 3\r\n\r\n\r\n\r\nlel".as_bytes();

    let (mut lel, mut pos) = next_req_line(req, 0);
    assert_eq!("GET / HTTP/1.1", String::from_utf8_lossy(lel));
    assert!(lel.len() > 0);
    assert_eq!(16, pos);

    let (lel, pos) = next_req_line(req, pos);
    assert_eq!("Content-Length: 3", String::from_utf8_lossy(lel));
    assert!(lel.len() > 0);
    assert_eq!(35, pos);

    let (lel, pos) = next_req_line(req, pos);
    assert_eq!("", String::from_utf8_lossy(lel));
    assert!(lel.len() == 0);
    assert_eq!(37, pos);

    let (lel, pos) = next_req_line(req, pos);
    assert_eq!("", String::from_utf8_lossy(lel));
    assert!(lel.len() == 0);

    let (lel, pos) = next_req_line(req, pos);
    assert_eq!("", String::from_utf8_lossy(lel));
    assert!(lel.len() == 0);

    let (lel, pos) = next_req_line(req, pos);
    assert_eq!("lel", String::from_utf8_lossy(lel));
    assert!(lel.len() == 3);
}

    #[test]
    fn test_parse_request() {
        let mut request = String::from("GET / HTTP/1.1\r\n");
        request.push_str("Content-Length: 3\r\n");
        request.push_str("\r\n");
        request.push_str("lel");
        let request = request.as_bytes();

        match parse_request(&request) {
            Ok(http_request) => {
                assert_eq!(http_request.method, "GET");
                assert_eq!(http_request.path, "/");
                assert_eq!(http_request.version, "HTTP/1.1");
            },
            Err(_) => {
                println!("Failed");
            }
        }
    }

The commented lines are just to show what's happening, and that's where I saw this output:注释行只是为了说明发生了什么,这就是我看到这个 output 的地方:


    Finished test [unoptimized + debuginfo] target(s) in 0.53s
     Running target/debug/deps/rweb-6bbc2a3130f7e3d9

running 4 tests
test http::testing::test_next_req_line ... ok
test http::testing::test_parse_header ... ok
test http::testing::test_parse_method_path_and_version ... ok
--- parsed method path version  ---
--- got next line: 35, Content-Length: 3 ---
LOOP
--- parsed header: Content-Length: 3 ---
--- got next line: 37,  ---
--- got next line: 39, lel ---
LOOP
--- got next line: 37,  ---
10
test http::testing::test_parse_request ... ok

test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

It seems that the while loop is not re-assigning the line and curr_req_reader_pos variables, but for me it made perfect sense to expect that the loop would update these variables and parse every header. However, it works perfecly outside a loop, as anyone can see in the tests.似乎while循环没有重新分配linecurr_req_reader_pos变量,但对我来说,期望循环会更新这些变量并解析每个 header 是完全合理的。但是,它在循环外工作得很好,任何人都可以在测试中看到。

I can't figure out why this happens with my current undertanding of Rust, why does it happen?我无法弄清楚为什么我目前对 Rust 的理解会发生这种情况,为什么会发生这种情况?

You aren't "reassigning" variables in the loop, you create new variables that temporarily shadow the outer ones and then go out of scope when the iteration ends.您不是在循环中“重新分配”变量,您创建的新变量会暂时隐藏外部变量,然后在迭代结束时从 scope 中创建 go。

Here's an illustration as to what is going on in simplified pseudocode:这是关于简化伪代码中发生的事情的说明:

let x0 = 0
{
    let x1 = x0 + 1 // original x gets shadowed, x = 1
    let x2 = x1 + 1 // x1 gets shadowed, x = 2
} // both x1 and x2 go out of scope
let x1 = x0 + 1 // x = 1

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

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