ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.