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

关于"生命周期"一节的问题 #558

Open
veekxt opened this issue Dec 15, 2017 · 0 comments
Open

关于"生命周期"一节的问题 #558

veekxt opened this issue Dec 15, 2017 · 0 comments

Comments

@veekxt
Copy link
Contributor

veekxt commented Dec 15, 2017

https://github.com/rustcc/RustPrimer/blob/master/ownership-system/lifetime.md

## 隐式Lifetime

我们经常会遇到参数或者返回值为引用类型的函数:

```rust
fn foo(x: &str) -> &str {
    x
}
```

上面函数在实际应用中并没有太多用处,`foo` 函数仅仅接受一个 `&str ` 类型的参数(`x`为对某个`string`类型资源`Something`的借用),并返回对资源`Something`的一个新的借用。

实际上,上面函数包含该了隐性的生命周期命名,这是由编译器自动推导的,相当于:

```rust
fn foo<'a>(x: &'a str) -> &'a str {
    x
}
```

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

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

为什么呢?这是因为字符串"hello, world!"的类型是`&'static str`,我们知道`static`类型的Lifetime是整个程序的运行周期,所以她比任意传入的参数的Lifetime`'a`都要长,即`'static >= 'a`满足。

这部分 在这里,约束返回值的Lifetime必须大于或等于参数x的Lifetime 是不是说反了? 而且"参数"和"返回值"的生命周期并没有关联性, 这里只是因为返回了参数x才有了联系, 容易误导. 而最后一个例子返回值与x无关, 不用考虑生命周期包含关系. 就算按错误思路考虑了也还是反的.
不过这节后面的手动指定lifetime时又纠正了... 另一个问题是仅靠"返回值依赖参数"就判断 "生命周期也有包含关系" 也不够严谨.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant