256 points · by andreabergia · 3y ago · 164 comments
I see this desire to get rid of shadowing all the time, but in practice it's such a disruptive restriction.
> You'll have to be more creative when coming up with variables that don't shadow existing ones (which, for me, generally means using more obscure names).
The last adjective I want used in relation to my variable names is “obscure.”
It’s just so damn useful and I’m not sure what the downside is, it sucks when you have to keep coming up with different names so you can keep around an identifier that you don’t need anymore.
Rust's Into::into() is consuming the object in the old (now shadowed) rect variable. So conveniently the old rect variable which we can't access also no longer has a value†. In many languages a method can't consume the object like that, so the old object still exists but we can't access it because it is shadowed.
For example in C++ they have move semantics, but their move isn't destructive, so the object is typically hollowed out, but still exists until the end of the scope at least.
Rust's type strictness matters here too. It means if you later modify some code using rect meaning whatever it was before that statement morphing it into a Rect<f32> chances are it doesn't type check and is rejected. For example in many languages if (rect) { ... } would be legal code and might change meaning as a result of the transformation, but in Rust only booleans are true or false.
† Unless this previous variable's type implemented the Copy trait and therefore it has Copy semantics and consuming it doesn't do anything.
Also useful because you can’t have abstracted local types, so let’s say you’re building an iterator in a language with interfaces you could do something like
let it: Iterator = some().thing();
// intermediate stuff
it = it.some().transform();
// more intermediate stuff
it = it.final().transform();
But in Rust that won’t work, every adapter yields a different concrete type, you’d have to box every layer to make them compatible. Intra-scope shadowing solves that issue.The biggest downside is that it’s possible to reuse names for completely unrelated purposes, which can make code much harder to understand. Clippy has a shadow_unrelated lint but it’s allowed by default because it’s a bit limited.
The downside is that you may get a weird bug and only after a while see that you accidentally overwrote a function parameter and the Rust compiler didn't even warn you about it.
For this reason I always add the following line to my projects to enable warnings:
#![warn(clippy::shadow_reuse, clippy::shadow_same, clippy::shadow_unrelated)]
You can also use "deny" instead of "warn" to make it an error.
I also like "#![deny(unreachable_patterns)]", which detects bugs in enum pattern matching if you accidentally match "Foo" instead of "Type::Foo" - I honestly don't know why this isn't set by default.My day job is predominantly in Typescript and a lot of code winds up reading significantly worse than it needs to. A common pattern for me is unique-ifying some sort of array—“const dataUnique = new Set(data);” is horrible, and if there’s no reason to keep the original “data” variable in scope then it’s doubly bad; I want to keep as little context in my head as possible.
That said, I still think sparing use of this is justified, especially with an editor which can show types on mouseover.
Shadowing is not a big deal with IDEs; you can always see the type of the variable , jump to definition easily etc etc.
The rule to not shadow variables makes more sense when you want to understand the code just by looking at it.
let x = foo() in
let x = bar x in
let x = baz x in
print x
In a functional language where mutation is less convenient than in C++, this is really handy, and I wanted Rust to support the same idiom.Well, second-to-last right after "misleading".
Specifically this kind of code (and I do not feel calling them e.g. iter1 and iter2 or foo_iter and bar_iter make the code nice):
var iter1 = foo_dir.iterate();
while (try iter1.next()) |entry| {
// Do something
}
var iter2 = bar_dir.iterate();
while (try iter2.next()) |entry| {
// Do something else
} {
var iter = foo_dir.iterate();
while (try iter.next()) |entry| {
// Do something
}
}
{
var iter = bar_dir.iterate();
while (try iter.next()) |entry| {
// Do something
}
}But also:
var iter = foo_dir.iterate();
while (try iter.next()) |entry| {
// Do something
}
iter = bar_dir.iterate();
while (try iter.next()) |entry| {
// Do something else
}
You can totally just reassign `iter` here since you're done with the first iterator (assuming they are both the same type, which appears to be the case).1) have bad coding habits. (playing with zig broke me of some of these)
or
2) you need to autogenerate code.
2 is a much harder nut to crack.
what to name things
cache coherency
off by one bugs
This feels like a mistake to me. I own and maintain a C library, and lack of private struct members is one of the things that causes the most problems. My users frequently reach into struct members even though I really do not want them to. This causes problems when those members have subtly different semantics than what they expect. It's even worse when I want to change the internal representation, and I have to track down all my users' code and change it accordingly.
In C, my only options are:
(1) Define the structure in a .c file instead of .h. This works great in cases where I can take the performance hit of not being able to inline accesses of those struct members. But for performance-critical structures where I need to be able to inline, this is not an option.
(2) Make the member names something like private_foo, internal_foo, etc. and hope my users take the hint. But this also makes my own code more ugly and creates longer lines that are more likely to wrap.
Unfortunately Zig is even less capable than C in this regard, because Zig takes away option (1). Since there is no header/source split in Zig, I cannot make a struct opaque by defining it in a source file only. Though I do see that there is "opaque {}", perhaps that plus some casting could accomplish a similar thing?
I see that rationale for not having private struct members was given here: https://github.com/ziglang/zig/issues/9909#issuecomment-9426...
> The idea of private fields and getter/setter methods was popularized by Java, but it is an anti-pattern. Fields are there; they exist. They are the data that underpins any abstraction. My recommendation is to name fields carefully and leave them as part of the public API, carefully documenting what they do. [...] In my subjective experience, public fields generally lead to better abstractions by eliminating the temptation to attempt full encapsulation, when the more effective strategy is to provide composable abstraction layers.
Java does indeed represent an anti-pattern of verbose and frequently trivial getters and setters. But newer languages like C#, Swift, and Dart have more elegant and low-overhead syntax for properties, even allowing a property to move between being an actual field member and being derived, without breaking users.
As a library maintainer, full encapsulation is very important for evolution of a system over time. The only way for layers to truly be layers is if the contract at each layer boundary is clear. Otherwise the layers gel together and you cannot safely change any one layer independently.
Something like so:
/// The internal implementation of this type.
const PrivateType = struct {
// Private fields.
field_a: u32,
field_b: bool,
// Public object exposed
public: PublicType,
// private functions here.
}
/// This gets exposed to the public API
pub const PublicType = struct {
// Public fields.
field_a: u32,
// Public functions here.
pub fn create(alloc: Allocator) !*PublicType {
var priv = try alloc.create(PrivateType);
return &priv.public;
}
/// Flips internal field b.
pub fn flip(p: *PublicType) void {
// Grabs the PrivateType that contains this PublicType as a field.
const self = @fieldParentPtr(PrivateType, "public", p);
self.*.field_b = !self.*.field_b;
}
}The purpose of this was to eliminate the need for "friend" classes.
This sometimes conflicts with what people coming from C and C++ are used to with everything being in one file (after headers are added by the preprocessor). But having modules gives opportunities for better ways to organize the code.
As for trivial property accessors and setters, those get inlined, so are not overhead.
Other languages would call these "internal", not "private".
It's not an anti-pattern.
This is how Java provides the exact functionality that you describe as very important (field encapsulation). Because Java doesn't support properties, it needs to go through getters and setters.
As you point out, more modern languages support this functionality directly in the language with properties.
Properties help avoid this anti-pattern by making it possible to transparently swap in a computed property for what used to be a plain field. This removes the incentive to proactively create trivial getters and setters "just in case."
Something has indeed gone wrong. The struct has succumbed to being a "kitchen sink".
Java's getters and setters *are* properties. Just with more syntactic sugar than languages that natively support properties, but the semantic is exactly the same.
if as a library writer you don't want me to access your private struct layout and as a user I want to, I promise there is absolutely nothing that I won't try, from casting to bytes and working there, passing things from / to DLL writtens in C, to running your program in a VM, etc. So why try to fight this fight? Just tell your users that go outside of the sanctioned route that you won't help them just like a car manufacturer won't help you hack into their engine but you still can and should be able to if you want to
Like the default is the compiler will throw a warning if you access a private field with a default reference.
So things like this works but the compiler bitches.
printf("what hell is bar doing %i", foo.bar); // throws a warning 'bar is private'
But you can have a reference that's all in for api functions.And also a reference that will throw a warning for any attempt access fields. The idea being it's a pure handle.
And, there are valid reasons for a library writer to want to warn people off using certain fields, but still have them in-structure. Work-in-progress, internal machinery that the writer may wish to refactor at their leisure, whatever.
You could write that warning up in the documentation, but it's probably better as a structural affordance in the code, because then it's not just enforceable, but also lends itself to automation.
Readers should have realistic expectations. It's not substantially downhill to write C like code. I ran into this bug right off the bat. TL/DL: Zig's linker does not pull in dynamic libs. It finds static libs but alas the .tsk doesn't give expected behavior anyway:
https://github.com/ziglang/zig/issues/14939
A. Kelly (head Zig dev), to his credit, seems to already be on top of in this through a related bug:
https://github.com/ziglang/zig/issues/14963
I didn't expect to run into link problems on day 1.
That seems similar to using "opaque {}", if I am understanding you correctly?
I think either of those solutions could potentially work, at the cost of one explicit cast in each function that actually needs to access the data. I would love to know if this works well enough in practice.
> I don't want to editorialize this post too much, but it's already caused the type of issues that you'd expect, and I think it'll only cause more difficulties in a 1.x world.
I wish the author elaborated a bit more here because I've always been interested in what problem exactly `private` (and all the language complexity/overhead) that comes with it solves. for something like C# it kind of makes sense because it's a language built around chaining method calls and IntelliSense, so the user types `foo.` and IntelliSense shows literally everything you could want to do with that `Foo` instance, excluding `private` members/methods. I can see the use-case for this in a corporate-type setting. in absence of this feature (which I believe is the case for Zig?), what possible difficulties can be caused, in practice?
Shout out to llvm for sticking with camelCase while the c++ library is all snake_case. Turns out eventually one gets used to reading mixtures of them and only occasionally writes dense_map or unorderedMap, but I still wish it wasn't like this.
edit: I write large patches in the one true style and then begrudgingly fix them up for review using ad hoc emacs macros but it looks like clang-tidy can automate that. Wonder if it's robust enough to bidirectionally convert between review acceptable and legible
Other than that, I'm definitely excited for Zig as a potential C++ replacement.
The symbol namespaces builtins, as those are the only identifiers that aren't declared in the file (either directly or by using `@import`).
// tea.zig
full: bool = true,
const Self = @This();
pub fn drink(self: *Self) void {
self.full = false;
}
// other.zig
const Tea = @import("tea.zig");
This example seemed to stop just short of the really interesting bit: what if other.zig called Tea.drink()? Would it set Tea.full to false? Maybe this is obvious to Zig users, but coming from C++, that would be a violation of const correctness.In C++ (thinking of classes rather than files), you wouldn't be able to call the drink method of a const object because it's not marked as a const method. Or, if it was marked as a const method, you wouldn't be able to modify full from in drink. You could get around this by marking full as mutable, which means you're going to deliberately violate const correctnees, but at least you have to be explicit about it. (In theory mutable is meant for things like caches that don't affect the visible behaviour of the class.)
To be clear: you would first need to create an instance of `Tea`.
var t: Tea = .{};
t.drink(); // will work and set t.full to false
If instead we declared `t` as `const`, then yes the call to `drink` would not have been possible.`const Self = @This();` just binds the top-level struct type definition to a name, which then allows you to refer to it in other plances. Nothing more than that.
Is it possible to mark a method const in Zig, like in C++? I guess you set the type of the self parameter to const *Self or similar?
fn foo(self: Self) void {}
fn bar(self: *const Self) void {}
fn baz(self: *Self) void {}
In this example, `foo` and `bar` cannot modify `self`, while `baz` can. In the case of `foo`, `self` is passed in by value, but since function arguments are immutable in Zig, it cannot be modified (the compiler might still opt for pass-by-reference under the hood, but the semantics don't change).In the case of `bar` we are explicitly asking for a constant pointer, as you mentioned.
You need an instance of Tea in order to call drink, and if it's const it won't compile because drink takes type *Tea, not *const Tea.
2. The type system is deep enough to describe the type of values, but not the type of types. That's what higher kinded types are for, and for better or for worse that's not part of zig. Also, type variables can only exist at compile time, so there is no runtime value.
pub fn expectEqual(expected: anytype, actual: @TypeOf(expected)) !void
to pub fn expectEqual(expected: @TypeOf(actual), actual: anytype) !void
What would the downsides be?https://github.com/ziglang/zig/issues/4437 is tracking the issue. I think std.testing is going to see some major changes, so it's possible this gets fixed. But going from the responses in that issue, I think that fix might be more of a side effect, since there doesn't seem to be too much sympathy for the issue as-is.
Also, do "Self" kind-of variables occupy memory?
How can I declare a (packed) struct describing a payload in a way that the struct can be then sent "as is" as a network packet?
Let's say this struct has a "calculateChecksum()" method. Will I need to declare "Self"? If so, will be "Self" part of the struct's memory layout?
In general, consts in Zig are purely compile time things and don't take up memory.
And putting a function inside a struct which takes a pointer to its struct type as first argument just allows method-call-syntax-sugar, but you can also write it as regular function (which must then be namespaced with the struct type though):
const Bla = struct {
const Self = @This();
val: i32 = 0,
fn add(self: *Self, val: i32) void {
self.val += val;
}
};
pub fn main() void {
var bla = Bla{};
// with method-call syntax sugar
bla.add(2);
// without method-call syntax sugar
Bla.add(&bla, 3);
}
...but in this case it's probably better to not use Self and @This() (it mostly makes sense with generics). const Bla = struct {
val: i32 = 0,
fn add(self: *Bla, val: i32) void {
self.val += val;
}
};1. If the first argument of a function is `self`, then that function is treated as a method and can be called like `obj.meth(args)`. Functions without `self` must be called statically, which in the case of an object would look like `Type::meth(obj, args)`. The second form is used occasionally by common wrapper types like Box and Rc to avoid dereferencing “piercing the veil” and calling a method on the wrapped object (Rust has no separate `obj->meth` syntax, which IMO is its own issue). 2. Having access to `Self` lets you specify the types of non-this arguments as well as return types, like `fn add(self, other: Self) -> Self {...}`. You can also use it as the name of the type when (de)structing objects, e.g., `let Self { fields } = other` or `return Self { fields }`. Writing out the name of the current type each time could get unwieldy. 3. `Self` as a namespace is handy when dealing with enums, e.g., `match self { Self::First => ..., Self::Second => ...}` or static functions like `Self::func(args)`. It's crucial in trait implementations when referring to associated types, e.g., in Iterator there's `type Item; fn next(&mut self) -> Option<Self::Item>;`
I don't why a Self variable would be placed on the stack differently from non-Self variables; method calls have always just been syntactic sugar + namespacing for a free function, no?
Not quite; they're more than that for languages that have dynamic dispatch, like virtual methods in C++ or dyn impl in Rust. In that case, that argument affects which function is called. In the case of multiple inheritence (in C++), the implicit this parameter is also potentially subject to a pointer offset; if it's virtual multiple inheritence then that offset may even be computed at runtime.
I'm only familiar with C++, not Zig, but it doesn't seem that different to me. If a C++ class includes a typedef, then that doesn't contribute to the class's footprint.
Even the explicit self parameter is not so different. In C++, a method can be marked as const or even && (rvalue reference) and that's applied to the implicit this parameter. If anything, it would be clearer if this was an explicit parameter; as of C++23, it actually is allowed to be [1], called "deducing this".
[1] https://devblogs.microsoft.com/cppblog/cpp23-deducing-this/
There is often a strong rationale behind clumsy syntax decisions, I hope they will fix those quirks.
> Types are PascalCase
> Variables are lowercase_with_underscores
Just why? It does not seem like the same language that used to treat tabs as a compiler error. Looks like the worst of every worlds to me. Why not just stick to one style?
Edit: Looks like they are already aware of the problem. That is good news.
https://github.com/ziglang/zig/issues/1097#issuecomment-6142...
It’s quite nice to work with, and comes naturally after a short while.
I actually use this approach in my style guides for my teams writing js too.
Once you get used to it, it's quite pleasant.
In js you run into some grey areas, like function type callable variables that look weird, but still make sense when named well: click_handler() read_complete_callback()
Maybe? They say their stage2 parser accepts them now.
On the other hand, manipulating sequences of data and pointers of various kinds is one of the main things you do when programming, and concise notation (especially in a low level programming language) is akin to how mathematicians have concise notation for the most common objects they manipulate in their formulas.
As for pointer types, they look reasonable but can't say much more.
They both do and don’t, which is a major issue with the language.
If you create a slice from an array, it’ll use that array as backing buffer. Likewise if you reslice and existing slice.
But because it also has an arraylist interface (kinda, it’s a bad one) you can quite easily stomp on other slices using the same backing buffer.
If there's one thing that's a nightmare about how zig handles these is that sometimes coercion between array types is a bit hidden and the rules are not obvious, though their application in code is usually straightforward and you don't have to think about it too much (AFAICT it doesn't let you do the wrong thing)
var tea = Tea{.full = true};
like: var tea = Tea{full = true};Here `full = true` is a valid expression syntax, and it'd be problematic if `{` could start a block of code here. This case may be parseable unambiguously thanks to `Tea` ident in the front, but e.g. if Zig ever wanted to add something like Swift's final closure syntax, then `expr { expr }` could become valid, and this would be ambiguous.
In Rust `if struct {}` is a parsing edge case. JS has ambiguous `{field: value}` objects and `{label: code}` blocks. CSS struggles to add nested rules, because syntaxes of `selector { property:value` and `selector { selector:selector` overlap, and that requires slower and/or more complicated parsers.
Golang has almost this exact problem in its grammar but in practice they manage just fine even though there are indeed some edge cases where parser gets confused:
> A parsing ambiguity arises when a composite literal using the TypeName form of the LiteralType appears as an operand between the keyword and the opening brace of the block of an "if", "for", or "switch" statement, and the composite literal is not enclosed in parentheses, square brackets, or curly braces. In this rare case, the opening brace of the literal is erroneously parsed as the one introducing the block of statements. To resolve the ambiguity, the composite literal must appear within parentheses.
if x == (T{a,b,c}[i]) { … }
if (x == T{a,b,c}[i]) { … }https://stackoverflow.com/questions/32698293/assign-values-t...
zig just error's, which is a silly behaviour.
What issues could public struct fields have caused?
As for public fields, the 0.9 change to allocator comes to mind. This was written off as a minor change, because Zig is pre 1.0. But what I haven't heard (and 100% upfront, I haven't looked hard), is how Zig plans on dealing with it post 1.0. Like, where are we in the gradient of: "1.0 will never break the public API (struct fields included)" to "deal with it".
> As for public fields, the 0.9 change to allocator comes to mind.
That's a good example of why it makes sense for Zig to have all fields be public: the change that we did to allocators has important implications that in Zig we don't want to hide behind a `private` descriptor. This is obviously not a universal truth, but it makes sense for a low-level programming language that cares about the details.
> Self is used in the standard library for non generic types every now and again.
I agree with the parent poster, those should probably be removed, as they don't really help make the code more readable or provide any other advantage. A overhaul of the stdlib is planned, but we're not there yet, as we're still busy working on the package manager and incremental compilation.
If I’m a library author and release something which exports a struct… I can never change any of the struct’s internal data structures? I can never rename a field. Or delete a field. Or change what should be an internal field’s type. And that makes non-breaking changes as a library author much more challenging, which may be a very serious problem for Zig, especially if the stdlib isn’t Go-style “batteries included”. I would seemingly need to version the structs to work around this: ArrayListV1, ArrayListV2…
Part of the beauty of great code is in its API design. And forcing my libs to document:
/// Don’t touch this field.
Without any way for me to hide the field itself from users or prevent them from using it is very strange. Users can’t intuit what to use and not use without studying documentation, which a well-thought out API might improve.
Go has been extremely successful in part due to its nicely thought out APIs in the stdlib. They have certain fields which anyone would care to use, and all the rest are—for your purpose as a user—not there. And this same design has made refactors of libraries/packages (without breaking changes for users) very easy.
I use relatively large fonts for medical reasons and tabs are much more accessible to me.