u/GimmeaRedditNamePlz

▲ 14 r/rust

I'm trying to learn Rust by rewriting a 2D fluid simulation I wrote in C++. I've hit a wall with the compiler/analyzer that I cannot wrap my head around and LLMs aren't giving me anything too helpful. I'm using nalgebra for Vector/Matrix operations, which seems to be where this issue is coming from...

I've got the following code, where I'm iterating over my sim's particles field, which is a Vec of Particles, whose definition is also below.

use std::fmt;
use nalgebra::DMatrix;
use nalgebra::Vector2;
use rand::RngExt;
struct Particle {
    pos: Vector2<f32>,
    vel: Vector2<f32>,
}

//...

fn grid_to_particles(&mut self) {
    for i in 0..self.particles.len() {
        let foo = self.particles[i].vel;
        //...
    }
    self.particles.iter_mut().for_each(|p| {
        let foo = *p.vel;
        //...
    });
}

The rust analyzer is telling me that foo has type Vector2<f32> in the for loop, which makes sense to me as that is the type I assigned in the Particle struct. foo in the for_each() method however, apparently has type XY<f32>. At first I thought this was just the analyzer hallucinating, but attempting to compile yields an error because I'm attempting to subtract an XY<f32> type from a Vector2<f32>.

Here is the compiler error I get where it's complaining about the type mismatch. I do not get this if using the aforementioned for loop instead

I cannot understand where this XY type is coming from. I can compile with the full implementation of the first for loop, but the for_each() loop seems like to more idiomatic way to write this function. I can post the complete file, but I don't think the rest of it is relevant to this question.

Thanks in advance!

reddit.com
u/GimmeaRedditNamePlz — 12 days ago