ADVERTISEMENT
ADVERTISEMENT

Rust program to create a generic function

Rust | Generics Example: Write a program to create a generic function.
Submitted by Nidhi, on November 23, 2021

Problem Solution:

In this program, we will create a generic function that can accept any type of parameter.

Program/Source Code:

The source code to create a generic function is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to create a generic function

use std::fmt::Display;

fn genric_fun<T:Display>(n1:T,n2:T){
   println!("Number1: {}",n1);
   println!("Number2: {}",n2);
}

fn main(){
   genric_fun(10 as u32, 20 as u32);
   genric_fun(10.23 as f32, 20.56 as f32);
}

Output:

Number1: 10
Number2: 20
Number1: 10.23
Number2: 20.56

Explanation:

In the above program, we created a generic function that can accept any type of parameter. The generic function is given below,

fn genric_fun<T:Display>(n1:T,n2:T){
   println!("Number1: {}",n1);
   println!("Number2: {}",n2);
}

In the main() function, we called the genric_fun() function with different types of parameters and printed them.

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.