Ugh, Rust

tags: rust

Incoming links: MacSE Weather Display Network

Last updated on .

I love Rust, in contrast to Scala and Python but it ain't always easy. Here are a few of the sharp edges I've run into.

1. Opaque types keep being terrible to me

For example, this is a thing I've found myself wanting to do:

fn might_filter<F>(things: Vec<usize>, do_filter: bool, some_filter: F)
where
    F: Fn(&usize) -> bool,
{
    let usize_iterator = if do_filter {
        things.iter().filter(|s| some_filter(s))
    } else {
        things.iter()
    };
    for i in usize_iterator {
        println!("nr: {i}");
    }
}

The error you get is:

error[E0308]: `if` and `else` have incompatible types
...
... expected `Filter<Iter<'_, usize>, ...>`, found `Iter<'_, usize>`

That's annoying because both arms of that if statement are iterators over usizes, it's just that one of them also filters the iterator. That's a difference in behaviour not of kind.