CAD97
July 11, 2021, 6:32am
2
Generally, the indexing syntax is useful for code clarity in that it returns a view (reference) into the indexed object.
What benefit (other than terseness) do you get by returning an owned 'static
value from indexing? That isn't provided by just a .get()
?
Additionally, what happens if you implement both Index
and MyIndex
? If you can't, how is that enforced?
Previously:
The motivation for this post is to get some feedback on a potential solution to a problem discussed several times before. I have not seen this exact solution being discussed, but perhaps it is trivially bad without me realizing it. What I want answered is if it is worth pursuing the problem further or if by some detail of how the language or the compiler works it is inherently a bad idea.
The problem is concerned referencing a view in some larger array. I have attempted to structured the text t…
The biggest flaw with proposals to make indexing return a custom view type, as I understand it, is actually quite simple and fundamental: thing[index] isn't actually sugar for calling Index::index! It's actually quite complicated and very directly coupled to references and autoref rules, in that roughly:
thing[index] is typed as a place (rvalue) of type Index::Output.
If the place is used by mutable reference, either via autoref rules or directly taking &mut of the place,
IndexMut::index_mu…
There's a thread (now closed) about generalizing Index and IndexMut to return "view" types that aren't references. There's also a prior RFC which was declined for accidentally proposing a solution that breaks backwards compatibility.
Here, I'd like to discuss a potential non-breaking solution: adding new indexing trait which supersedes the old ones, while providing covering implementations for types that implement the old types. More concretely:
trait CoolIndex<'a, Idx: ?Sized> {
type Outp…
&var[idx] isn't translated to &(Index::index(&var, idx)). It's translated to Index::index(&var, idx). The introduced reference is "lost", and effectively it is your var.index_by_ref(idx), as var.index(idx)/Index::index(&var, idx).
The point I'm trying to convey is that &var[idx] evaluating to a type that isn't &_ is going to be surprising, and lose the affordance that the current syntax has.
On top of this, if [] doesn't always return T, &T, or &mut T, but instead, for example, returns Result<T…
(Wow I've argued this point a fair number of times... indexing returning a custom type seems like an obvious extension, it just runs into a whole thorny bush of issues once you start digging into the implications. Maybe I should write up some lang design notes to this effect...)
5 Likes