Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix bug in lifetime.md #576

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all 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
4 changes: 2 additions & 2 deletions ownership-system/lifetime.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,15 @@ fn foo<'a>(x: &'a str) -> &'a str {
}
```

在这里,约束返回值的Lifetime必须大于或等于参数`x`的Lifetime。下面函数写法也是合法的:
在这里,约束返回值的Lifetime必须是其依赖的输入值参数`x`的Lifetime的子集。下面函数写法也是合法的:

```rust
fn foo<'a>(x: &'a str) -> &'a str {
"hello, world!"
}
```

为什么呢?这是因为字符串"hello, world!"的类型是`&'static str`,我们知道`static`类型的Lifetime是整个程序的运行周期,所以她比任意传入的参数的Lifetime`'a`都要长,即`'static >= 'a`满足
为什么呢?这是因为字符串"hello, world!"的类型虽然是`&'static str`,我们知道`static`类型的Lifetime是整个程序的运行周期,但它的生命周期不依赖于输入值`x`的生命周期,因此可以编译成功


在上例中Rust可以自动推导Lifetime,所以并不需要程序员显式指定Lifetime `'a` 。
Expand Down