Mistakes with Rust smart pointers: when Deref goes wrong
fuzzypixelz.com
fuzzypixelz.com
For example, Box<T> implements Deref so that you can conveniently use T's methods. If you look at the documentation of Box, the things you can do with the Box itself, like Box::leak, are non-method functions. This means that you always have to qualify them, like Box::leak(my_box), and thus you can't get this type of conflict.
Using Deref for types like String or Vec doesn't really fall into this category. They implement something more analogous to an "is-a relationship" in OO. Even outside of those examples, I've seen people manually implement inheritance-like behavior, using Deref to delegate to a field that stores the "base class" instance.
If you do that, you're likely to have a name conflict between the two types sooner rather than later. That's fine as long as you're aware that Rust doesn't really do overload resolution -- AFAICT, the "outer" methods always wins regardless of the arguments at the call site.
IMHO there the logic behind that is very clear and makes a lot of sense. I think it's natural that view-related traits (the ones who operate on the elements of a contiguous area of memory) should be associated with slices, while memory-related ones (the ones that operate on an owning container) should be implemented on the owning types. If you mix them up, you are bound to mess up first and foremost because _it is not logically sound_. You don't need to own a string in order to check if all of its ASCII characters are all caps, for instance, because it's an operation that's also valid on any array of bytes, without the whole concept of "owning memory".
Interestingly you can ask whether a string is ASCII, "this".is_ascii() is a predicate which does exactly that, but for what I think is your question, "are they all ASCII caps?" you'd need to go via an iterator and a lambda: "THIS".bytes().all(|b| b.is_ascii_uppercase())
The iterator is because there is no provision of each such predicate over the whole string, which seems reasonable (the character class predicates are provided on u8 (ASCII only), and on char (all of them)), but the lambda is due to Rust's 1.0 compatibility commitment plus an unfortunate historical choice. If not for compatibility we'd fix it so you could just write "THIS".bytes().all(u8::is_ascii_uppercase)
That's a heavy lift though, you may need to carry this special code around in every compiler, forever, and I haven't even figured out what such code should look like, it might be really hard to even write it.
I imagine this is explicitly state in some portion that I have never read of the Deref documentation. The thing is, every introductory text ignores this, and there is no itemized rule in a more global document so that things like Rc and Cell can point directly to it.
The Rust docs have a very general discoverability problem, and this is one of its facets. Since things have a very generic and reusable definition, the docs have no good place to put information like that.
It's also worth noting that if the ambiguity is between two trait impls rather than the concrete type and one of its trait impls, the compiler does require explicit disambiguation (either by calling the method as a top-level function on the trait and passing in the `self` parameter or by casting before calling the method)[1].
[0]: https://play.rust-lang.org/?version=stable&mode=debug&editio... [1]: https://play.rust-lang.org/?version=stable&mode=debug&editio...
It's one of the few places that C++ is more explicit than Rust. I wonder if there's a reason Rust went a different way? I'm mainly a C++ programmer so I'm genuinely curious.
Yes there is a difference at the call site between taking a reference to an owned thing and taking potential ownership of the thing.
However inside the function block it is noise. Nothing inside the code is semantically different between the two forms, both do work on preexisting data.
Certainly the second version could have a change where it does something with respect to the fact it is a smart pointers, changing what used to be a grabbed pointer to a weak pointer to be more explicit about lifetimes for instance.
However that code change would be just as explicit as long as there aren't any methods on the smart pointer in the auto deref world.
There are lots of things wrong with C and C++ that Zig and Rust fixes, but I never thought of this one being problematic in any way. It's as easy to type, the difference is obvious, and it's easy to see from a glance what's going on.
Incidentally, the authors of Go were asked why they didn’t use a postfix dereference when Sethi noted[1] back in 1981 that C syntax would have been simpler that way, was quoted in Ritchie’s 1993 retrospective[2] on that point, and even their own blog post on declaration syntax pointed out that possibility[3], but IIRC the answer amounted to “but then we wouldn’t have gotten those sweet, sweet C-bandwagon popularity points”.
(I also cannot help calling out “Language X” here: One nice approach that nevertheless basically forces implicit dereferencing is that of Algon-68, where all values are constant values; the way to declare a mutable variable is to declare a pointer—a constant value—to a mutable cell; and the way to make the whole thing bearable is to have the compiler infer the minimum possible amount of dereferencing in an expression from the types of the values involved. Then of course it becomes impossible to infer the types, so the ML family goes with the inconvenient dereferencing, and you end up not really using a lot of mutability in ML.)
[1] https://dx.doi.org/10.1002/spe.4380110606
Rust and Go have the pointer have the unified syntax, but I thought in zig it does differentiate between the pointer itself and the value it points to.
Rust and Go:
ptr.method_on_ptr() ptr.method_from_underlying_val()
Zig:
ptr.method_on_ptr() ptr.*.method_from_underlying_val()
That's true but I think the bigger motivation is avoiding ambiguity than seeing when an indirection is happening. (You also can't see whether a method is virtual, i.e. indirecting via the vtable, from the call site.) In C++ references don't have any standalone methods or operators so there's no ambiguity from using methods via a reference just using a dot.
To the extent that this is a problem, it's a problem with references as a language feature in general, not with the arrow syntax.
Right. Rust's doesn't allow much overloading of function names. Partly because C++ did. The C++ overload resolution rules got very complex, especially since they interact with implicit conversions. To keep those rules from introducing errors, there's a rule in C++ that the overload chosen must be at least one step "better" than any matching alternative. Something that was supposed to make thing simpler thus became very complicated.
So Rust makes the programmer write that stuff out, which is more verbose but less confusing.
bool operator()(const LLDispatcher* dispatcher, const std::string& key
...
Yes, they actually overloaded "()". void foo(std::string x, int y);
void foo(const char* x);
Then calls to foo("bar", 0) would resolve to the first overload: the second isn't a match at all, but the first is a match with an implicit conversion from const char* to std::string. But if you removed the second parameter, including arguments at all call sites, then foo("bar") would match the second better because it doesn't involve any conversions, so it would be selected instead of the first.Boom. No longer compiles.
Yes I understand the complex and surprising rules that cause this to happen. That doesn't make them any less complex and surprising.
The callers won't find a matching signature once there is 1 less parameter. I don't see what is confusing about it.
You probably misunderstood that warning as "No callers pass this parameter", which btw would only make sense for a parameter with a default value.
I went from
void foo(A a, B b) {
// Only use a
}
...
foo(x, y);
To this void foo(A a) {
// Only use a
}
...
foo(x);
And it stopped compiling. There were no other functions called `foo` so it is nothing to do with overloading.I'll give you the answer if you want or we can leave it a mystery so you can experience how confusing that behaviour is...
[1] https://en.m.wikipedia.org/wiki/Argument-dependent_name_look...
https://rust-unofficial.github.io/patterns/anti_patterns/der...
One of the reasons for Deref (ab)use is that Rust doesn't have a good story for delegation for newtypes yet...
What happened is that in many usages the compiler would insert an implicit deref which would lead to an `Index` implementation being available.
But this does not work in all cases. Not just the case mentioned in the article but many others. The simplest is that it doesn't implement the `Index` trait and hence any generic bound requiring `Index` will fail if you try to use it with a `AsciiString`.
So it important to _not think of `Deref` as a form of inheritance ever_ nor use this as a oversimplifications when teaching rust or similar, it will only lead to a lot of confusion.
Additionally smart pointer in rust are "pointer like" which means you don't expect them to have methods by themself or anything like that. Hence why special methods on smart pointers are implemented as static function on the type, instead of methods.
Through `Deref` can also idiomatically be implemented for types with a owned/borrowed duality (e.g. `String`/`&str`) so `AsciiString/AsciiStr` would work but `AsciiString/str` won't be ideomatic.
Then if you idiomatically implement traits on this types you won't run into the issue described in the post, as you implement all you `Index` types and similar on the `&AsciiStr`/`&mut AsciiStr` etc.
Anyway there is a way to get a reference to a different kind of type, e.g. getting a `&str` from a `AsciiString`. It's `AsRef`. But that is not automatically applied like `Deref` for the reasons many reasons including stuff like mentioned in the Article.
Lastly a better way to think about why it doesn't work is that the type resolver looks if the type is implemented on your concrete type in some form and only if it isn't it will potentially dereference. And due to technical details of how type resolving reliable in multiple direction can be tricky `Index<T>` does count here as "the type is implemented" even if the `T` doesn't match.
The articles conclusion of not implementing `Deref` (in most cases) is something I can fully agree with.
From the start, I wished that Rust had used different punctuation for method calls on a `T` and a `SmartPtr<T>`. For instance, `my_t.f()` but `my_boxed_t->f()` (or get rid of auto Deref and just require `(my_boxed_t).f()`). For subscripting it could be something like `my_vec->[index]` (or just require `(my_vec)[index]`. Just something there to remind you that you are in fact using a smart pointer. This would also let you distinguish between `box.leak()` and `box->leak()` and not require `Box::leak(box)`.
str::from_utf8( as Deref>::deref(&self.0))
Thanks for the article! ^_^I finally found out what was going wrong here. All angle brackets and other characters were being escaped in other parts of the document, even in <code></code> blocks. Except when it came to code blocks inside <pre></pre> blocks.
For context, I use Zola and Cloudflare pages.
It turns out there is a bug[^0] in Zola 1.40.0 which reads:
> Fix code blocks content not being escaped when not using syntax highlighting
I presume that this is the culprit, as I use an external syntax highlighting library.
Cloudflare Pages has been famously sluggish with updating the Zola version. For reference, 1.14.0 was released in July 2021.
This explains why everything was working fine on my machine™.
Thanks for pointing this out, though I unsure how to work around it without changing my setup.
[^0]: https://github.com/getzola/zola/blob/master/CHANGELOG.md#014...
You can change this under Settings > Builds & deployments > Build system version. Cheers!
Apparently you can now ZOLA_VERSION to _any_ version you desire in v1 and the build system will install it on demand. I didn't realize that part had changed.
On the other hand, v2 doesn't even have Zola; my builds failed with a "failed to find zola command".
I guess we're now set for life, and will never have to wait for Cloudflare to update the image in order to bump the version. Less headaches for everyone.
Source: https://developers.cloudflare.com/pages/platform/language-su...
struct AsciiString(Vec);
and impl Index> for AsciiString {But isn't that wrong already? The element type `u8` is not an ASCII char. We need a subtype of `u8`, like `u7` if that existed.
Not following here, the compiler iterates over the deref-chain and acquires a list of method names, but it also "checks for ... where-clauses", what does that mean? A quick look at the linked probe code indicates what we filter on Self traits and return value traits.
str::from_utf8( as Deref>::deref(&self.0))
And I totally agree with the conclusion of the article: don't implement Deref yourself.