Rust语言

关注公众号 jb51net

关闭
首页 > 软件编程 > Rust语言 > Rust泛型编程

Rust泛型编程深入实例介绍应用技巧

作者:第一程序员

这篇文章主要介绍了Rust泛型编程,泛型是Rust中一种强大的特性,它允许我们编写通用的代码,适用于不同类型,通过掌握泛型的高级应用,我们可以编写更加灵活、可复用的代码,需要的朋友可以参考下

1. 泛型基础

泛型是 Rust 中一种强大的特性,它允许我们编写通用的代码,适用于不同类型。

// 泛型函数
fn add<T: std::ops::Add<Output = T>>(a: T, b: T) -> T {
    a + b
}
fn main() {
    println!("1 + 2 = {}", add(1, 2));
    println!("1.5 + 2.5 = {}", add(1.5, 2.5));
}

2. 高级泛型技巧

2.1 泛型结构体

// 泛型结构体
struct Point<T> {
    x: T,
    y: T,
}
impl<T> Point<T> {
    fn new(x: T, y: T) -> Self {
        Self { x, y }
    }
    fn x(&self) -> &T {
        &self.x
    }
}
// 为特定类型实现方法
impl Point<i32> {
    fn distance_from_origin(&self) -> f64 {
        ((self.x * self.x + self.y * self.y) as f64).sqrt()
    }
}
fn main() {
    let p1 = Point::new(1, 2);
    let p2 = Point::new(1.5, 2.5);
    println!("p1.x = {}", p1.x());
    println!("p2.x = {}", p2.x());
    println!("p1 distance from origin: {}", p1.distance_from_origin());
}

2.2 泛型枚举

// 泛型枚举
enum Option<T> {
    Some(T),
    None,
}
enum Result<T, E> {
    Ok(T),
    Err(E),
}
fn main() {
    let some_number = Option::Some(5);
    let some_string = Option::Some("hello");
    let none = Option::None;
    match some_number {
        Option::Some(value) => println!("Value: {}", value),
        Option::None => println!("No value"),
    }
}

2.3 泛型 trait

// 泛型 trait
trait Iterator {
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}
// 实现泛型 trait
struct Counter {
    count: u32,
}
impl Iterator for Counter {
    type Item = u32;
    fn next(&mut self) -> Option<Self::Item> {
        if self.count < 5 {
            self.count += 1;
            Some(self.count)
        } else {
            None
        }
    }
}
fn main() {
    let mut counter = Counter { count: 0 };
    while let Some(value) = counter.next() {
        println!("Value: {}", value);
    }
}

2.4 泛型边界

// 泛型边界
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];
    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }
    largest
}
fn main() {
    let numbers = vec![34, 50, 25, 100, 65];
    let result = largest(&numbers);
    println!("The largest number is {}", result);
    let chars = vec!['y', 'm', 'a', 'q'];
    let result = largest(&chars);
    println!("The largest char is {}", result);
}

3. 实际应用场景

3.1 容器类型

// 泛型容器
struct Stack<T> {
    items: Vec<T>,
}
impl<T> Stack<T> {
    fn new() -> Self {
        Self { items: Vec::new() }
    }
    fn push(&mut self, item: T) {
        self.items.push(item);
    }
    fn pop(&mut self) -> Option<T> {
        self.items.pop()
    }
    fn is_empty(&self) -> bool {
        self.items.is_empty()
    }
}
fn main() {
    let mut stack = Stack::new();
    stack.push(1);
    stack.push(2);
    stack.push(3);
    while !stack.is_empty() {
        println!("Popped: {:?}", stack.pop());
    }
}

3.2 函数包装器

// 泛型函数包装器
fn with_logging<F, R>(func: F) -> R
where
    F: Fn() -> R,
{
    println!("Before function call");
    let result = func();
    println!("After function call");
    result
}
fn main() {
    let result = with_logging(|| {
        println!("Inside function");
        42
    });
    println!("Result: {}", result);
}

3.3 类型转换

// 泛型类型转换
trait From<T> {
    fn from(value: T) -> Self;
}
trait Into<T> {
    fn into(self) -> T;
}
// 为 String 实现 From<&str>
impl From<&str> for String {
    fn from(s: &str) -> Self {
        s.to_string()
    }
}
// 为所有类型实现 Into
impl<T, U> Into<U> for T
where
    U: From<T>,
{
    fn into(self) -> U {
        U::from(self)
    }
}
fn main() {
    let s: String = "hello".into();
    println!("String: {}", s);
}

3.4 多态

// 泛型多态
trait Draw {
    fn draw(&self);
}
struct Circle {
    radius: f64,
}
struct Rectangle {
    width: f64,
    height: f64,
}
impl Draw for Circle {
    fn draw(&self) {
        println!("Drawing a circle with radius {}", self.radius);
    }
}
impl Draw for Rectangle {
    fn draw(&self) {
        println!("Drawing a rectangle with width {} and height {}", self.width, self.height);
    }
}
// 泛型函数,接受任何实现了 Draw trait 的类型
fn draw_shape<T: Draw>(shape: T) {
    shape.draw();
}
fn main() {
    let circle = Circle { radius: 5.0 };
    let rectangle = Rectangle { width: 10.0, height: 20.0 };
    draw_shape(circle);
    draw_shape(rectangle);
}

4. 最佳实践

5. 总结

泛型是 Rust 中一种强大的特性,它允许我们编写通用的代码,适用于不同类型。通过掌握泛型的高级应用,我们可以编写更加灵活、可复用的代码。

在实际应用中,泛型可以用于容器类型、函数包装器、类型转换和多态等多种场景,大大提高代码的复用性和可维护性。

希望本文对你理解和应用 Rust 泛型编程有所帮助!

以上就是Rust泛型编程深入实例介绍应用技巧的详细内容,更多关于Rust泛型编程的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文