Does Rust automatically look for primitive link types?

I'm new to Rust and trying to find out how links work. In the following code, when I want to perform a calculation on a1 , which is i32 , I do not need to i32 it. But with b1 , which is Box , I have to dereference it.

In fact, both let a2 = a1 * 2; and let a3 = *a1 * 2; behave in a similar way. It seems that dereferencing in primitives is optional OR the compiler implicitly does this 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 explain this functionality?

+7
rust
source share
1 answer

All arithmetic operators in Rust are implemented both for primitive values ​​and for references to primitives on both sides of the operator. For example, see the Implementors Section std::ops::Mul , a tag that controls operator overrides * .

You will 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 

etc. etc.

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

+5
source share

All Articles