Trait core::ops::Add

pub trait Add {
    /// Add two values of the same type.
    ///
    /// # Arguments
    ///
    /// * `other`: [Self] - The value to add to self.
    ///
    /// # Returns
    ///
    /// * [Self] - The result of the two values added.
    ///
    /// # Examples
    ///
    /// ```sway
    /// struct MyStruct {
    ///     val: u64,
    /// }
    ///
    /// impl Add for MyStruct {
    ///     fn add(self, other: Self) -> Self {
    ///         let val = self.val + other.val;
    ///         Self {
    ///             val
    ///         }
    ///     }
    /// }
    ///
    /// fn foo() {
    ///     let struct1 = MyStruct { val: 1 };
    ///     let struct2 = MyStruct { val: 2 };
    ///     let result_struct = struct1 + struct2;
    ///     assert(result_struct.val == 3);
    /// }
    /// ```
    fn add(self, other: Self) -> Self;
}
Expand description

Trait for the addition of two values.

Required Methods

Add two values of the same type.

Arguments

  • other: [Self] - The value to add to self.

Returns

  • [Self] - The result of the two values added.

Examples

struct MyStruct {
    val: u64,
}

impl Add for MyStruct {
    fn add(self, other: Self) -> Self {
        let val = self.val + other.val;
        Self {
            val
        }
    }
}

fn foo() {
    let struct1 = MyStruct { val: 1 };
    let struct2 = MyStruct { val: 2 };
    let result_struct = struct1 + struct2;
    assert(result_struct.val == 3);
}