#Why doesn't Zig see the type of this struct property at compile time?

1 messages · Page 1 of 1 (latest)

snow anchor
#

Hey! I'm pretty new to Zig, and I ran into this error. It kind of baffles me. I reduced my code down to this simple example:

pub fn MyExample() type {
    return struct {
        x: usize = 0,
    };
}

// In this outer scope, it's implicitly comptime
// so I would expect that the type is fully known
const TheExample = MyExample();

test {
    var ex = TheExample {};
    try expectEqual(0, ex.x);
    // error: unable to resolve comptime value
}

test {
    var ex = TheExample {};
    try expectEqual(ex.x, 0);
    // This works, but the expected value should be the first param, not the second
}
slow vale
#

it isn't the type that's the problem - and just fyi, type is always evaluated at comptime, so doesn't matter whether the declaration is at global or local scope.

#

the issue here is that expectEqual is a bit stupid

#

its parameters look like this: expected: anytype, actual: @TypeOf(actual)

#

looking at the first test, you're specifying expected = 0

#

but it just so happens that @TypeOf(0) = comptime_int

#

which means that actual also takes on the type of comptime_int

#

but you're trying to pass a runtime-known value, the field x of ex, which is a struct value instantiated at runtime

#

the solution here would be to do try expectEqual(@as(usize, 0), ex.x)

#

and, yes, as you might imagine, there is an issue open for this on github, as it's a bit contentious

snow anchor
#

Okay, it makes sense now, thank you so much!

#

People can probably think of reasons why you might not want to do this, but since I'm just messing around, I made my own expectEquals that works how I expect

const std = @import("std");

pub fn expectEqual(expected: anytype, actual: anytype) !void {
    try std.testing.expectEqual(@as(@TypeOf(actual), expected), actual);
}