gpt4 book ai didi

对于给定的 impl,rustc 可以是 "infer the appropriate lifetime",但不能用于另一个

转载 作者:行者123 更新时间:2023-11-29 08:27:22 28 4
gpt4 key购买 nike

<分区>

为令人困惑的标题道歉...如果有人想到更好的,请编辑这篇文章。

我定义了这样一个特征:

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;
}

&Vec<(T, U)> 实现它很简单:

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
}
}

但是,我在尝试为 &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
}
}

这里是错误:

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

我有两个问题:

  • 有没有办法为 &'a mut Vec<(T, U)> 实现这个特性? ?
  • 为什么我没有为 &'a Vec<(T, U)> 遇到这个错误?从一生的角度来看,它在我看来完全一样:&self 的内容。是&'a Vec<(T, U)> ,比&self长.

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com