205 points · by xy2_ · 3y ago · 61 comments
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)
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.
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.
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.
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.
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.