Does Rust automatically dereference primitive type

2019-03-26 01:25发布

问题:

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.

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?

回答1:

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.

You'll see something like:

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

and so on and so on.

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