如何在以下代码中正确返回set函数中的引用?我确实理解变量set
在块结束时超出了范围,但它引用的数组是拥有的并且是活动的。终身'b
的尝试是徒劳的。
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Appearance<'a> {
identity: &'a u64,
role: &'a str
}
#[derive(Clone, Copy, Debug)]
enum Dereference<'a> {
Dereference1ary {set: [&'a Appearance<'a>;1]},
Dereference2ary {set: [&'a Appearance<'a>;2]},
}
impl<'a, 'b> Dereference<'a> {
fn set(&self) -> &'b [&'a Appearance<'a>] {
match *self {
Dereference::Dereference1ary{set} => &set,
Dereference::Dereference2ary{set} => &set
}
}
}
fn main() {
let r = "hair_color";
let i1 = 42;
let i2 = 43;
let a1 = Appearance{identity: &i1, role: r};
let a2 = Appearance{identity: &i2, role: r};
let d1 = Dereference::Dereference1ary{set: [&a1]};
let d2 = Dereference::Dereference2ary{set: [&a1, &a2]};
let list: Vec<Dereference> = vec!(d1, d2);
println!("{:?}", list);
println!("{:?}", d1.set());
}
这里设有一个游乐场:https://play.rust-lang.org/?gist=fd528ebd054a9ce96004c8608166f9ac&version=stable&backtrace=0
答案 0 :(得分:5)
问题是Derefencece1ary{set}
复制set
并引用该副本。您想要的是使用set
Dereference1ary{ ref set }
字段
impl<'a> Dereference<'a> {
fn set(&self) -> &[&'a Appearance<'a>] {
match *self {
Dereference::Dereference1ary{ref set} => set,
Dereference::Dereference2ary{ref set} => set,
}
}
}
请注意,您的生命周期'b
是多余的,但如果您明确要求,则可以写
fn set<'b>(&'b self) -> &'b [&'a Appearance<'a>]
因为你想借用self
对象的一部分,所以生命周期需要匹配。