Lifetime bounds for `std::str::strip_prefix` should be relaxed

Currently the bounds for std::str::strip_prefix are:

pub fn strip_prefix<'a, P>(&'a self, prefix: P) -> Option<'a str>
    where P: Pattern<'a>

But it doesn't really make any sense that the output's lifetime should depend on the lifetime of the pattern. Something like this would make more sense:

pub fn strip_prefix<'s: 'p, 'p, P>(&'s self, prefix: P) -> Option<'s str>
where 
    P: Pattern<'p>

since the Pattern really only needs to stay alive inside the function call itself.

I'm currently dealing with an issue in which a function takes a &mut &str and a Pattern<'static>, but the borrow checker is mad that the &str isn't 'static as well. I haven't found anyone else complaining about this, but I'm sure I'm not the first person who's wanted this changed

Pattern<'a> doesn't mean the lifetime of the pattern itself is 'a, but rather of the string we match against.

I think the bounds are correct:

So anything requiring Pattern<'static> does require &'static str. I think whatever API you're working with needs to be updated to allow shorter lifetimes.

"Can only work on 'static haystacks" is exactly what P: Pattern<'static> means.

Perhaps you or whomever imposed the Pattern<'static> constraint meant P: for<'any> Pattern<'any>.

1 Like

Ah gotcha. I probably messed up the bounds on my end somehow

Uh...yes. Somehow you fixed my problem without even looking at the code.

In case anyone is looking at this in the future and doesn't understand this like I didn't, the issue is that in fn foo<'a>(pat: impl Pattern<'a>), pat has exactly one lifetime, whereas in fn<P> foo(pat: P) where P: for<'a> Pattern<'a>, the Rust compiler treats pat like it is compatible with all lifetimes at once, meaning it will be compatible with any &str, whether that's a &'a str, &'short str, or a &'static str

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.