2
如何在下面的代碼中正確地返回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
謝謝,ref關鍵字正是我在找的東西,但還沒有學習:) –