ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.