sách gpt4 ai đã đi

rust - 具有 &str 和生命周期的索引特征

In lại 作者:行者123 更新时间:2023-11-29 08:14:15 26 4
mua khóa gpt4 Nike

我正在尝试为具有生命周期和挣扎的结构实现 Index 特征。我希望内部向量在 &str 上可索引。 IE。 myqstr["foo"].

这是我得到的:

pub struct QString<'a> {
pub params: Vec>
}

pub struct Param<'a> {
pub name: &'a str,
pub value: &'a str,
}

impl<'a, 'b> ::std::ops::Index<&'b str> for QString<'a> {
type Output = Param<'a>;
fn index(&self, index: &'b str) -> &Param<'a> {
&self.params.iter()
.rposition(|ref p| p.name == index)
.map(|pos| self.params[pos])
.unwrap()
}
}

错误是经典的。

   Compiling qstring v0.1.0 (file:///Users/martin/dev/qstring)
error[E0597]: borrowed value does not live long enough
--> src/lib.rs:113:10
|
113 | &self.params.iter()
| __________^
114 | | .rposition(|ref p| p.name == index)
115 | | .map(|pos| self.params[pos])
116 | | .unwrap()
| |_____________________^ does not live long enough
117 | }
| - temporary value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the method body at 112:5

我明白 Index 要我返回索引结构的借用值,而且我知道我要返回的生命周期是 'a,但是那是在这种情况下甚至可能吗?

1 Câu trả lời

你在错误的地方引用了引用,你想在你的 .map 函数中引用。

self.params.iter()
.rposition(|ref p| p.name == index)
.map(|pos| &self.params[pos])
.unwrap()

因为您想要引用 Vec 本身中的参数。

这样做也更容易

self.params.iter()
.rev()
.find(|p| p.name == index)
.unwrap()

关于rust - 具有 &str 和生命周期的索引特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46632474/

26 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com