Rust – Generics
Last Updated :
08 Sep, 2022
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 allow writing clean and concise code thereby providing type safety and refactored code.
In Generics, we have <T> as the type parameter which is used to declare a generic construct T. T can be of any data type.
Now we see an example for generic collections, we create a vector that has an integer of i32 type.
Example 1:
Rust
fn main(){
let mut _int_vector: Vec<i32> = vec![10,20];
_int_vector.push(30);
println!( "{:?}" ,_int_vector);
}
|
Output:
The <T> type indicates the generic type specifier for the Data.
Example 2:
Rust
struct Data<T> {
value:T,
}
fn main() {
let type1:Data<String> = Data{value: "GFG" .to_string()};
println!( "Organization :{} " ,type1.value);
let type2:Data<i32> = Data{value:2022};
println!( "Year :{} " ,type2.value);
}
|
Output:
Here, the merge function takes a value of the string as well as takes a value of i32. T is the generic type specifier.
Example 3:
Rust
fn main(){
println!( "****** Passing String literals*******" );
merge( "Geeks for " , " Geeks " );
println!( "******** Passing an integer ***********" );
merge(20 as i32, 22 as i32);
}
use std::fmt::Display;
fn merge<T:Display>(t:T, s:T){
let result = format!( "{}{}" , t , s);
println!( "{}" , result);
}
|
Output:
Share your thoughts in the comments
Please Login to comment...