too-many-lists/ok-stack/peek #791
Replies: 4 comments 5 replies
-
在定义peek时,为何rust不允许这种定义方式: pub fn peek(&self) -> Option<&T> {
self.head.map(|ref node| {
&node.elem
})
} 编译器的报错是 self.head.map(|node| {
let ref ref_node = node;
&ref_node.elem
}) 想请教下这种理解是否正确。 |
Beta Was this translation helpful? Give feedback.
3 replies
-
pub fn peek(&self) -> Option<&T> {
Some(&self.head.as_ref()?.elem)
} |
Beta Was this translation helpful? Give feedback.
1 reply
-
声明中mut和闭包中的mut不一样,前者表示声明一个可变变量,后者表示模式匹配一个可变变量。除此之外,函数参数中也有mut的身影,冒号前通常修饰参数名,冒号后修饰引用。 |
Beta Was this translation helpful? Give feedback.
1 reply
-
#[allow(dead_code)]
struct Temp {
num: i32,
}
#[allow(dead_code)]
fn ok_to_get_ref(temp: &Temp) -> &i32 {
&temp.num
}
// 这段代码无法工作, 类似于跳过 as_ref 直接调用 map, 在 map 函数运行时获得了 self 本身的所有权
// self 内部的变量也就是 data owned by the current function
// 进一步, 如果返回 self 内部变量的引用则导致:returns a reference to data owned by the current function
fn not_ok_to_get_ref(temp: Temp) -> &i32 {
&temp.num
} |
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.
-
too-many-lists/ok-stack/peek
https://course.rs/too-many-lists/ok-stack/peek.html
Beta Was this translation helpful? Give feedback.
All reactions