MST

星途 面试题库

面试题:Rust特征中泛型的基础使用

请编写一个Rust特征 `Printable`,它有一个关联类型 `Item` 作为泛型,并且包含一个方法 `print_item`,用于打印关联类型的实例。然后创建一个结构体实现这个特征。
25.2万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
trait Printable {
    type Item;
    fn print_item(&self, item: Self::Item);
}

struct Printer;

impl Printable for Printer {
    type Item = i32;
    fn print_item(&self, item: Self::Item) {
        println!("The item is: {}", item);
    }
}