Q:

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

belongs to collection: Rust Generics Programs

0

In this program, we will create a generic function to calculate the subtraction 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 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.

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

total answers (1)

Rust program to create a generic structure... >>
<< Rust program to calculate the addition of two numb...