我有一个接受通用类型T的结构Character。我无法弄清楚如何为Character实现fmt :: Display特征。这是我尝试过的:
pub struct Character<T> {
pub name: String,
pub level: u32,
pub class: T,
pub attack: i32,
pub defense: i32,
pub speed: i32,
}
impl fmt::Display for Character<T> {
// Display trait for Player
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{}] {} (Lv {})", self.class, self.name, self.level)
}
}
错误指出在impl fmt::Display for Character<T>
行的范围内找不到T
我已经尝试搜索您将如何执行此操作,但我无法弄清楚。
答案 0 :(得分:1)
use std::fmt;
impl<T> fmt::Display for Character<T>
where
T: fmt::Display,
{
// Display trait for Player
fn fmt(&self, f: &mut std::fmt::Formatter) -> fmt::Result {
write!(f, "[{}] {} (Lv {})", self.class, self.name, self.level)
}
}
impl<T>
指出以下是一些通用的实现(与Character
一样)where T: std::fmt::Display
要求T
实现Display
。这是必需的,因为您要write
self.class
,类型为T