MST
星途 面试题库

面试题:Rust 中关联类型在泛型 trait 里的基础应用

请编写一个 Rust 程序,定义一个泛型 trait `Drawable`,其中包含一个关联类型 `Color`,并在实现 `Drawable` trait 的结构体中使用该关联类型,结构体需要有一个 `draw` 方法,该方法接受一个 `Color` 类型的参数并打印相关信息。
43.8万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 定义泛型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());
}