#Why doesn't usingnamespace work as I expect it to?

1 messages · Page 1 of 1 (latest)

idle basalt
#

I have a project with two files:

pub const Foo = struct {
    i: u32,
};
const std = @import("std");
usingnamespace @import("foo.zig");

pub fn main() !void {
    const foo = Foo { .i = 42 };
    std.debug.print("{}", .{ foo.i });
}

I would expect this to compile, but I'm getting this error:

    const foo = Foo { .i = 42 };```

Why isn't `Foo` visible in `main.zig`?
sick trail
#

Decls have to be pub to be exposed through @import

idle basalt
#

Oh, of course, sorry. That was a typo, even with pub it doesn't work. Edited the original post.

ruby osprey
#

usingnamespace makes the decls available when qualified. you would have to use @This().Foo for your example to work.

idle basalt
#

I see

ruby osprey
#

there's no way to use decls from another file unqualified

#

except making new names in your scope

idle basalt
#

Is this the intended behavior?

#

The docs for usingnamespace aren't super clear, so I mostly guessed what it would do coming from C++

ruby osprey
#

an identifier in scope of more than one usingnamespace forces all of them to be resolved, in order to make sure there are no name conflicts. However, using a.b syntax means only the includenamespace declarations that apply to a must be resolved. With incremental compilation, having an identifier force an unrelated usingnamespace to be resolved creates a dependency between these two things.

#

it's a bit unintuitive but it makes sense as a decision to me

idle basalt
#

Yeah, it makes sense actually

#

From the compilers point of view at least 🙂

#

I need to do some thinking on how to to organize a larger project. I'm used to working with many small files organized into folders, where the folders map to namespaces. It seems like that approach won't work very well in Zig.

balmy cargo
#

it just means you can't import identifiers en-masse, you can still do const assert = std.debug.assert;

hollow quartz
fierce owl
#

the other way it losses where did the symbol come from

#

so it's harder to track down usages