3 ms·
Here's a case I ran into. I have a `Span` type and it can act like `RangeInclusive`. I want to index into a `&str` with it. This looks something like this :
by duped 5y ago
Here's a case I ran into.
I have a `Span` type and it can act like `RangeInclusive`. I want to index into a `&str` with it. This looks something like this :
use std::ops::Index;
pub struct Span {
start:usize,
end:usize,
}
impl<'a> Index<Span> for &'a str {
type Output = str;
fn index(&self, span:Span) -> &Self::Output {
&self[span.start..=span.end]
}
}
(NB4 RangeInclusive, in this example, Span is almost identical to RangeInclusive, in practice it was not)
Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=70e409cb51af1a267e3367f375fa2543 https://play.rust-lang.org/?version=stable&mode=debug&editio...
This gives you a cryptic error :
error[E0308]: mismatched types
--> src/lib.rs:10:19
|
10 | &self[span.start..=span.end]
| ^^^^^^^^^^^^^^^^^^^^^ expected struct `Span`, found struct `RangeInclusive`
|
= note: expected struct `Span`
found struct `RangeInclusive<usize>`
For more information about this error, try `rustc --explain E0308
This is weird, because you can definitely index into a `&str` with `RangeInclusive`.
What you actually need to do is implement it for `str` instead of `&'a str`. This is a little peculiarity with how the `str` type works (to date, this is the only time I've ever needed the raw `str` type and not &str! it almost never is required) and the generic implementation for Index<I> for str combined with how Deref works.
It's a small one line change to fix the code, but it's not obvious from the error message how to do it, and a bit tricky to solve unless you knew a little bit more about how Rust's operators get parsed/implemented.
In my experience this is a common class of problems when you deal with generic and trait programming in Rust. It's ultimately the front end to an advanced constraint solver, and due to the explosion of complexity when you start making generic things more/less generic you will hit the wall with weirdness and need to understand more about the type system rather than letting the type system prevent you from doing stupid things.
Frankly the memory management issue is not a problem once you buy into ownership.