Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions tutorial/09_lifetimes.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,9 +201,17 @@ impl<'a> ImportantExcerpt<'a> {
fn main() {
let novel = String::from("Call me Ishmael. Some years ago...");
let first_sentence = novel.split('.').next().expect("Could not find a '.'");
let i = ImportantExcerpt {
part: first_sentence,
};

let res;
{
let i = ImportantExcerpt {
part: first_sentence,
};
res = i.announce_and_return_part("生命周期");
println!("{}", res);
}
// 根据上面的规则3,res的生命周期由 i 决定。此处 i 已经离开作用域,故 res 无效
// println!("{}", res);
}
```

Expand Down
14 changes: 7 additions & 7 deletions tutorial/10_trait_objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ fn benchmark() {
let start = Instant::now();
let mut sum: i64 = 0;
for _ in 0..1000000 {
sum += adder.compute(10); // 隐式转换 i32 到 i64
sum += adder.compute(10) as i64; // 隐式转换 i32 到 i64
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

加了 as i64,就不是隐式转换了

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

加了 as i64,就不是隐式转换了

是的是的,忘了改之前的注释,rust不支持这种隐式转换。重新改了一下注释

}
println!("静态分发时间: {:?}", start.elapsed());
println!("静态分发结果 (i32): {}", sum);
Expand Down Expand Up @@ -568,23 +568,23 @@ fn use_service(service: &mut dyn Service, input: &str) -> String {
}

// 2. 必要时才转移所有权
struct ServiceManager {
services: Vec<Box<dyn Service>>,
struct ServiceManager<'s> {
services: Vec<Box<dyn Service + 's>>,
}

impl ServiceManager {
impl<'s> ServiceManager<'s> {
// R: 提供只读访问
fn find_service(&self, index: usize) -> Option<&dyn Service> {
fn find_service(&self, index: usize) -> Option<&(dyn Service + 's)> {
self.services.get(index).map(|s| s.as_ref())
}

// W: 提供可变访问
fn find_service_mut(&mut self, index: usize) -> Option<&mut dyn Service> {
fn find_service_mut(&mut self, index: usize) -> Option<&mut (dyn Service+'s)> {
self.services.get_mut(index).map(|s| s.as_mut())
}

// O: 转移所有权(谨慎使用)
fn extract_service(&mut self, index: usize) -> Option<Box<dyn Service>> {
fn extract_service(&mut self, index: usize) -> Option<Box<dyn Service + 's>> {
if index < self.services.len() {
Some(self.services.remove(index))
} else {
Expand Down