4 ms·
That makes sense! What's funny is, I went to go write the equivalent Rust code: struct Logger; impl Logger { fn log(&self, _: &str) {}
by steveklabnik 1y ago
That makes sense! What's funny is, I went to go write the equivalent Rust code:
struct Logger;
impl Logger {
fn log(&self, _: &str) {}
}
fn do_something(data: &str, logger: Option<Logger>) {
for l in logger {
l.log(data)
}
}
fn main() {
let logger = Some(Logger);
let data = "foo";
do_something(data, logger);
}
and rustc actually warns about this:
warning: for loop over an `Option`. This is more readably written as an `if let` statement
--> src/main.rs:8:14
|
8 | for l in logger {
| ^^^^^^
|
= note: `#[warn(for_loops_over_fallibles)]` on by default
help: to check pattern in a loop use `while let`
|
8 - for l in logger {
8 + while let Some(l) = logger {
|
help: consider using `if let` to clear intent
|
8 - for l in logger {
8 + if let Some(l) = logger {
|
I was actually going to say "I've never seen folks in Rust write out for loops this way, even though you can" and I suspect this lint has something to do with that!
I think this is most useful in generic contexts, I agree that I would not write this exact code this way because it does feel weird, if you know you have an Option, if let is the way to go. But if you're writing code over generic iterators, it can be nice that it exists.
- masklinn 1y ago> I think this is most useful in generic contexts And to build other iterators e.g. std::iter::once is a trivial wrapper around an Option::Some.
- kstrauser 1y agoHah! I've internalized rustc and Clippy. Good job, team! Yeah, I don't hate it. The semantics aren't wrong, either: an Option has 0 payload items or 1. It still feels wrong to me in ways I can't fully explain.