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

Rust | Generics Example: Write a program to find the square of a given number using a generic function.
Submitted by Nidhi, on November 23, 2021

Problem Solution:

In this program, we will create a generic function to calculate the square of a given number and print the result.

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.

Rust Generics Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.