Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Problems
  • C
  • C++
  • Java
  • Python
  • JavaScript
  • Data Science
  • Machine Learning
  • Courses
  • Linux
  • DevOps
  • SQL
  • Web Development
  • System Design
  • Aptitude
  • GfG Premium
Open In App
Next Article:
Rust - Generic Function
Next article icon

Rust - Generic Function

Last Updated : 09 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In Rust, Generic functions are very useful. Generic make code more flexible and provide more functionality to the callers of the function. It prevents code duplication as it is not required to define different functions of different types. Generics are specified in the signature of function where we actually specify the datatype of parameters and return type.

Let's look into an example of normal functions:

fn sampleFunction1(varX:i32)->i32{

// this function accepts integer and return an integer

...................

....................

}

fn sampleFunction2(varX:f64)->f64{

......

......

// accepts float and return float

// same functionality of above function

}

Above are the two functions which are having same functionality but due to difference in the type of parameters and return type, two functions are defined. But the generic function will help us define the function once and use it with multiple types.

Syntax:

fn functionName<T>(variable_name1 : T, variable_name2 : T ,...) -> T { ...... ...... } where T represents the generic type. variable_name1,  variable_name2 are parameters of type generic. The function will return a value of the same type T. Let's look at the coding part of using a generic function.

Let's see another example to write a program to add two numbers of the same type in Rust.

Example 1:

Rust
// Rust code for addition fn main() {     println!("Addition between 10 & 20 is {}", sumGeneric(10,20));//30     println!("Addition between 10.1 & 20.3 is {}", sumGeneric(10.1,20.3));//30.4 }  // generic function that add two numbers use std::ops::Add; fn sumGeneric<T:Add<Output = T> + Copy> (a: T, b: T) -> T {     return a + b; } 

Output:

 

If we didn't used the generic function then we need to write two different functions where one function accepts integers and return an integer and other function that accepts floating point numbers and return floating point result. So here Generic function helps us to avoid code redundancy.

Let's look at the another example of generic function for better understanding.

Example 2:

Rust
// Rust program to find the largest number among 3 numbers. fn main() {     println!("Greatest among 1, 2, 3 is {}",greater(1,2,3));     println!("Greatest among 1.2, 7.2, 3.0 is {}",greater(1.2,7.2,3.0));     println!("Greatest among 10, 20, 30 is {}",greater(10,20,30)); } fn greater<T:PartialOrd>(a:T,b:T,c:T)->T{   if a>b && a>c{     return a;   }   else if b>a && b>c{     return b;   }   else{     return c;   } } 

Output:

 

In the above code, inside the generic function we used PartialOrd represents the ordered trait that allows the parameters in the function to be compared. The advantage of using Generic function is it helps to prevent code duplication and make code looks more organized and concise. 


Next Article
Rust - Generic Function

A

akhilvasabhaktula03
Improve
Article Tags :
  • Rust
  • Rust functions

Similar Reads

    Functions in Rust
    Functions are the block of reusable code that can perform similar related actions. You have already seen one of the most important functions in the language: the main function, which is the entry point of many programs. You’ve also seen the "fn" keyword, which allows you to declare new functions. Ru
    4 min read
    TypeScript Generic Functions
    TypeScript generic functions allow you to create functions that work with various types while maintaining type safety. By using type parameters, defined within angle brackets (<T>), generics enable functions to operate on different data types without losing the benefits of TypeScript's type-ch
    3 min read
    Rust - Higher Order Functions
    In Rust, we have a concept of Higher order functions that passes the function to another function once the variable is stored in another function. To define a function in Rust, we use the fn keyword. Syntax: fn <function name>() { } Higher-order functions in Rust are those functions that take
    2 min read
    Rust - Generics
    Generics in Rust is a method of generalizing data types. Generics are always defined at run time. As generics can have multiple forms over given parameters and can be applied to methods, functions, structures, traits, etc they are often referred to as parametric polymorphism in type theory. Generics
    2 min read
    Rust - Casting
    Type Conversion or casting in Rust is a way to convert one type to another. As its name suggests, type conversion is the process of converting variables from one data type to another. So that, the compiler treats the variable as a new datatype. Rust doesn't allow us to implicitly convert the datatyp
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences