Q:

Rust program to find the square of a given number using a generic function

belongs to collection: Rust Generics Programs

0

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

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

total answers (1)

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