Iteratively add to MeshBuilder

Hi, I'm not sure exactly how to phrase this question, so I'll try my best.

I have a MeshBuilder from the ggez crate and I'm trying to use a for-loop to consecutively add random rectangles to it.

Code:

let mut rng = rand::thread_rng(); 
let mut mesh_builder = graphics::MeshBuilder::new();

let (size_x, size_y) = graphics::drawable_size(ctx);

for _ in 0..100 {
    //Create a rectangle somewhere inside the screen
    let new_rect = graphics::Rect::new(
        rng.gen_range(0.0, size_x - 100.0), //x pos
        rng.gen_range(0.0, size_y - 100.0), //y pos
        100.0, //width
        100.0 //height
    );
    //add rectangle to mesh_builder
    mesh_builder = mesh_builder.rectangle(graphics::DrawMode::fill(), new_rect, graphics::WHITE);
}

let mesh = mesh_builder.build(ctx).unwrap();

The error is on this line:

mesh_builder = mesh_builder.rectangle(graphics::DrawMode::fill(), new_rect, graphics::WHITE);

"expected struct MeshBuilder, found &mut MeshBuilder"

So, I tried dereferencing it:

mesh_builder = *mesh_builder.rectangle(graphics::DrawMode::fill(), new_rect, graphics::WHITE);

And here it says that it can't dereference since MeshBuilder doesn't implement the Copy trait. Side question if anyone's willing to answer it: Why do I need to copy a value just to change it? Can Rust really not just add a rectangle to the MeshBuilder buffer?

Any help fixing this would be seriously appreciated. Thank you!

The method signature is

pub fn rectangle(&mut self, /* ... */) -> &mut Self

So that you can do things like

mesh_builder
    .rectangle(/*...*/)
    .rectangle(/*...*/)
    .rectangle(/*...*/)
    .rectangle(/*...*/);

It's just passing back the mutable reference it got. There's no reason to keep it around (to save the return value) unless you started with just a &mut MeshBuilder and needed to hold on to it so you could do more.

In this case, you have the MeshBuilder (not just a &mut MeshBuilder borrow), and you're trying to assign the &mut MeshBuilder return to your MeshBuilder variable -- hence the error.

Just do

mesh_builder.rectangle(graphics::DrawMode::fill(), new_rect, graphics::WHITE);

and don't assign over mesh_builder.

Man, I don't know why I didn't think of that. Thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.