Skip to content

Using struct method as function argument causes compiler to fail #4022

Closed
@cshenton

Description

@cshenton

The following simple "apply" function works for a top level declaration but not for a method. Resulting in a compiler error:

const std = @import("std");

pub fn apply(func: var, arr: []f32) void {
    for (arr) |*el| {
        el.* = func(el.*);
    }
}

pub fn double(x: f32) f32 {
    return 2*x;
}

const TimesBy = struct {
    x: f32,

    pub fn func(self: TimesBy, y: f32) f32 {
        return self.x * y;
    }
};

// This works fine
test "plain function arguments" {
    var vals = [_]f32{1, 2, 3, 4, 5};
    apply(double, vals[0..]);

    std.testing.expect(vals[0] == 2);
    std.testing.expect(vals[1] == 4);
    std.testing.expect(vals[2] == 6);
    std.testing.expect(vals[3] == 8);
    std.testing.expect(vals[4] == 10);
}

// This errors the compiler
test "functor arguments" {
    var vals = [_]f32{1, 2, 3, 4, 5};
    const functor = TimesBy{ .x = 3 };
    apply(functor.func, vals[0..]);

    std.testing.expect(vals[0] == 3);
    std.testing.expect(vals[1] == 6);
    std.testing.expect(vals[2] == 9);
    std.testing.expect(vals[3] == 12);
    std.testing.expect(vals[4] == 15);
}

The output is:

$ zig test scratch.zig
Unreachable at D:\a\1\s\src\analyze.cpp:5241 in hash_const_val. This is a bug in the Zig compiler.
Unable to dump stack trace: debug info stripped

I'm sure this is an indication I'm doing things in an unintended way, what is the correct way to implement this sort of behaviour in zig currently?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugObserved behavior contradicts documented or intended behaviorstage1The process of building from source via WebAssembly and the C backend.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions