# Rust program to calculate the subtract a number from another number using generic function

Rust | Generics Example: Write a program to calculate the subtract a number from another number using generic function.
Submitted by Nidhi, on November 23, 2021

Problem Solution:

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

Program/Source Code:

The source code to calculate the subtraction 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 subtract a number
// from another number using generic function

use std::ops::Sub;

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

fn main() {
let result1 = Subtract(40,20);
println!("Subtraction is: {:?}", result1);

let result2 = Subtract(40.23,20.45);
println!("Subtraction is: {:?}", result2);
}
```

Output:

```Subtraction is: 20
Subtraction is: 19.779999999999998
```

Explanation:

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

```fn Subtract<T:Sub<Output = T> + Copy> (num1: T, num2: T) -> T {
return num1 - num2;
}
```

In the main() function, we called the Subtract() function and printed the result.

Preparation

What's New

Top Interview Coding Problems/Challenges!