Rustコトハジメ

プログラミング言語Rustに関する情報をお届けします。

How reference of integer is able to add

Are you surprised by this code? If you are a C/C++ programmer you should be.

fn main() {
    let a = 5;
    let b = 3;
    println!("{},{},{},{}", a+b, a+&b, &a+b, &a+&b)
}

To surprise the output is

8,8,8,8

The trick behind this behavior is macros: Arithmetic operations are generated by macros. In Rust's standard library, macros are widely used for DRY reason.

macro_rules! add_impl {
    ($($t:ty)*) => ($(
        #[stable(feature = "rust1", since = "1.0.0")]
        impl Add for $t {
            type Output = $t;

            #[inline]
            #[rustc_inherit_overflow_checks]
            fn add(self, other: $t) -> $t { self + other }
        }

        forward_ref_binop! { impl Add, add for $t, $t }
    )*)
}
add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }

// implements binary operators "&T op U", "T op &U", "&T op &U"
// based on "T op U" where T and U are expected to be `Copy`able
macro_rules! forward_ref_binop {
    (impl $imp:ident, $method:ident for $t:ty, $u:ty) => {
        forward_ref_binop!(impl $imp, $method for $t, $u,
                #[stable(feature = "rust1", since = "1.0.0")]);
    };
    (impl $imp:ident, $method:ident for $t:ty, $u:ty, #[$attr:meta]) => {
        #[$attr]
        impl<'a> $imp<$u> for &'a $t {
            type Output = <$t as $imp<$u>>::Output;

            #[inline]
            fn $method(self, other: $u) -> <$t as $imp<$u>>::Output {
                $imp::$method(*self, other)
            }
        }
        ....

As the document says, it generates &T + U, T + &U and &T + &U from the base T + U.

But how does this actually help you? The following code is compilable because of this. The type of argument x in closure is &i32 and compiler applies&i32 + i32 to result in integer output.

fn main() {
    let v1 = vec![1,2,3];
    let v2: Vec<i32> = v1.iter().map(|x| x + 1).collect();
    println!("{:?}", v2);
}
[2, 3, 4]