提交 7b642af1 编写于 作者: F feilong

add lifetime exercise

上级 8992cd1a
......@@ -18,8 +18,8 @@ fn main() {
```rust
fn main() {
let str = "Hello,World!";
println!("{}", str);
let str1 = "Hello,World!";
println!("{}", str1);
}
```
......
{
"node_id": "rust-d38898d251df42d49f5f367f077ede55",
"keywords": []
"keywords": [],
"children":[],
"export": [
"lifetime.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"author": "huanhuilong",
"source": "lifetime.md",
"notebook_enable": false
}
\ No newline at end of file
# Rust 函数的生命周期
选出以下Rust代码中,生命周期错误的选项
## 答案
```rust
// compile error!
// where am I come from?
fn process_objs(x:&Obejct, y:&Object):&Object{
if(x.is_ok()){
&x
}else{
&y
}
}
```
## 选项
### 如果这个借用本来就是从外部传入的,那当然可以返回,函数结束后这个对象还是有效的
```rust
// I am borrowed from caller
// return borrow to the caller is safe
fn process_obj(obj:&Object):&Object{
&obj
}
```
### 显式添加生命周期标记
```rust
// I am come from 'a lifetime, NOT 'b
fn process_objs<'a,'b>(x: &'a Obejct, y:&'b Object):&'a Object{
&x
}
```
### 显式添加生命周期标记,解决歧义
```rust
// I am come from 'a lifetime, x,y,and result are all 'a lifetime
fn process_objs<'a>(x: &'a Obejct, y:&'a Object):&'a Object{
if(x.is_ok()){
&x
}else{
&y
}
}
```
......@@ -4,7 +4,7 @@
"keywords": [],
"children": [
{
"Rust初阶": {
"rust初阶": {
"node_id": "rust-e2292238ccbf403d85fb20dd7b4c85ad",
"keywords": [],
"children": [
......@@ -14,7 +14,7 @@
"keywords": [],
"children": [
{
"Rust简介": {
"rust简介": {
"node_id": "rust-7c394f164d8f44519521f03db08a1321",
"keywords": [],
"children": [
......@@ -68,7 +68,7 @@
}
},
{
"Rust安装": {
"rust安装": {
"node_id": "rust-502b3cef4dbc41fdad069522470f3662",
"keywords": [],
"children": [
......@@ -96,7 +96,7 @@
}
},
{
"认识Rust工具链": {
"认识rust工具链": {
"node_id": "rust-0d9e5f9449b94aa692a363f21a66c8af",
"keywords": [],
"children": []
......@@ -120,7 +120,7 @@
}
},
{
"Rust基本概念": {
"rust基本概念": {
"node_id": "rust-2cea732119294abab6f2887a364b242a",
"keywords": [],
"children": [
......@@ -272,7 +272,7 @@
}
},
{
"Rust中阶": {
"rust中阶": {
"node_id": "rust-7377966439734497b91f3d775f9b0e0d",
"keywords": [],
"children": [
......@@ -387,7 +387,7 @@
}
},
{
"Rust高阶": {
"rust高阶": {
"node_id": "rust-981f4f37a8e547abb135f54592ac52a5",
"keywords": [],
"children": [
......@@ -496,14 +496,14 @@
}
},
{
"用Rust实现X算法": {
"用rust实现X算法": {
"node_id": "rust-d935276e360d41deb87caa06272c1ade",
"keywords": [],
"children": []
}
},
{
"用Rust解X题": {
"用rust解X题": {
"node_id": "rust-f8981b363064411c86d033f391ec133c",
"keywords": [],
"children": []
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册