Rust 如何为具有trait对象成员的结构实现调试trait?

Rust 如何为具有trait对象成员的结构实现调试trait?,rust,traits,Rust,Traits,我的目标是打印包含trait对象成员的struct的内容,但我找不到如何告诉Rust编译器该成员还实现了其他特性,如Display或Debug 例如,在下面的程序中,我想打印S2(和S1的结构以进行比较),但我在fmt的实现中遇到了困难 trait Tr{} 使用{}的impl Tr 字符串{}的impl Tr #[导出(调试)] 结构S1{ 成员:框, } 结构S2{ 成员:框, } S2的impl std::fmt::调试{ fn fmt(&self,fmt:&mut std::fmt::F

我的目标是打印包含trait对象成员的struct的内容,但我找不到如何告诉Rust编译器该成员还实现了其他特性,如
Display
Debug

例如,在下面的程序中,我想打印
S2
(和
S1
的结构以进行比较),但我在
fmt
的实现中遇到了困难

trait Tr{}
使用{}的impl Tr
字符串{}的impl Tr
#[导出(调试)]
结构S1{
成员:框,
}
结构S2{
成员:框,
}
S2的impl std::fmt::调试{

fn fmt(&self,fmt:&mut std::fmt::Formatter您可以将
S2
设置为泛型,但不需要指定类型也应在此处实现
Debug
。相反,您可以在
impl
中指定它:

struct S2<A: Tr> {
    member: Box<A>,
}

impl<A: Tr + std::fmt::Debug> std::fmt::Debug for S2<A> {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(fmt, "S2 {{ member: {:?} }}", self.member)?;
        Ok(())
    }
}
struct S2{
成员:框,
}
S2的impl std::fmt::调试{
fn fmt(&self,fmt:&mut std::fmt::格式化程序
对于像
S2
这样的结构,是否可以实现
Debug

是的,你可以,这一点在

您需要为
S2
实现
Debug
特性,如下所示:

trait MyTrait {}
impl MyTrait for usize {}
impl MyTrait for String {}

trait MyTraitWritable: MyTrait + Debug {}
impl MyTraitWritable for usize {}
impl MyTraitWritable for String {}

impl std::fmt::Debug for S2 {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(fmt, "S2 {{ member: {:?} }}", self.member)
    }
}
trait MyTrait{}
使用{}的impl MyTrait
字符串{}的impl MyTrait
trait mytraitwriteable:MyTrait+Debug{}
impl MyTraitWritable for usize{}
字符串{}的impl MyTraitWritable
S2的impl std::fmt::调试{

fn fmt(&self,fmt:&mut std::fmt::Formatter
T
对于一个trait来说是个坏名字,因为如果我看到
Box
我希望
T
是一个通过struct提供的泛型类型参数,例如
struct S2{}
。应该是更长的
Result
-习惯上只使用
std::fmt::Result
@Shepmaster,修改了关于您的评论的答案。习惯上,它提供了一个
mytraitwitable
;类似于
impl mytraitwitable for T{}
(如链接副本所示)。