The source code to find the square of a given number using a generic function is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.
// Rust program to find the square of a given number
// using a generic function
use 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);
}
Output:
Square is: 36
Square is: 38.812900000000006
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;
}
In the main() function, we called the getsquare() function and printed the square of the specified number.
Program/Source Code:
The source code to find the square of a given number using a generic function is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.
Output:
Explanation:
In the above program, we created a generic function to calculate the square of the given number. The generic function is given below,
In the main() function, we called the getsquare() function and printed the square of the specified number.
need an explanation for this answer? contact us directly to get an explanation for this answer