@import inside a function

Hello,

I am on the exercise “Isogram”. I implemented the solution with a StaticBitSet. As I only need 1 single instance of it and nothing else from the std-library, I come to the idea to import it inside the function:

pub fn isIsogram(str: []const u8) bool {
    var alphabet = @import("std").StaticBitSet(26).initEmpty();
// [...] rest of the code

Is there any difference to import std at the global level?

My thinking was: “Keep the scopes tight. No unnecessary names in the global scope.”

Is this good style?

Kindly regards
Eisenaxt

I’m not a Zig expert, so take this with a grain of salt!

Is there any difference to import std at the global level?

No, on a functional level this should be identical.

My thinking was: “Keep the scopes tight. No unnecessary names in the global scope.”

  1. Doing a const std = @import("std"); is a convention used throughout Zig code.
  2. Rarely will anyone want to use std as a name in a function, because that would very much confuse people because of 1)
  3. Having all external dependencies clearly listed at the start of a file makes it a lot easier to check for dependencies. If you used your inline style that would be much harder to find out.

Maybe one thing might help a bit if you aren’t aware: Imported stuff in zig is always bound to the struct that you assign the import to. So you don’t have the same type of global scope pollution that you would have in C or JS. Only your current file is affected by any global scope variables, not the files that import your file.

2 Likes