例子1
fn largest_i32(list:&[i32])->&i32 {
let mut largest=&list[0];
for item in list{
if item > largest{
largest=item;
}
}
largest
}
fn largest_char(list:&[char])->&char{
let mut largest = &list[0];
for item in list {
if item>largest{
largest=item;
}
}
largest
}
fn main() {
let number_list=vec![34,50,25,100,65];
let result=largest_i32(&number_list);
println!("The largest number is {}",result);
let char_list=vec!['y','m','a','q'];
let result=largest_char(&char_list);
println!("The largest char is {}",result);
}
例子2
fn largest<T:std::cmp::PartialOrd>(list:&[T])->&T {
let mut largest=&list[0];
for item in list{
if item > largest{
largest=item;
}
}
largest
}
fn main() {
let number_list=vec![34,50,25,100,65];
let result=largest(&number_list);
println!("The largest number is {}",result);
let char_list=vec!['y','m','a','q'];
let result=largest(&char_list);
println!("The largest char is {}",result);
}
例子3
struct Point<T>{
x:T,
y:T,
}
fn main() {
let integer=Point{x:5,y:10};
let float=Point{x:1.0,y:4.0};
}
例子4
struct Point<T,U>{
x:T,
y:U,
}
fn main() {
let integer=Point{x:5,y:10.0};
let float=Point{x:1,y:4.0};
}
例子5,枚举中的泛型
enum Option<T> {
Some(T),
None,
}
enum Result<T,E> {
Ok(T),
Err(E),
}
例子6,方法定义中的泛型
struct Point<T>{
x:T,
y:T,
}
impl <T> Point<T> {
fn x(&self)->&T{
&self.x
}
}
fn main() {
let p = Point{x:5,y:10};
println!("p.x={}",p.x());
}
例子7
struct Point<X1,Y1>{
x:X1,
y:Y1
}
impl<X1,Y1> Point<X1,Y1> {
fn mixup<X2,Y2>(self,other:Point<X2,Y2>)->Point<X1,Y2>{
Point{
x:self.x,
y:other.y,
}
}
}
fn main(){
let p1=Point{x:5,y:10.4};
let p2=Point{x:"Hello",y:'c'};
let p3=p1.mixup(p2);
println!("p3.x={},p3.y={}",p3.x,p3.y);
}
Rust基础之泛型
最新推荐文章于 2024-11-08 23:27:36 发布