Rust 是否会自动取消引用原始类型引用? [英] Does Rust automatically dereference primitive type references?

查看:45
本文介绍了Rust 是否会自动取消引用原始类型引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Rust 的新手,正在尝试学习引用是如何工作的.在下面的代码中,当我想对 a1i32 进行计算时,我不必取消引用它.但是对于 b1 这是一个 Box,我必须取消引用它.

I'm new to Rust and trying to learn how references work. In the following code when I want to do a calculation on a1 which is i32 I don't have to dereference it. But with b1 which is a Box, I have to dereference it.

实际上 let a2 = a1 * 2;let a3 = *a1 * 2; 的行为相似.看起来原语中的取消引用是可选的,或者编译器隐式地为我们做这件事.

Actually both let a2 = a1 * 2; and let a3 = *a1 * 2; behave similarly. It looks like dereferencing in primitives is optional OR the compiler is implicitly doing that for us.

fn main(){
    let a = 5;
    let b = Box::new(10);
    let a1 = &a;
    let b1 = &b;

    println!("{} {}", a1, b1);

    let a2 = a1 * 2;
    let b2 = (**b1) * 10;
    let a3 = *a1 * 2;

    println!("{} {} {}", a2, a3, b2);

}

有人可以解释一下这个功能吗?

Can someone please explain this functionality?

推荐答案

Rust 中的所有算术运算符都是为原始值和运算符任一侧的原始值引用实现的.例如,请参阅 Implementors 部分>std::ops::Mul,控制覆盖 * 操作符的特征.

All of the arithmetic operators in Rust are implemented for both primitive values and references to primitives on either side of the operator. For example, see the Implementors section of std::ops::Mul, the trait that controls the overriding of the * operator.

您会看到如下内容:

impl Mul<i32> for i32
impl<'a> Mul<i32> for &'a i32
impl<'a> Mul<&'a i32> for i32
impl<'a, 'b> Mul<&'a i32> for &'b i32

等等等等.

在您的示例中,b1 的类型为 &Box(默认整数类型),而 Box 实现许多特征作为其包含类型的传递(例如 impl Read for Box),算术运算符不在其中.这就是为什么您必须取消对框的引用.

In your example, b1 has a type of &Box<i32> (the default integer type), and while Box implements many traits as a passthrough for its contained type (e.g. impl<T: Read> Read for Box<T>), the arithmetic operators are not among them. That is why you have to dereference the box.

这篇关于Rust 是否会自动取消引用原始类型引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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