// rust/01-basic-generics.rs/*Basic generic patterns and best practices for Rust*/usestd::fmt::Display;usestd::cmp::PartialOrd;/// Generic data structure.pubstructContainer<T>{data:T,}impl<T>Container<T>{pubfnnew(data:T)->Self{Self{data}}pubfnget(&self)->&T{&self.data}pubfnget_mut(&mutself)->&mutT{&mutself.data}pubfninto_inner(self)->T{self.data}}/// Generic function with trait bounds.pubfnfind_max<T>(items:&[T])->Option<&T>whereT:PartialOrd,{items.iter().max_by(|a,b|a.partial_cmp(b).unwrap())}/// Generic function with multiple trait bounds.pubfnprint_and_return<T>(item:T)->TwhereT:Display+Clone,{println!("Item: {}",item);item}/// Generic struct with trait bounds.pubstructSortedContainer<T>whereT:PartialOrd+Clone,{items:Vec<T>,}impl<T>SortedContainer<T>whereT:PartialOrd+Clone,{pubfnnew()->Self{Self{items:Vec::new()}}pubfninsert(&mutself,item:T){self.items.push(item);self.items.sort_by(|a,b|a.partial_cmp(b).unwrap());}pubfnget_items(&self)->&[T]{&self.items}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_container(){letcontainer=Container::new(42);assert_eq!(*container.get(),42);}#[test]fntest_find_max(){letnumbers=vec![1,5,3,9,2];assert_eq!(find_max(&numbers),Some(&9));}#[test]fntest_sorted_container(){letmutcontainer=SortedContainer::new();container.insert(3);container.insert(1);container.insert(2);letitems=container.get_items();assert_eq!(items,&[1,2,3]);}}
// rust/02-trait-patterns.rs/*Trait patterns and best practices for Rust*/usestd::fmt::Display;/// Basic trait definition.pubtraitDrawable{fndraw(&self);fnarea(&self)->f64;}/// Trait with default implementation.pubtraitDrawableWithDefault{fndraw(&self){println!("Drawing default shape");}fnarea(&self)->f64;fnperimeter(&self)->f64{0.0}}/// Trait with associated types.pubtraitIterator{typeItem;fnnext(&mutself)->Option<Self::Item>;}/// Trait with generic parameters.pubtraitProcessor<T>{fnprocess(&self,item:T)->T;}/// Trait with lifetime parameters.pubtraitParser<'a>{fnparse(&self,input:&'astr)->Result<&'astr,&'astr>;}/// Trait with multiple bounds.pubtraitComplexTrait:Display+Clone+PartialEq{fncomplex_method(&self)->String;}/// Trait with generic associated types.pubtraitContainer{typeItem;typeIterator<'a>:Iterator<Item=&'aSelf::Item>whereSelf:'a;fniter(&self)->Self::Iterator<'_>;}/// Demonstrates trait implementation.pubstructCircle{radius:f64,}implDrawableforCircle{fndraw(&self){println!("Drawing circle with radius {}",self.radius);}fnarea(&self)->f64{std::f64::consts::PI*self.radius*self.radius}}implDrawableWithDefaultforCircle{fnarea(&self)->f64{std::f64::consts::PI*self.radius*self.radius}fnperimeter(&self)->f64{2.0*std::f64::consts::PI*self.radius}}implDisplayforCircle{fnfmt(&self,f:&mutstd::fmt::Formatter<'_>)->std::fmt::Result{write!(f,"Circle(radius: {})",self.radius)}}implCloneforCircle{fnclone(&self)->Self{Self{radius:self.radius}}}implPartialEqforCircle{fneq(&self,other:&Self)->bool{(self.radius-other.radius).abs()<1e-10}}implComplexTraitforCircle{fncomplex_method(&self)->String{format!("Complex circle: {}",self)}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_circle_drawable(){letcircle=Circle{radius:5.0};circle.draw();assert!((circle.area()-78.54).abs()<1.0);}#[test]fntest_circle_display(){letcircle=Circle{radius:5.0};letdisplay=format!("{}",circle);assert!(display.contains("Circle"));}}
// rust/03-advanced-generics.rs/*Advanced generic patterns and best practices for Rust*/usestd::marker::PhantomData;usestd::ops::{Add,Mul};/// Generic function with complex bounds.pubfnprocess_items<T,U,F>(items:&[T],processor:F)->Vec<U>whereT:Clone,F:Fn(T)->U,{items.iter().map(|item|processor(item.clone())).collect()}/// Generic struct with phantom data.pubstructPhantomContainer<T>{data:Vec<u8>,_phantom:PhantomData<T>,}impl<T>PhantomContainer<T>{pubfnnew()->Self{Self{data:Vec::new(),_phantom:PhantomData,}}pubfnadd_data(&mutself,data:u8){self.data.push(data);}pubfnget_data(&self)->&[u8]{&self.data}}/// Generic trait with associated types.pubtraitConverter{typeInput;typeOutput;fnconvert(&self,input:Self::Input)->Self::Output;}/// Generic struct implementing Converter.pubstructStringToIntConverter;implConverterforStringToIntConverter{typeInput=String;typeOutput=i32;fnconvert(&self,input:String)->i32{input.parse().unwrap_or(0)}}/// Generic function with trait bounds.pubfncalculate<T>(a:T,b:T)->TwhereT:Add<Output=T>+Mul<Output=T>+Copy,{a*b+a+b}/// Generic struct with multiple type parameters.pubstructPair<T,U>{first:T,second:U,}impl<T,U>Pair<T,U>{pubfnnew(first:T,second:U)->Self{Self{first,second}}pubfnget_first(&self)->&T{&self.first}pubfnget_second(&self)->&U{&self.second}}/// Generic enum.pubenumResult<T,E>{Ok(T),Err(E),}impl<T,E>Result<T,E>{pubfnis_ok(&self)->bool{matches!(self,Result::Ok(_))}pubfnis_err(&self)->bool{matches!(self,Result::Err(_))}}#[cfg(test)]modtests{usesuper::*;#[test]fntest_process_items(){letnumbers=vec![1,2,3,4,5];letdoubled:Vec<i32>=process_items(&numbers,|x|x*2);assert_eq!(doubled,vec![2,4,6,8,10]);}#[test]fntest_phantom_container(){letmutcontainer:PhantomContainer<String>=PhantomContainer::new();container.add_data(42);assert_eq!(container.get_data(),&[42]);}#[test]fntest_converter(){letconverter=StringToIntConverter;letresult=converter.convert("123".to_string());assert_eq!(result,123);}#[test]fntest_calculate(){letresult=calculate(2,3);assert_eq!(result,11);// 2*3 + 2 + 3 = 11}#[test]fntest_pair(){letpair=Pair::new("hello",42);assert_eq!(*pair.get_first(),"hello");assert_eq!(*pair.get_second(),42);}}