Hello Guys! Now, You are going to subtract two numbers using a generic function in rust program. Firstly I wish to share about rust generic function. It is nothing but describes anything that accepts one or more generic type parameters <T>.
Rust program to calculate the subtract a number from another number using generic function
This is a source code for subtract two numbers in rust program using the generic function.
// 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);
}
Program Execution
- Initially, You need to create the generic function to subtract two numbers like given below:
fn Subtract<T:Sub<Output = T> + Copy> (num1: T, num2: T) -> T {
return num1 - num2;
}
2. After that, The two given numbers will be subtracted using the main subtract() function and the output will be displayed on the screen using the printIn() function.
output
Subtraction is: 20
Subtraction is: 19.779999999999998
Conclusion
I hope this tutorial will help you to learn “Rust Program to Calculate the Subtract a Number From Another Number Using Generic Function“. If you need any help regarding this topic please ask us via the comment section. We are ready to help you. Don’t forget to share this article and bookmark us.
Table of Contents