Can't nest namespaces in `test` blocks

I’m trying to declare a function that returns a struct within a test block, but I’m getting an error.

Example:

test {
    const Foo = struct {
        pub fn init() Foo {
            return .{};
        }
    }

    const foo = Foo.init();
    _ = foo;
}

And this is the error I get:

test.zig:19:23: error: use of undeclared identifier 'Foo'
        pub fn init() Foo {
                      ^~~

This behavior is the same with methods, e.g.:

test {
    const Foo = struct {
        pub fn bar(self: Foo) void {
            _ = self;
        }
    }

    const foo: Foo = .{};
    foo.bar();
}

It seems I can’t reference a struct/namespace I declare in a test block. Is this the intended behavior?

Yes this is the intended behavior. This happens for regular function bodies as well.
You can use @This() to refer to the struct from the inside here:

pub fn init() @This() {

Or your can also make a declaration Self:

    const Foo = struct {
        const Self = @This();
        pub fn init() Self {
            return .{};
        }
    }
4 Likes

Tests are like functions and you can declare structures in them.
The problem is that Foo is not declared yet. You can use @This() instead (or const Foo = @This();).

2 Likes

Ah, make sense. I think this is what I was missing here – that tests are like functions. Thanks guys!

2 Likes