ref不能做什么呢? [英] What can ref do that references couldn't?

查看:96
本文介绍了ref不能做什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ref 不能做什么引用?可以

What can ref do that references couldn't? Could

match value.try_thing() {
    &Some(ref e) => do_stuff(e),
    // ...
}

不能等同地表达为

match value.try_thing() {
    &Some(e) => do_stuff(&e),
    // ...
}

推荐答案

否,建议的语法无法避免.您的语法不允许引用,否则将允许移动.在此示例中, inner val 中整数的副本,对其进行更改不会影响 val :

No, it is not avoidable with your proposed syntax. Your syntax does not allow for taking a reference when otherwise a move would be permissable. In this example, inner is a copy of the integer from val and changing it has no effect on val:

fn main() {
    let mut val = Some(42);

    if let &mut Some(mut inner) = &mut val {
        inner += 1;
    }

    println!("{:?}", val); // Some(42)
}

需要 ref 关键字来强制引用:

The ref keyword is needed to force taking a reference:

fn main() {
    let mut val = Some(42);

    if let &mut Some(ref mut inner) = &mut val {
        *inner += 1;
    }

    println!("{:?}", val); // Some(43)
}

匹配人体工程学允许以更简单的方式编写代码:

Match ergonomics allows writing this in a simpler manner:

fn main() {
    let mut val = Some(42);

    if let Some(inner) = &mut val {
        *inner += 1;
    }

    println!("{:?}", val);
}

但是,如果我们仅以这种语法开头,那么我们可能会遇到相反的问题和关键字,一个是强制移动.也许 Some(向内移动).在那个替代的宇宙中,会有一个问题问 move 关键字是否可以避免.

However, if we started with only this syntax, then we'd probably have the opposite problem and keyword, one to force a move instead; perhaps Some(move inner). In that alternate universe, there'd be a question asking if the move keyword was avoidable.

另请参阅:

这篇关于ref不能做什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆