#Pass slice into function and modify elements

1 messages · Page 1 of 1 (latest)

kindred pollen
#

Is there a simpler way of doing this? I feel like **Point type that I capture in the loop is weird.


const Point = struct {
    x: usize,
    y: usize,
};

fn init_points(points: *[]Point) void {
    for (points.*, 0..) |*point, i| {
        point.* = Point{ .x = i, .y = i };
    }
}

pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    defer _ = gpa.deinit();
    var points: []Point = try allocator.alloc(Point, 10);
    defer allocator.free(points);

    init_points(&points);
    std.debug.print("Points {any}\n", .{points});
}```
steep current
#

for the code block you need const std on the line after ```

meager timber
kindred pollen
meager timber
kindred pollen
#

Yes type hints are from LSP. I don't understand why I need **Point just so I can dereference it in the next line with point.*. If I had *Point I wouldn't need to dereference?

meager timber
#

the LSP is wrong, if you @compileLog(@TypeOf(point)) it will show you its a *Point, and you need the dereference syntax to write to a pointer's destination