相关疑难解决方法(0)

什么时候在 Rust 中使用 ref?

我注意到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?这里有什么惯用的编程实践吗?

rust

6
推荐指数
1
解决办法
121
查看次数

Rust模式匹配如何确定绑定变量是引用还是值?

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引用是参考,因此将值从引用中移出是没有意义的,但是是否有任何明确定义规则的规范?

pattern-matching rust

0
推荐指数
1
解决办法
86
查看次数

标签 统计

rust ×2

pattern-matching ×1