gpt4 book ai didi

sockets - 循环中匹配臂中的变量来自哪里?

转载 作者:行者123 更新时间:2023-11-29 08:36:40 25 4
gpt4 key购买 nike

我正在尝试使用 this as a starting point 在 Rust 中实现一个 HTTP 客户端.我被 rust-lang.org 网站通过他们的 TcpStream 页面中的 rust-by-example 建议之一转到了这个链接。我正在研究如何从 TcpStream 中读取数据。我正在尝试遵循此代码:

fn handle_client(mut stream: TcpStream) {
// read 20 bytes at a time from stream echoing back to stream
loop {
let mut read = [0; 1028];
match stream.read(&mut read) {
Ok(n) => {
if n == 0 {
// connection was closed
break;
}
stream.write(&read[0..n]).unwrap();
}
Err(err) => {
panic!(err);
}
}
}
}

n 变量从何而来?它到底是什么?作者说一次读取20个字节;这是从哪里来的?

我还没有真正尝试过任何东西,因为我想在尝试之前先了解一下。

最佳答案

我强烈建议您阅读所用工具的文档。在这种情况下,The match Control Flow Operator来自 Rust 编程语言 解释了您需要了解的内容。

来自Patterns that Bind to Values部分:

In the match expression for this code, we add a variable called state to the pattern that matches values of the variant Coin::Quarter. When a Coin::Quarter matches, the state variable will bind to the value of that quarter’s state. Then we can use state in the code for that arm, like so:

fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("State quarter from {:?}!", state);
25
},
}
}

If we were to call value_in_cents(Coin::Quarter(UsState::Alaska)), coin would be Coin::Quarter(UsState::Alaska). When we compare that value with each of the match arms, none of them match until we reach Coin::Quarter(state). At that point, the binding for state will be the value UsState::Alaska. We can then use that binding in the println! expression, thus getting the inner state value out of the Coin enum variant for Quarter.

an entire chapter关于可用的模式匹配语法及其使用位置。

关于sockets - 循环中匹配臂中的变量来自哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56465813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com