# 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

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

fn main() {
let result1 = Sum(10,20);

let result2 = Sum(10.23,20.45);
}
```

Output:

```Addition is: 30
```

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.

Preparation

What's New

Top Interview Coding Problems/Challenges!