Why is this call ambiguous? Both functions indeed do have the same names, but the signatures are clearly different. And if the signatures had been the same, how would I have called the global function?
But… it’s a struct, not a scope. I would imagine the Bar’s method to be recognized as Bar.foo instead of foo here. Hence, calling foo would call foo, and never Bar.foo.
pub fn main() void {
var k: u32 = 2;
k = k * k;
var j: u32 = 0;
while (j < 3) {
var k = j;
j += 1;
}
}
results in
$ /opt/zig-0.10/zig build-exe shadow.zig
shadow.zig:7:13: error: local variable 'k' shadows local variable from outer scope
var k = j;
^
shadow.zig:3:9: note: previous declaration here
var k: u32 = 2;
^
i.e the word “shadow” is explicit.
But “structurally” it is the same - same identifier in outer/inner scope, same identifier in outer/inner namespace… something like that I guess.
Yep, that’s the workaround I have recently used. Although, I changed the name of the method. That’s just a bit annoying, since there is seemingly (IMHO) no reason for it to be this way.
What would be the disadvantage of being explicit like this? In an Object Oriented language you could probably get away with using the same name foo in both cases, but does that make the code better? I suppose it makes it easier to write, but not easier to read and unambiguously understand what’s going on; especially if a year has gone by, or the call site is 10,000 lines apart from the definition of the global.
Now that you mentioned it, I was indeed leaning towards things I got used to in OOP. But I can also understand the Zig’s point of view. I guess that’s the matter of taste at this point.
… but why use global functions in “main” (or not very “main”) file at all?
Suppose that global function is some utility/helper function. Okay, let put them
all into separate file (== namespace):
// util.zig
const std = @import("std");
pub fn doThis() void {
std.log.info("I am doing this", .{});
}
pub fn doThat() void {
std.log.info("And I am doing that", .{});
}
That’s interesting, I would have expected it to be consistent with the global stuff. This might be an oversight either in the design or the implementation. I’ll ask Andrew when I get a chance.
In a sense. That issue, #705 and #1836 are about declarations and fields having the same name at call site (going as far as proposing a special syntax for this), and this one is about (potential) ambiguity of calling declarations with the same name in a scope (e.g., in Foo’s scope above you have two foo’s).