I'm really new to Rust with less than a day of rusting. I'd like to know if the following code is ok or could it be written somehow better, and specifically, which would be the preferred way to handle the actual error case.
The return type bool represents whether a packet was received or not, so that the call to tryReceiveUdp can be chained using bool::then to do something else instead.
fn tryReceiveUdp(socket:UdpSocket) -> std::io::Result<bool>
{
let mut buf = [0; 1024];
let r = match socket.recv_from(&mut buf)
{
Ok((bytes,src)) => {
handleUdp(buf[..bytes].to_vec(),src)?;
false
},
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => true,
//Err(e) => Err(e) <-- Is this better than the next line?
e => {e?;true}
};
Ok(r)
}
Edit: There's a mistake in the above. The code initially didn't have Ok(r) at the end. Instead the specific question was between these two
Err(e) => Err(e), //<-- Is this better than the next line?
e => {e?;Ok(true)},
truewhen nothing happened is very unintuitive for atry*function. \$\endgroup\$tryReceiveUdp(&socket)?.then(|| sleep(Duration::from_millis(100)));\$\endgroup\$if !tryReceiveUdp(&socket)? { sleep(Duration::from_millis(100)) }\$\endgroup\$boolvariable to indicate whether to sleep or not and check that at the end of the loop. I'm wondering what is the most rustic approach. \$\endgroup\$