我注意到Microsoft 的 Take your first steps with Rust 中的代码:
fn count_letters(text: &str) -> usize {
text.chars().filter(|ref c| c.is_alphabetic()).count()
}
Run Code Online (Sandbox Code Playgroud)
很明显,没有ref
.
为什么ref
用在这里?我应该什么时候使用ref
?这里有什么惯用的编程实践吗?
use crate::List::{Cons, Nil};
#[derive(Debug)]
struct Foo {}
#[derive(Debug)]
enum List {
Cons(i32, Foo),
Nil,
}
impl List {
fn tail(&self) -> Option<&Foo> {
match self {
Cons(_, item) => Some(item), // why `item` is of type `&Foo`?
Nil => None,
}
}
}
Run Code Online (Sandbox Code Playgroud)
如评论中所述,为什么是item
类型&Foo
?说的item
是类型&Foo
而不是类型的规则是什么Foo
?
我理解项目是没有意义的Foo
; &self
表示self
引用是参考,因此将值从引用中移出是没有意义的,但是是否有任何明确定义规则的规范?