Q:

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

belongs to collection: Rust Generics Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to calculate the subtract a number fr... >>
<< Rust program to find the square of a given number ...