面试题答案
一键面试- 通过特征约束函数参数类型的方式:
- 在Rust中,可以在函数定义时,使用特征界限(trait bound)来约束函数参数的类型,确保传入的参数类型实现了特定的特征。
- 示例代码:
// 定义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);
}