0

I'm trying to call SomeClass().call, but am running into compiler errors.

Specifically, running tests for

const std = @import("std");

test "doing a thing" {
    {
        const calc_result = SomeClass().call(.{});
        try std.testing.expectEqual(calc_result, 42);
    }
}

fn SomeClass() type {
    return struct {
        fn call(context: .{}) u32 {
            _ = context;
            return 42;
        }
    };
}

results in the error message

src/test.zig:12:17: error: expected type 'type', found '@TypeOf(.{})'
        fn call(context: .{}) u32 {
                ^~~~~~~
referenced by:
    test.doing a thing: src/test.zig:5:40
    remaining reference traces hidden; use '-freference-trace' to see all reference traces

How do I call a generic type method that takes an empty context?

CrepeGoat
  • 2,315
  • 20
  • 24

1 Answers1

1

What you're doing is equivalent to fn foo(value: 0) void {}. Which is obviously wrong. A function definition cannot have values.

You need to define the type of the context:

const std = @import("std");

const Context = struct {
};

fn SomeClass() type {
    return struct {
        fn call(context: Context) u32 {
            _ = context;
            return 42;
        }
    };
}

test "doing a thing" {
    {
        const calc_result = SomeClass().call(.{});
        try std.testing.expectEqual(calc_result, 42);
    }
}

Or, use anytype:

fn call(context: anytype) u32 { ... }
sigod
  • 3,514
  • 2
  • 21
  • 44
  • so in other words: `.{}` is a value (specifically an empty tuple); and it doesn't have an explicit type (other than maybe `@TypeOf(.{})`) so I have to give it one, like your `Context`, or use `anytype`? – CrepeGoat Jan 10 '23 at 21:08
  • Yes, that's right. – sigod Jan 10 '23 at 22:50
  • ah, ok I was hoping `.{}` had an explicit off-the-shelf type that I could use. thanks! – CrepeGoat Jan 10 '23 at 23:37
  • side note: I could also use the signature `fn call(context: void) ...` and call it like `SomeClass().call({})` to get an "empty" context – CrepeGoat Jan 13 '23 at 07:19