Skip to content

Pointer to tuple does not auto-dereference when accessed as indexable #13852

@cryptocode

Description

@cryptocode

Zig Version

0.11.0-dev.640+71c82393e

Steps to Reproduce and Observed Behavior

const std = @import("std");

const MyTuple = struct { i32, u32 };

// Accessing a pointer to array via pointer works with direct indexing and for loop
pub fn printArray(x: *[2]u32) void {
    std.debug.print("first array item is: {}\n", .{x[0]});

    for (x) |val, i| {
        std.debug.print("array[{}] is: {}\n", .{i, val});
    }
}

// Tuples are indexable and has a len property, so I expected the same behavior as above
// Pointer to tuples, however, require explicit dereferencing with .* so this won't compile
pub fn printTuple(x: *MyTuple) void {
    std.debug.print("first tuple item is: {}\n", .{x[0]});

    inline for (x) |val, i| {
        std.debug.print("tuple[{}] is: {}\n", .{i, val});
    }
}

test "tuple" {

    var arr: [2]u32 = [2]u32{ 1, 2 };
    printArray(&arr);

    var x: MyTuple = .{ 1, 2 };
    printTuple(&x);
}

Fails with:

`error: element access of non-indexable type`

and

`error: type '*tuple.MyTuple' does not support indexing`

Expected Behavior

Since tuples are indexable and have a length like arrays, I expected dereferencing to happen as with arrays.

  • If x is a pointer to array, then direct indexing works with x[0] as Zig auto-dereferences

  • If x is a pointer to tuple, then x[0] gives error element access of non-indexable type

Should autoderef also happen for tuples? This would make ptr-to-indexable consistent, and I suspect that would be helpful for certain generic code.

Same question with for loops, as ptr-to-array is auto deref'ed, but that's not the case with ptr-to-tuple.

Perhaps this is by design, but it came as a surprise and I couldn't find a reasons for it, so making this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedThis proposal is planned.enhancementSolving this issue will likely involve adding new logic or components to the codebase.proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions