MST

星途 面试题库

面试题:Rust中特征如何约束函数参数类型

请说明在Rust中,如何通过特征来约束函数参数的类型。并给出一个具体的示例代码,例如定义一个特征`Drawable`,有`draw`方法,然后定义一个函数`draw_all`,它接受一个实现了`Drawable`特征的类型的切片作为参数,在函数内部调用每个元素的`draw`方法。
13.4万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
  1. 通过特征约束函数参数类型的方式
    • 在Rust中,可以在函数定义时,使用特征界限(trait bound)来约束函数参数的类型,确保传入的参数类型实现了特定的特征。
  2. 示例代码
// 定义Drawable特征
trait Drawable {
    fn draw(&self);
}

// 定义一个结构体并实现Drawable特征
struct Rectangle {
    width: u32,
    height: u32,
}

impl Drawable for Rectangle {
    fn draw(&self) {
        println!("Drawing a rectangle with width {} and height {}", self.width, self.height);
    }
}

// 定义一个结构体并实现Drawable特征
struct Circle {
    radius: u32,
}

impl Drawable for Circle {
    fn draw(&self) {
        println!("Drawing a circle with radius {}", self.radius);
    }
}

// 定义draw_all函数,接受实现了Drawable特征的类型的切片作为参数
fn draw_all<T: Drawable>(shapes: &[T]) {
    for shape in shapes {
        shape.draw();
    }
}

你可以这样使用这个函数:

fn main() {
    let rect1 = Rectangle { width: 10, height: 5 };
    let rect2 = Rectangle { width: 20, height: 15 };
    let circle1 = Circle { radius: 5 };

    let shapes: Vec<Box<dyn Drawable>> = vec![
        Box::new(rect1),
        Box::new(rect2),
        Box::new(circle1),
    ];

    draw_all(&shapes);
}