Rust program to calculate the addition of two numbers using generic function

Rust | Generics Example: Write a program to calculate the addition of two numbers using generic function.
Submitted by Nidhi, on November 23, 2021

Problem Solution:

In this program, we will create a generic function to calculate the addition of a given number and print the result.

Program/Source Code:

The source code to calculate the addition of two numbers using a generic function is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to calculate the addition 
// of two numbers using generic function

use std::ops::Add;

fn Sum<T:Add<Output = T> + Copy> (num1: T, num2: T) -> T {
    return num1 + num2;
}

fn main() {
    let result1 = Sum(10,20);
    println!("Addition is: {:?}", result1);
    
    let result2 = Sum(10.23,20.45);
    println!("Addition is: {:?}", result2);
}

Output:

Addition is: 30
Addition is: 30.68

Explanation:

In the above program, we created a generic function to calculate the addition of given numbers. The generic function is given below,

fn Sum<T:Add<Output = T> + Copy> (num1: T, num2: T) -> T {
    return num1 + num2;
}

In the main() function, we called the Sum() function and printed the addition of specified numbers.

Rust Generics Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.