面试题答案
一键面试设计思路
- 分层抽象:将通用的输出逻辑抽象出来,针对不同类型的特定格式需求,通过 trait 的默认实现和覆写来处理。
- 利用泛型:使得方案具有通用性,可以应用到项目中的各种自定义类型。
- 模块化管理:将 trait 的实现和相关逻辑分布在合适的模块中,便于维护和复用。
关键实现步骤
-
定义基础 trait:
pub trait CustomDisplay { fn custom_display(&self) -> String; }
此 trait 定义了一个方法
custom_display
,用于返回特定格式的字符串。 -
为
Display
trait 提供默认实现:use std::fmt; impl fmt::Display for dyn CustomDisplay { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.custom_display()) } }
这样所有实现了
CustomDisplay
trait 的类型都自动实现了Display
trait。 -
在各个自定义类型中实现
CustomDisplay
trait:struct SpecificType { // 类型成员 } impl CustomDisplay for SpecificType { fn custom_display(&self) -> String { // 特定输出格式逻辑 "SpecificType output".to_string() } }
不同的自定义类型根据自身需求实现
custom_display
方法。 -
模块整合: 将
CustomDisplay
trait 的定义和Display
trait 的默认实现放在一个公共模块中,各个自定义类型所在模块引入此公共模块,并实现CustomDisplay
trait,以确保整个项目的一致性和复用性。