Find the square of a given number using a generic function
Rust Programming Language
Problem
In this program, we will create a generic function to calculate the square of a given number and print the result.
Input
// Rust program to find the square of a given number// using a generic functionuse std::ops::Mul;fn getsquare<T: Mul<Output = T> + Copy> (num: T) -> T {return num * num;}fn main() {let sqr1 = getsquare(6);println!("Square is: {:?}", sqr1);let sqr2 = getsquare(6.23);println!("Square is: {:?}", sqr2);}{codeBox}
Output
Square is: 36Square is: 38.812900000000006{codeBox}
Explanation
In the above program, we created a generic function to calculate the square of the given number. The generic function is given below,
fn getsquare<T: Mul<Output = T> + Copy> (num: T) -> T {return num * num;}{codeBox}
In the main() function, we called the getsquare() function and printed the square of the specified number.