#How to iterate over ArrayList in a for loop?

1 messages · Page 1 of 1 (latest)

snow galleon
#

Hello I have a ArrayList of objects that have a method, I am trying to iterate over it using a for loop. But the item in between pipes is of type *const T but my method takes *T. How can i fix this issue?

// Library imports here

// This is the object
const Boid = struct {
    const boidRadius = 5;
    const boidPointerLen = 10;

    pos: rl.Vector2 = rl.Vector2{ .x = width / 2, .y = height / 2 },
    vel: rl.Vector2 = rl.Vector2{ .x = 1, .y = 1 },
    acc: rl.Vector2 = rl.Vector2{ .x = 0, .y = 0 },

    // The method
    fn draw(self: *Boid) void {
        const velAngle = std.math.atan2(f32, self.vel.y, self.vel.x);

        rl.DrawLineV(self.pos, rl.Vector2{ .x = (std.math.cos(velAngle) * boidPointerLen) + self.pos.x, .y = (std.math.sin(velAngle) * boidPointerLen) + self.pos.y }, rl.RAYWHITE);

        rl.DrawCircleV(self.pos, boidRadius, rl.RAYWHITE);
    }
};



pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    defer _ = gpa.deinit();

    // var boids = try allocator.alloc(Boid, boidCount);
    // defer allocator.free(boids);

    var boids = std.ArrayList(Boid).init(allocator);
    defer boids.deinit();

    var i: usize = 0;
    while (i < boidCount) : (i += 1) {
        try boids.append(Boid{});
    }

    // Some code...

    while (!rl.WindowShouldClose()) {
        
        // Some code...

        // Here is the problem
        for (boids.items) |boid| {
            boid.draw();
        }
    }
}


noble jungle
#

just make the capture a pointer

for (boids.items) |*boid| boid.draw();
#

to be quite clear, boid is of type *T here, but could also be *const T if the iterated slice were of type []const T

snow galleon
#

Thx for the solution, it works :)