面试题答案
一键面试// 定义泛型trait Drawable,包含关联类型Color
trait Drawable {
type Color;
fn draw(&self, color: Self::Color);
}
// 实现Drawable trait的结构体
struct Rectangle;
// 为Rectangle结构体实现Drawable trait
impl Drawable for Rectangle {
type Color = String;
fn draw(&self, color: Self::Color) {
println!("Drawing a rectangle with color: {}", color);
}
}
你可以使用以下方式测试这个代码:
fn main() {
let rect = Rectangle;
rect.draw("Red".to_string());
}