lifetime/advance #206
Replies: 2 comments
-
好强,感谢大佬的无私奉献。 |
Beta Was this translation helpful? Give feedback.
0 replies
-
第一题 struct DoubleRef<'a, 'b: 'a, T> {
r: &'a T,
s: &'b T,
} 第二题 impl<'a, 'b> ImportantExcerpt<'a> where 'a: 'b {
fn announce_and_return_part(&'a self, announcement: &'b str) -> &'b str {
println!("Attention please: {}", announcement);
self.part
}
} 第三题 fn f<'a, 'b>(x: &'a i32, mut y: &'b i32) where
'a: 'b
{
y = x;
let r: &'b &'a i32 = &&0;
} 第四题 fn call_on_ref_zero<F>(f: F)
where
F: for<'a> Fn(&'a i32)
{
let zero = 0;
f(&zero);
} 第五题 fn main() {
let mut data = 10;
let ref1 = &mut data;
let ref2 = &mut *ref1;
*ref2 += 2;
*ref1 += 1;
println!("{}", data);
} 第六题 struct Interface<'i, 'm> where 'm: 'i {
manager: &'i mut Manager<'m> // i 借用了 m。则m必须大于i
}
impl Interface<'_, '_> { // 这里impl中不涉及引用,所以不必理会生命周期
pub fn noop(self) {
println!("interface consumed 《{}》", self.manager.text);
}
}
struct Manager<'m> {
text: &'m str
}
struct List<'m> {
manager: Manager<'m>,
}
impl<'m> List<'m> {
// i 为这个Interface的生命周期
pub fn get_interface<'i>(&'i mut self) -> Interface<'i, 'm> {
// ^^^^^^^^^^^^ <= 这里确保self把自己的manager借出去的时长与Interface 实例一致
Interface {
manager: &mut self.manager
}
}
}
fn main() {
let mut list = List {
manager: Manager {
text: "hello"
}
};
list.get_interface().noop(); // noop调用完归还list.manager的所有权
println!("Interface should be dropped here and the borrow released");
use_list(&list);
}
fn use_list(list: &List) {
println!("{}", list.manager.text);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
lifetime/advance
Learning Rust By Practice, narrowing the gap between beginner and skilled-dev with challenging examples, exercises and projects.
https://zh.practice.rs/lifetime/advance.html
Beta Was this translation helpful? Give feedback.
All reactions