Apologies for the confusing title... If someone thinks of a better one, please edit this post.
I defined a trait like this:
pub trait AsUrlParams
where <Self::I as IntoIterator>::Item: Borrow<(Self::K, Self::V)>,
{
type I: IntoIterator;
type K: AsRef<str>;
type V: AsRef<str>;
fn as_url_params(&self) -> Self::I;
}
Implementing it for &Vec<(T, U)>
is straightforward:
impl<'a, T, U> AsUrlParams for &'a Vec<(T, U)>
where T: AsRef<str>,
U: AsRef<str>,
{
type I = Self;
type K = T;
type V = U;
fn as_url_params(&self) -> Self::I {
*self
}
}
However, I hit a lifetime issue when trying to implemented it for &mut Vec<(T, U)>
:
impl<'a, T, U> AsUrlParams for &'a mut Vec<(T, U)>
where T: AsRef<str>,
U: AsRef<str>,
{
type I = Self;
type K = T;
type V = U;
fn as_url_params(&self) -> Self::I {
*self
}
}
Here is the error:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/main.rs:186:13
|
186 | *self
| ^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 185:43...
--> src/main.rs:185:44
|
185 | fn as_url_params(&self) -> Self::I {
| ____________________________________________^ starting here...
186 | | *self
187 | | }
| |_________^ ...ending here
note: ...so that reference does not outlive borrowed content
--> src/main.rs:186:13
|
186 | *self
| ^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the body at 185:43...
--> src/main.rs:185:44
|
185 | fn as_url_params(&self) -> Self::I {
| ____________________________________________^ starting here...
186 | | *self
187 | | }
| |_________^ ...ending here
note: ...so that types are compatible (expected AsUrlParams, found AsUrlParams)
--> src/main.rs:185:44
|
185 | fn as_url_params(&self) -> Self::I {
| ____________________________________________^ starting here...
186 | | *self
187 | | }
| |_________^ ...ending here
I have two questions:
- Is there a way to implement this trait for
&'a mut Vec<(T, U)>
? - Why am I not hitting this error for
&'a Vec<(T, U)>
? It looks exactly the same to me from a lifetime perspective: the content of&self
is&'a Vec<(T, U)>
, which outlives&self
.